Bitcoin Core 30.99.0
P2P Digital Currency
blockchain.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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
8#include <blockfilter.h>
9#include <chain.h>
10#include <chainparams.h>
11#include <chainparamsbase.h>
12#include <clientversion.h>
13#include <coins.h>
14#include <common/args.h>
15#include <consensus/amount.h>
16#include <consensus/params.h>
18#include <core_io.h>
19#include <deploymentinfo.h>
20#include <deploymentstatus.h>
21#include <flatfile.h>
22#include <hash.h>
25#include <interfaces/mining.h>
26#include <kernel/coinstats.h>
27#include <logging/timer.h>
28#include <net.h>
29#include <net_processing.h>
30#include <node/blockstorage.h>
31#include <node/context.h>
32#include <node/transaction.h>
33#include <node/utxo_snapshot.h>
34#include <node/warnings.h>
36#include <rpc/server.h>
37#include <rpc/server_util.h>
38#include <rpc/util.h>
39#include <script/descriptor.h>
40#include <serialize.h>
41#include <streams.h>
42#include <sync.h>
43#include <tinyformat.h>
44#include <txdb.h>
45#include <txmempool.h>
46#include <undo.h>
47#include <univalue.h>
48#include <util/check.h>
49#include <util/fs.h>
50#include <util/strencodings.h>
51#include <util/syserror.h>
52#include <util/translation.h>
53#include <validation.h>
54#include <validationinterface.h>
55#include <versionbits.h>
56
57#include <cstdint>
58
59#include <condition_variable>
60#include <iterator>
61#include <memory>
62#include <mutex>
63#include <optional>
64#include <string>
65#include <string_view>
66#include <vector>
67
70
77
78std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex*>
80 Chainstate& chainstate,
81 const std::function<void()>& interruption_point = {})
83
85 Chainstate& chainstate,
86 CCoinsViewCursor* pcursor,
87 CCoinsStats* maybe_stats,
88 const CBlockIndex* tip,
89 AutoFile&& afile,
90 const fs::path& path,
91 const fs::path& temppath,
92 const std::function<void()>& interruption_point = {});
93
94/* Calculate the difficulty for a given block index.
95 */
96double GetDifficulty(const CBlockIndex& blockindex)
97{
98 int nShift = (blockindex.nBits >> 24) & 0xff;
99 double dDiff =
100 (double)0x0000ffff / (double)(blockindex.nBits & 0x00ffffff);
101
102 while (nShift < 29)
103 {
104 dDiff *= 256.0;
105 nShift++;
106 }
107 while (nShift > 29)
108 {
109 dDiff /= 256.0;
110 nShift--;
111 }
112
113 return dDiff;
114}
115
116static int ComputeNextBlockAndDepth(const CBlockIndex& tip, const CBlockIndex& blockindex, const CBlockIndex*& next)
117{
118 next = tip.GetAncestor(blockindex.nHeight + 1);
119 if (next && next->pprev == &blockindex) {
120 return tip.nHeight - blockindex.nHeight + 1;
121 }
122 next = nullptr;
123 return &blockindex == &tip ? 1 : -1;
124}
125
126static const CBlockIndex* ParseHashOrHeight(const UniValue& param, ChainstateManager& chainman)
127{
129 CChain& active_chain = chainman.ActiveChain();
130
131 if (param.isNum()) {
132 const int height{param.getInt<int>()};
133 if (height < 0) {
134 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
135 }
136 const int current_tip{active_chain.Height()};
137 if (height > current_tip) {
138 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
139 }
140
141 return active_chain[height];
142 } else {
143 const uint256 hash{ParseHashV(param, "hash_or_height")};
144 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
145
146 if (!pindex) {
147 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
148 }
149
150 return pindex;
151 }
152}
153
154UniValue blockheaderToJSON(const CBlockIndex& tip, const CBlockIndex& blockindex, const uint256 pow_limit)
155{
156 // Serialize passed information without accessing chain state of the active chain!
157 AssertLockNotHeld(cs_main); // For performance reasons
158
159 UniValue result(UniValue::VOBJ);
160 result.pushKV("hash", blockindex.GetBlockHash().GetHex());
161 const CBlockIndex* pnext;
162 int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
163 result.pushKV("confirmations", confirmations);
164 result.pushKV("height", blockindex.nHeight);
165 result.pushKV("version", blockindex.nVersion);
166 result.pushKV("versionHex", strprintf("%08x", blockindex.nVersion));
167 result.pushKV("merkleroot", blockindex.hashMerkleRoot.GetHex());
168 result.pushKV("time", blockindex.nTime);
169 result.pushKV("mediantime", blockindex.GetMedianTimePast());
170 result.pushKV("nonce", blockindex.nNonce);
171 result.pushKV("bits", strprintf("%08x", blockindex.nBits));
172 result.pushKV("target", GetTarget(blockindex, pow_limit).GetHex());
173 result.pushKV("difficulty", GetDifficulty(blockindex));
174 result.pushKV("chainwork", blockindex.nChainWork.GetHex());
175 result.pushKV("nTx", blockindex.nTx);
176
177 if (blockindex.pprev)
178 result.pushKV("previousblockhash", blockindex.pprev->GetBlockHash().GetHex());
179 if (pnext)
180 result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
181 return result;
182}
183
184UniValue blockToJSON(BlockManager& blockman, const CBlock& block, const CBlockIndex& tip, const CBlockIndex& blockindex, TxVerbosity verbosity, const uint256 pow_limit)
185{
186 UniValue result = blockheaderToJSON(tip, blockindex, pow_limit);
187
188 result.pushKV("strippedsize", (int)::GetSerializeSize(TX_NO_WITNESS(block)));
189 result.pushKV("size", (int)::GetSerializeSize(TX_WITH_WITNESS(block)));
190 result.pushKV("weight", (int)::GetBlockWeight(block));
192 txs.reserve(block.vtx.size());
193
194 switch (verbosity) {
196 for (const CTransactionRef& tx : block.vtx) {
197 txs.push_back(tx->GetHash().GetHex());
198 }
199 break;
200
203 CBlockUndo blockUndo;
204 const bool is_not_pruned{WITH_LOCK(::cs_main, return !blockman.IsBlockPruned(blockindex))};
205 bool have_undo{is_not_pruned && WITH_LOCK(::cs_main, return blockindex.nStatus & BLOCK_HAVE_UNDO)};
206 if (have_undo && !blockman.ReadBlockUndo(blockUndo, blockindex)) {
207 throw JSONRPCError(RPC_INTERNAL_ERROR, "Undo data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
208 }
209 for (size_t i = 0; i < block.vtx.size(); ++i) {
210 const CTransactionRef& tx = block.vtx.at(i);
211 // coinbase transaction (i.e. i == 0) doesn't have undo data
212 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.vtxundo.at(i - 1) : nullptr;
214 TxToUniv(*tx, /*block_hash=*/uint256(), /*entry=*/objTx, /*include_hex=*/true, txundo, verbosity);
215 txs.push_back(std::move(objTx));
216 }
217 break;
218 }
219
220 result.pushKV("tx", std::move(txs));
221
222 return result;
223}
224
226{
227 return RPCHelpMan{
228 "getblockcount",
229 "Returns the height of the most-work fully-validated chain.\n"
230 "The genesis block has height 0.\n",
231 {},
232 RPCResult{
233 RPCResult::Type::NUM, "", "The current block count"},
235 HelpExampleCli("getblockcount", "")
236 + HelpExampleRpc("getblockcount", "")
237 },
238 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
239{
240 ChainstateManager& chainman = EnsureAnyChainman(request.context);
241 LOCK(cs_main);
242 return chainman.ActiveChain().Height();
243},
244 };
245}
246
248{
249 return RPCHelpMan{
250 "getbestblockhash",
251 "Returns the hash of the best (tip) block in the most-work fully-validated chain.\n",
252 {},
253 RPCResult{
254 RPCResult::Type::STR_HEX, "", "the block hash, hex-encoded"},
256 HelpExampleCli("getbestblockhash", "")
257 + HelpExampleRpc("getbestblockhash", "")
258 },
259 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
260{
261 ChainstateManager& chainman = EnsureAnyChainman(request.context);
262 LOCK(cs_main);
263 return chainman.ActiveChain().Tip()->GetBlockHash().GetHex();
264},
265 };
266}
267
269{
270 return RPCHelpMan{
271 "waitfornewblock",
272 "Waits for any new block and returns useful info about it.\n"
273 "\nReturns the current block on timeout or exit.\n"
274 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
275 {
276 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
277 {"current_tip", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "Method waits for the chain tip to differ from this."},
278 },
279 RPCResult{
280 RPCResult::Type::OBJ, "", "",
281 {
282 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
283 {RPCResult::Type::NUM, "height", "Block height"},
284 }},
286 HelpExampleCli("waitfornewblock", "1000")
287 + HelpExampleRpc("waitfornewblock", "1000")
288 },
289 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
290{
291 int timeout = 0;
292 if (!request.params[0].isNull())
293 timeout = request.params[0].getInt<int>();
294 if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
295
296 NodeContext& node = EnsureAnyNodeContext(request.context);
297 Mining& miner = EnsureMining(node);
298
299 // If the caller provided a current_tip value, pass it to waitTipChanged().
300 //
301 // If the caller did not provide a current tip hash, call getTip() to get
302 // one and wait for the tip to be different from this value. This mode is
303 // less reliable because if the tip changed between waitfornewblock calls,
304 // it will need to change a second time before this call returns.
305 BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
306
307 uint256 tip_hash{request.params[1].isNull()
308 ? current_block.hash
309 : ParseHashV(request.params[1], "current_tip")};
310
311 // If the user provided an invalid current_tip then this call immediately
312 // returns the current tip.
313 std::optional<BlockRef> block = timeout ? miner.waitTipChanged(tip_hash, std::chrono::milliseconds(timeout)) :
314 miner.waitTipChanged(tip_hash);
315
316 // Return current block upon shutdown
317 if (block) current_block = *block;
318
320 ret.pushKV("hash", current_block.hash.GetHex());
321 ret.pushKV("height", current_block.height);
322 return ret;
323},
324 };
325}
326
328{
329 return RPCHelpMan{
330 "waitforblock",
331 "Waits for a specific new block and returns useful info about it.\n"
332 "\nReturns the current block on timeout or exit.\n"
333 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
334 {
335 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Block hash to wait for."},
336 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
337 },
338 RPCResult{
339 RPCResult::Type::OBJ, "", "",
340 {
341 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
342 {RPCResult::Type::NUM, "height", "Block height"},
343 }},
345 HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
346 + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
347 },
348 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
349{
350 int timeout = 0;
351
352 uint256 hash(ParseHashV(request.params[0], "blockhash"));
353
354 if (!request.params[1].isNull())
355 timeout = request.params[1].getInt<int>();
356 if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
357
358 NodeContext& node = EnsureAnyNodeContext(request.context);
359 Mining& miner = EnsureMining(node);
360
361 // Abort if RPC came out of warmup too early
362 BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
363
364 const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
365 while (current_block.hash != hash) {
366 std::optional<BlockRef> block;
367 if (timeout) {
368 auto now{std::chrono::steady_clock::now()};
369 if (now >= deadline) break;
370 const MillisecondsDouble remaining{deadline - now};
371 block = miner.waitTipChanged(current_block.hash, remaining);
372 } else {
373 block = miner.waitTipChanged(current_block.hash);
374 }
375 // Return current block upon shutdown
376 if (!block) break;
377 current_block = *block;
378 }
379
381 ret.pushKV("hash", current_block.hash.GetHex());
382 ret.pushKV("height", current_block.height);
383 return ret;
384},
385 };
386}
387
389{
390 return RPCHelpMan{
391 "waitforblockheight",
392 "Waits for (at least) block height and returns the height and hash\n"
393 "of the current tip.\n"
394 "\nReturns the current block on timeout or exit.\n"
395 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
396 {
397 {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Block height to wait for."},
398 {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
399 },
400 RPCResult{
401 RPCResult::Type::OBJ, "", "",
402 {
403 {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
404 {RPCResult::Type::NUM, "height", "Block height"},
405 }},
407 HelpExampleCli("waitforblockheight", "100 1000")
408 + HelpExampleRpc("waitforblockheight", "100, 1000")
409 },
410 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
411{
412 int timeout = 0;
413
414 int height = request.params[0].getInt<int>();
415
416 if (!request.params[1].isNull())
417 timeout = request.params[1].getInt<int>();
418 if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
419
420 NodeContext& node = EnsureAnyNodeContext(request.context);
421 Mining& miner = EnsureMining(node);
422
423 // Abort if RPC came out of warmup too early
424 BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
425
426 const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
427
428 while (current_block.height < height) {
429 std::optional<BlockRef> block;
430 if (timeout) {
431 auto now{std::chrono::steady_clock::now()};
432 if (now >= deadline) break;
433 const MillisecondsDouble remaining{deadline - now};
434 block = miner.waitTipChanged(current_block.hash, remaining);
435 } else {
436 block = miner.waitTipChanged(current_block.hash);
437 }
438 // Return current block on shutdown
439 if (!block) break;
440 current_block = *block;
441 }
442
444 ret.pushKV("hash", current_block.hash.GetHex());
445 ret.pushKV("height", current_block.height);
446 return ret;
447},
448 };
449}
450
452{
453 return RPCHelpMan{
454 "syncwithvalidationinterfacequeue",
455 "Waits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
456 {},
459 HelpExampleCli("syncwithvalidationinterfacequeue","")
460 + HelpExampleRpc("syncwithvalidationinterfacequeue","")
461 },
462 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
463{
464 NodeContext& node = EnsureAnyNodeContext(request.context);
465 CHECK_NONFATAL(node.validation_signals)->SyncWithValidationInterfaceQueue();
466 return UniValue::VNULL;
467},
468 };
469}
470
472{
473 return RPCHelpMan{
474 "getdifficulty",
475 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
476 {},
477 RPCResult{
478 RPCResult::Type::NUM, "", "the proof-of-work difficulty as a multiple of the minimum difficulty."},
480 HelpExampleCli("getdifficulty", "")
481 + HelpExampleRpc("getdifficulty", "")
482 },
483 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
484{
485 ChainstateManager& chainman = EnsureAnyChainman(request.context);
486 LOCK(cs_main);
487 return GetDifficulty(*CHECK_NONFATAL(chainman.ActiveChain().Tip()));
488},
489 };
490}
491
493{
494 return RPCHelpMan{
495 "getblockfrompeer",
496 "Attempt to fetch block from a given peer.\n\n"
497 "We must have the header for this block, e.g. using submitheader.\n"
498 "The block will not have any undo data which can limit the usage of the block data in a context where the undo data is needed.\n"
499 "Subsequent calls for the same block may cause the response from the previous peer to be ignored.\n"
500 "Peers generally ignore requests for a stale block that they never fully verified, or one that is more than a month old.\n"
501 "When a peer does not respond with a block, we will disconnect.\n"
502 "Note: The block could be re-pruned as soon as it is received.\n\n"
503 "Returns an empty JSON object if the request was successfully scheduled.",
504 {
505 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash to try to fetch"},
506 {"peer_id", RPCArg::Type::NUM, RPCArg::Optional::NO, "The peer to fetch it from (see getpeerinfo for peer IDs)"},
507 },
508 RPCResult{RPCResult::Type::OBJ, "", /*optional=*/false, "", {}},
510 HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
511 + HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
512 },
513 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
514{
515 const NodeContext& node = EnsureAnyNodeContext(request.context);
517 PeerManager& peerman = EnsurePeerman(node);
518
519 const uint256& block_hash{ParseHashV(request.params[0], "blockhash")};
520 const NodeId peer_id{request.params[1].getInt<int64_t>()};
521
522 const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(block_hash););
523
524 if (!index) {
525 throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
526 }
527
528 // Fetching blocks before the node has syncing past their height can prevent block files from
529 // being pruned, so we avoid it if the node is in prune mode.
530 if (chainman.m_blockman.IsPruneMode() && index->nHeight > WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()->nHeight)) {
531 throw JSONRPCError(RPC_MISC_ERROR, "In prune mode, only blocks that the node has already synced previously can be fetched from a peer");
532 }
533
534 const bool block_has_data = WITH_LOCK(::cs_main, return index->nStatus & BLOCK_HAVE_DATA);
535 if (block_has_data) {
536 throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
537 }
538
539 if (const auto err{peerman.FetchBlock(peer_id, *index)}) {
540 throw JSONRPCError(RPC_MISC_ERROR, err.value());
541 }
542 return UniValue::VOBJ;
543},
544 };
545}
546
548{
549 return RPCHelpMan{
550 "getblockhash",
551 "Returns hash of block in best-block-chain at height provided.\n",
552 {
553 {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The height index"},
554 },
555 RPCResult{
556 RPCResult::Type::STR_HEX, "", "The block hash"},
558 HelpExampleCli("getblockhash", "1000")
559 + HelpExampleRpc("getblockhash", "1000")
560 },
561 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
562{
563 ChainstateManager& chainman = EnsureAnyChainman(request.context);
564 LOCK(cs_main);
565 const CChain& active_chain = chainman.ActiveChain();
566
567 int nHeight = request.params[0].getInt<int>();
568 if (nHeight < 0 || nHeight > active_chain.Height())
569 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
570
571 const CBlockIndex* pblockindex = active_chain[nHeight];
572 return pblockindex->GetBlockHash().GetHex();
573},
574 };
575}
576
578{
579 return RPCHelpMan{
580 "getblockheader",
581 "If verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
582 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
583 {
584 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
585 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{true}, "true for a json object, false for the hex-encoded data"},
586 },
587 {
588 RPCResult{"for verbose = true",
589 RPCResult::Type::OBJ, "", "",
590 {
591 {RPCResult::Type::STR_HEX, "hash", "the block hash (same as provided)"},
592 {RPCResult::Type::NUM, "confirmations", "The number of confirmations, or -1 if the block is not on the main chain"},
593 {RPCResult::Type::NUM, "height", "The block height or index"},
594 {RPCResult::Type::NUM, "version", "The block version"},
595 {RPCResult::Type::STR_HEX, "versionHex", "The block version formatted in hexadecimal"},
596 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
597 {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
598 {RPCResult::Type::NUM_TIME, "mediantime", "The median block time expressed in " + UNIX_EPOCH_TIME},
599 {RPCResult::Type::NUM, "nonce", "The nonce"},
600 {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
601 {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
602 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
603 {RPCResult::Type::STR_HEX, "chainwork", "Expected number of hashes required to produce the current chain"},
604 {RPCResult::Type::NUM, "nTx", "The number of transactions in the block"},
605 {RPCResult::Type::STR_HEX, "previousblockhash", /*optional=*/true, "The hash of the previous block (if available)"},
606 {RPCResult::Type::STR_HEX, "nextblockhash", /*optional=*/true, "The hash of the next block (if available)"},
607 }},
608 RPCResult{"for verbose=false",
609 RPCResult::Type::STR_HEX, "", "A string that is serialized, hex-encoded data for block 'hash'"},
610 },
612 HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
613 + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
614 },
615 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
616{
617 uint256 hash(ParseHashV(request.params[0], "hash"));
618
619 bool fVerbose = true;
620 if (!request.params[1].isNull())
621 fVerbose = request.params[1].get_bool();
622
623 const CBlockIndex* pblockindex;
624 const CBlockIndex* tip;
625 ChainstateManager& chainman = EnsureAnyChainman(request.context);
626 {
627 LOCK(cs_main);
628 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
629 tip = chainman.ActiveChain().Tip();
630 }
631
632 if (!pblockindex) {
633 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
634 }
635
636 if (!fVerbose)
637 {
638 DataStream ssBlock{};
639 ssBlock << pblockindex->GetBlockHeader();
640 std::string strHex = HexStr(ssBlock);
641 return strHex;
642 }
643
644 return blockheaderToJSON(*tip, *pblockindex, chainman.GetConsensus().powLimit);
645},
646 };
647}
648
649void CheckBlockDataAvailability(BlockManager& blockman, const CBlockIndex& blockindex, bool check_for_undo)
650{
652 uint32_t flag = check_for_undo ? BLOCK_HAVE_UNDO : BLOCK_HAVE_DATA;
653 if (!(blockindex.nStatus & flag)) {
654 if (blockman.IsBlockPruned(blockindex)) {
655 throw JSONRPCError(RPC_MISC_ERROR, strprintf("%s not available (pruned data)", check_for_undo ? "Undo data" : "Block"));
656 }
657 if (check_for_undo) {
658 throw JSONRPCError(RPC_MISC_ERROR, "Undo data not available");
659 }
660 throw JSONRPCError(RPC_MISC_ERROR, "Block not available (not fully downloaded)");
661 }
662}
663
664static CBlock GetBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
665{
666 CBlock block;
667 {
668 LOCK(cs_main);
669 CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
670 }
671
672 if (!blockman.ReadBlock(block, blockindex)) {
673 // Block not found on disk. This shouldn't normally happen unless the block was
674 // pruned right after we released the lock above.
675 throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
676 }
677
678 return block;
679}
680
681static std::vector<std::byte> GetRawBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
682{
683 std::vector<std::byte> data{};
684 FlatFilePos pos{};
685 {
686 LOCK(cs_main);
687 CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
688 pos = blockindex.GetBlockPos();
689 }
690
691 if (!blockman.ReadRawBlock(data, pos)) {
692 // Block not found on disk. This shouldn't normally happen unless the block was
693 // pruned right after we released the lock above.
694 throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
695 }
696
697 return data;
698}
699
700static CBlockUndo GetUndoChecked(BlockManager& blockman, const CBlockIndex& blockindex)
701{
702 CBlockUndo blockUndo;
703
704 // The Genesis block does not have undo data
705 if (blockindex.nHeight == 0) return blockUndo;
706
707 {
708 LOCK(cs_main);
709 CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/true);
710 }
711
712 if (!blockman.ReadBlockUndo(blockUndo, blockindex)) {
713 throw JSONRPCError(RPC_MISC_ERROR, "Can't read undo data from disk");
714 }
715
716 return blockUndo;
717}
718
720 RPCResult::Type::ARR, "vin", "",
721 {
722 {RPCResult::Type::OBJ, "", "",
723 {
724 {RPCResult::Type::ELISION, "", "The same output as verbosity = 2"},
725 {RPCResult::Type::OBJ, "prevout", "(Only if undo information is available)",
726 {
727 {RPCResult::Type::BOOL, "generated", "Coinbase or not"},
728 {RPCResult::Type::NUM, "height", "The height of the prevout"},
729 {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
730 {RPCResult::Type::OBJ, "scriptPubKey", "",
731 {
732 {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
733 {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
734 {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
735 {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
736 {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
737 }},
738 }},
739 }},
740 }
741};
742
744{
745 return RPCHelpMan{
746 "getblock",
747 "If verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
748 "If verbosity is 1, returns an Object with information about block <hash>.\n"
749 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
750 "If verbosity is 3, returns an Object with information about block <hash> and information about each transaction, including prevout information for inputs (only for unpruned blocks in the current best chain).\n",
751 {
752 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
753 {"verbosity|verbose", RPCArg::Type::NUM, RPCArg::Default{1}, "0 for hex-encoded data, 1 for a JSON object, 2 for JSON object with transaction data, and 3 for JSON object with transaction data including prevout information for inputs",
755 },
756 {
757 RPCResult{"for verbosity = 0",
758 RPCResult::Type::STR_HEX, "", "A string that is serialized, hex-encoded data for block 'hash'"},
759 RPCResult{"for verbosity = 1",
760 RPCResult::Type::OBJ, "", "",
761 {
762 {RPCResult::Type::STR_HEX, "hash", "the block hash (same as provided)"},
763 {RPCResult::Type::NUM, "confirmations", "The number of confirmations, or -1 if the block is not on the main chain"},
764 {RPCResult::Type::NUM, "size", "The block size"},
765 {RPCResult::Type::NUM, "strippedsize", "The block size excluding witness data"},
766 {RPCResult::Type::NUM, "weight", "The block weight as defined in BIP 141"},
767 {RPCResult::Type::NUM, "height", "The block height or index"},
768 {RPCResult::Type::NUM, "version", "The block version"},
769 {RPCResult::Type::STR_HEX, "versionHex", "The block version formatted in hexadecimal"},
770 {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
771 {RPCResult::Type::ARR, "tx", "The transaction ids",
772 {{RPCResult::Type::STR_HEX, "", "The transaction id"}}},
773 {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
774 {RPCResult::Type::NUM_TIME, "mediantime", "The median block time expressed in " + UNIX_EPOCH_TIME},
775 {RPCResult::Type::NUM, "nonce", "The nonce"},
776 {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
777 {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
778 {RPCResult::Type::NUM, "difficulty", "The difficulty"},
779 {RPCResult::Type::STR_HEX, "chainwork", "Expected number of hashes required to produce the chain up to this block (in hex)"},
780 {RPCResult::Type::NUM, "nTx", "The number of transactions in the block"},
781 {RPCResult::Type::STR_HEX, "previousblockhash", /*optional=*/true, "The hash of the previous block (if available)"},
782 {RPCResult::Type::STR_HEX, "nextblockhash", /*optional=*/true, "The hash of the next block (if available)"},
783 }},
784 RPCResult{"for verbosity = 2",
785 RPCResult::Type::OBJ, "", "",
786 {
787 {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
788 {RPCResult::Type::ARR, "tx", "",
789 {
790 {RPCResult::Type::OBJ, "", "",
791 {
792 {RPCResult::Type::ELISION, "", "The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
793 {RPCResult::Type::NUM, "fee", "The transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
794 }},
795 }},
796 }},
797 RPCResult{"for verbosity = 3",
798 RPCResult::Type::OBJ, "", "",
799 {
800 {RPCResult::Type::ELISION, "", "Same output as verbosity = 2"},
801 {RPCResult::Type::ARR, "tx", "",
802 {
803 {RPCResult::Type::OBJ, "", "",
804 {
806 }},
807 }},
808 }},
809 },
811 HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
812 + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
813 },
814 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
815{
816 uint256 hash(ParseHashV(request.params[0], "blockhash"));
817
818 int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/1, /*allow_bool=*/true)};
819
820 const CBlockIndex* pblockindex;
821 const CBlockIndex* tip;
822 ChainstateManager& chainman = EnsureAnyChainman(request.context);
823 {
824 LOCK(cs_main);
825 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
826 tip = chainman.ActiveChain().Tip();
827
828 if (!pblockindex) {
829 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
830 }
831 }
832
833 const std::vector<std::byte> block_data{GetRawBlockChecked(chainman.m_blockman, *pblockindex)};
834
835 if (verbosity <= 0) {
836 return HexStr(block_data);
837 }
838
839 DataStream block_stream{block_data};
840 CBlock block{};
841 block_stream >> TX_WITH_WITNESS(block);
842
843 TxVerbosity tx_verbosity;
844 if (verbosity == 1) {
845 tx_verbosity = TxVerbosity::SHOW_TXID;
846 } else if (verbosity == 2) {
847 tx_verbosity = TxVerbosity::SHOW_DETAILS;
848 } else {
850 }
851
852 return blockToJSON(chainman.m_blockman, block, *tip, *pblockindex, tx_verbosity, chainman.GetConsensus().powLimit);
853},
854 };
855}
856
858std::optional<int> GetPruneHeight(const BlockManager& blockman, const CChain& chain) {
860
861 // Search for the last block missing block data or undo data. Don't let the
862 // search consider the genesis block, because the genesis block does not
863 // have undo data, but should not be considered pruned.
864 const CBlockIndex* first_block{chain[1]};
865 const CBlockIndex* chain_tip{chain.Tip()};
866
867 // If there are no blocks after the genesis block, or no blocks at all, nothing is pruned.
868 if (!first_block || !chain_tip) return std::nullopt;
869
870 // If the chain tip is pruned, everything is pruned.
871 if (!((chain_tip->nStatus & BLOCK_HAVE_MASK) == BLOCK_HAVE_MASK)) return chain_tip->nHeight;
872
873 const auto& first_unpruned{*CHECK_NONFATAL(blockman.GetFirstBlock(*chain_tip, /*status_mask=*/BLOCK_HAVE_MASK, first_block))};
874 if (&first_unpruned == first_block) {
875 // All blocks between first_block and chain_tip have data, so nothing is pruned.
876 return std::nullopt;
877 }
878
879 // Block before the first unpruned block is the last pruned block.
880 return CHECK_NONFATAL(first_unpruned.pprev)->nHeight;
881}
882
884{
885 return RPCHelpMan{"pruneblockchain",
886 "Attempts to delete block and undo data up to a specified height or timestamp, if eligible for pruning.\n"
887 "Requires `-prune` to be enabled at startup. While pruned data may be re-fetched in some cases (e.g., via `getblockfrompeer`), local deletion is irreversible.\n",
888 {
889 {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block height to prune up to. May be set to a discrete height, or to a " + UNIX_EPOCH_TIME + "\n"
890 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
891 },
892 RPCResult{
893 RPCResult::Type::NUM, "", "Height of the last block pruned"},
895 HelpExampleCli("pruneblockchain", "1000")
896 + HelpExampleRpc("pruneblockchain", "1000")
897 },
898 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
899{
900 ChainstateManager& chainman = EnsureAnyChainman(request.context);
901 if (!chainman.m_blockman.IsPruneMode()) {
902 throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
903 }
904
905 LOCK(cs_main);
906 Chainstate& active_chainstate = chainman.ActiveChainstate();
907 CChain& active_chain = active_chainstate.m_chain;
908
909 int heightParam = request.params[0].getInt<int>();
910 if (heightParam < 0) {
911 throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
912 }
913
914 // Height value more than a billion is too high to be a block height, and
915 // too low to be a block time (corresponds to timestamp from Sep 2001).
916 if (heightParam > 1000000000) {
917 // Add a 2 hour buffer to include blocks which might have had old timestamps
918 const CBlockIndex* pindex = active_chain.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0);
919 if (!pindex) {
920 throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
921 }
922 heightParam = pindex->nHeight;
923 }
924
925 unsigned int height = (unsigned int) heightParam;
926 unsigned int chainHeight = (unsigned int) active_chain.Height();
927 if (chainHeight < chainman.GetParams().PruneAfterHeight()) {
928 throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
929 } else if (height > chainHeight) {
930 throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
931 } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
932 LogDebug(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
933 height = chainHeight - MIN_BLOCKS_TO_KEEP;
934 }
935
936 PruneBlockFilesManual(active_chainstate, height);
937 return GetPruneHeight(chainman.m_blockman, active_chain).value_or(-1);
938},
939 };
940}
941
942CoinStatsHashType ParseHashType(std::string_view hash_type_input)
943{
944 if (hash_type_input == "hash_serialized_3") {
945 return CoinStatsHashType::HASH_SERIALIZED;
946 } else if (hash_type_input == "muhash") {
947 return CoinStatsHashType::MUHASH;
948 } else if (hash_type_input == "none") {
950 } else {
951 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("'%s' is not a valid hash_type", hash_type_input));
952 }
953}
954
960static std::optional<kernel::CCoinsStats> GetUTXOStats(CCoinsView* view, node::BlockManager& blockman,
962 const std::function<void()>& interruption_point = {},
963 const CBlockIndex* pindex = nullptr,
964 bool index_requested = true)
965{
966 // Use CoinStatsIndex if it is requested and available and a hash_type of Muhash or None was requested
967 if ((hash_type == kernel::CoinStatsHashType::MUHASH || hash_type == kernel::CoinStatsHashType::NONE) && g_coin_stats_index && index_requested) {
968 if (pindex) {
969 return g_coin_stats_index->LookUpStats(*pindex);
970 } else {
971 CBlockIndex& block_index = *CHECK_NONFATAL(WITH_LOCK(::cs_main, return blockman.LookupBlockIndex(view->GetBestBlock())));
972 return g_coin_stats_index->LookUpStats(block_index);
973 }
974 }
975
976 // If the coinstats index isn't requested or is otherwise not usable, the
977 // pindex should either be null or equal to the view's best block. This is
978 // because without the coinstats index we can only get coinstats about the
979 // best block.
980 CHECK_NONFATAL(!pindex || pindex->GetBlockHash() == view->GetBestBlock());
981
982 return kernel::ComputeUTXOStats(hash_type, view, blockman, interruption_point);
983}
984
986{
987 return RPCHelpMan{
988 "gettxoutsetinfo",
989 "Returns statistics about the unspent transaction output set.\n"
990 "Note this call may take some time if you are not using coinstatsindex.\n",
991 {
992 {"hash_type", RPCArg::Type::STR, RPCArg::Default{"hash_serialized_3"}, "Which UTXO set hash should be calculated. Options: 'hash_serialized_3' (the legacy algorithm), 'muhash', 'none'."},
993 {"hash_or_height", RPCArg::Type::NUM, RPCArg::DefaultHint{"the current best block"}, "The block hash or height of the target height (only available with coinstatsindex).",
995 .skip_type_check = true,
996 .type_str = {"", "string or numeric"},
997 }},
998 {"use_index", RPCArg::Type::BOOL, RPCArg::Default{true}, "Use coinstatsindex, if available."},
999 },
1000 RPCResult{
1001 RPCResult::Type::OBJ, "", "",
1002 {
1003 {RPCResult::Type::NUM, "height", "The block height (index) of the returned statistics"},
1004 {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at which these statistics are calculated"},
1005 {RPCResult::Type::NUM, "txouts", "The number of unspent transaction outputs"},
1006 {RPCResult::Type::NUM, "bogosize", "Database-independent, meaningless metric indicating the UTXO set size"},
1007 {RPCResult::Type::STR_HEX, "hash_serialized_3", /*optional=*/true, "The serialized hash (only present if 'hash_serialized_3' hash_type is chosen)"},
1008 {RPCResult::Type::STR_HEX, "muhash", /*optional=*/true, "The serialized hash (only present if 'muhash' hash_type is chosen)"},
1009 {RPCResult::Type::NUM, "transactions", /*optional=*/true, "The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1010 {RPCResult::Type::NUM, "disk_size", /*optional=*/true, "The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1011 {RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of coins in the UTXO set"},
1012 {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount", /*optional=*/true, "The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
1013 {RPCResult::Type::OBJ, "block_info", /*optional=*/true, "Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1014 {
1015 {RPCResult::Type::STR_AMOUNT, "prevout_spent", "Total amount of all prevouts spent in this block"},
1016 {RPCResult::Type::STR_AMOUNT, "coinbase", "Coinbase subsidy amount of this block"},
1017 {RPCResult::Type::STR_AMOUNT, "new_outputs_ex_coinbase", "Total amount of new outputs created by this block"},
1018 {RPCResult::Type::STR_AMOUNT, "unspendable", "Total amount of unspendable outputs created in this block"},
1019 {RPCResult::Type::OBJ, "unspendables", "Detailed view of the unspendable categories",
1020 {
1021 {RPCResult::Type::STR_AMOUNT, "genesis_block", "The unspendable amount of the Genesis block subsidy"},
1022 {RPCResult::Type::STR_AMOUNT, "bip30", "Transactions overridden by duplicates (no longer possible with BIP30)"},
1023 {RPCResult::Type::STR_AMOUNT, "scripts", "Amounts sent to scripts that are unspendable (for example OP_RETURN outputs)"},
1024 {RPCResult::Type::STR_AMOUNT, "unclaimed_rewards", "Fee rewards that miners did not claim in their coinbase transaction"},
1025 }}
1026 }},
1027 }},
1029 HelpExampleCli("gettxoutsetinfo", "") +
1030 HelpExampleCli("gettxoutsetinfo", R"("none")") +
1031 HelpExampleCli("gettxoutsetinfo", R"("none" 1000)") +
1032 HelpExampleCli("gettxoutsetinfo", R"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1033 HelpExampleCli("-named gettxoutsetinfo", R"(hash_type='muhash' use_index='false')") +
1034 HelpExampleRpc("gettxoutsetinfo", "") +
1035 HelpExampleRpc("gettxoutsetinfo", R"("none")") +
1036 HelpExampleRpc("gettxoutsetinfo", R"("none", 1000)") +
1037 HelpExampleRpc("gettxoutsetinfo", R"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1038 },
1039 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1040{
1042
1043 const CBlockIndex* pindex{nullptr};
1044 const CoinStatsHashType hash_type{ParseHashType(self.Arg<std::string_view>("hash_type"))};
1045 bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
1046
1047 NodeContext& node = EnsureAnyNodeContext(request.context);
1049 Chainstate& active_chainstate = chainman.ActiveChainstate();
1050 active_chainstate.ForceFlushStateToDisk();
1051
1052 CCoinsView* coins_view;
1053 BlockManager* blockman;
1054 {
1055 LOCK(::cs_main);
1056 coins_view = &active_chainstate.CoinsDB();
1057 blockman = &active_chainstate.m_blockman;
1058 pindex = blockman->LookupBlockIndex(coins_view->GetBestBlock());
1059 }
1060
1061 if (!request.params[1].isNull()) {
1062 if (!g_coin_stats_index) {
1063 throw JSONRPCError(RPC_INVALID_PARAMETER, "Querying specific block heights requires coinstatsindex");
1064 }
1065
1066 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1067 throw JSONRPCError(RPC_INVALID_PARAMETER, "hash_serialized_3 hash type cannot be queried for a specific block");
1068 }
1069
1070 if (!index_requested) {
1071 throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot set use_index to false when querying for a specific block");
1072 }
1073 pindex = ParseHashOrHeight(request.params[1], chainman);
1074 }
1075
1076 if (index_requested && g_coin_stats_index) {
1077 if (!g_coin_stats_index->BlockUntilSyncedToCurrentChain()) {
1078 const IndexSummary summary{g_coin_stats_index->GetSummary()};
1079
1080 // If a specific block was requested and the index has already synced past that height, we can return the
1081 // data already even though the index is not fully synced yet.
1082 if (pindex->nHeight > summary.best_block_height) {
1083 throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Unable to get data because coinstatsindex is still syncing. Current height: %d", summary.best_block_height));
1084 }
1085 }
1086 }
1087
1088 const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex, index_requested);
1089 if (maybe_stats.has_value()) {
1090 const CCoinsStats& stats = maybe_stats.value();
1091 ret.pushKV("height", (int64_t)stats.nHeight);
1092 ret.pushKV("bestblock", stats.hashBlock.GetHex());
1093 ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs);
1094 ret.pushKV("bogosize", (int64_t)stats.nBogoSize);
1095 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1096 ret.pushKV("hash_serialized_3", stats.hashSerialized.GetHex());
1097 }
1098 if (hash_type == CoinStatsHashType::MUHASH) {
1099 ret.pushKV("muhash", stats.hashSerialized.GetHex());
1100 }
1101 CHECK_NONFATAL(stats.total_amount.has_value());
1102 ret.pushKV("total_amount", ValueFromAmount(stats.total_amount.value()));
1103 if (!stats.index_used) {
1104 ret.pushKV("transactions", static_cast<int64_t>(stats.nTransactions));
1105 ret.pushKV("disk_size", stats.nDiskSize);
1106 } else {
1107 CCoinsStats prev_stats{};
1108 if (pindex->nHeight > 0) {
1109 const std::optional<CCoinsStats> maybe_prev_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex->pprev, index_requested);
1110 if (!maybe_prev_stats) {
1111 throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1112 }
1113 prev_stats = maybe_prev_stats.value();
1114 }
1115
1116 CAmount block_total_unspendable_amount = stats.total_unspendables_genesis_block +
1120 CAmount prev_block_total_unspendable_amount = prev_stats.total_unspendables_genesis_block +
1121 prev_stats.total_unspendables_bip30 +
1122 prev_stats.total_unspendables_scripts +
1123 prev_stats.total_unspendables_unclaimed_rewards;
1124
1125 ret.pushKV("total_unspendable_amount", ValueFromAmount(block_total_unspendable_amount));
1126
1127 UniValue block_info(UniValue::VOBJ);
1128 // These per-block values should fit uint64 under normal circumstances
1129 arith_uint256 diff_prevout = stats.total_prevout_spent_amount - prev_stats.total_prevout_spent_amount;
1130 arith_uint256 diff_coinbase = stats.total_coinbase_amount - prev_stats.total_coinbase_amount;
1131 arith_uint256 diff_outputs = stats.total_new_outputs_ex_coinbase_amount - prev_stats.total_new_outputs_ex_coinbase_amount;
1132 CAmount prevout_amount = static_cast<CAmount>(diff_prevout.GetLow64());
1133 CAmount coinbase_amount = static_cast<CAmount>(diff_coinbase.GetLow64());
1134 CAmount outputs_amount = static_cast<CAmount>(diff_outputs.GetLow64());
1135 block_info.pushKV("prevout_spent", ValueFromAmount(prevout_amount));
1136 block_info.pushKV("coinbase", ValueFromAmount(coinbase_amount));
1137 block_info.pushKV("new_outputs_ex_coinbase", ValueFromAmount(outputs_amount));
1138 block_info.pushKV("unspendable", ValueFromAmount(block_total_unspendable_amount - prev_block_total_unspendable_amount));
1139
1140 UniValue unspendables(UniValue::VOBJ);
1141 unspendables.pushKV("genesis_block", ValueFromAmount(stats.total_unspendables_genesis_block - prev_stats.total_unspendables_genesis_block));
1142 unspendables.pushKV("bip30", ValueFromAmount(stats.total_unspendables_bip30 - prev_stats.total_unspendables_bip30));
1143 unspendables.pushKV("scripts", ValueFromAmount(stats.total_unspendables_scripts - prev_stats.total_unspendables_scripts));
1144 unspendables.pushKV("unclaimed_rewards", ValueFromAmount(stats.total_unspendables_unclaimed_rewards - prev_stats.total_unspendables_unclaimed_rewards));
1145 block_info.pushKV("unspendables", std::move(unspendables));
1146
1147 ret.pushKV("block_info", std::move(block_info));
1148 }
1149 } else {
1150 throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1151 }
1152 return ret;
1153},
1154 };
1155}
1156
1158{
1159 return RPCHelpMan{
1160 "gettxout",
1161 "Returns details about an unspent transaction output.\n",
1162 {
1163 {"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
1164 {"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
1165 {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
1166 },
1167 {
1168 RPCResult{"If the UTXO was not found", RPCResult::Type::NONE, "", ""},
1169 RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "", {
1170 {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at the tip of the chain"},
1171 {RPCResult::Type::NUM, "confirmations", "The number of confirmations"},
1172 {RPCResult::Type::STR_AMOUNT, "value", "The transaction value in " + CURRENCY_UNIT},
1173 {RPCResult::Type::OBJ, "scriptPubKey", "", {
1174 {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1175 {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1176 {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1177 {RPCResult::Type::STR, "type", "The type, eg pubkeyhash"},
1178 {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1179 }},
1180 {RPCResult::Type::BOOL, "coinbase", "Coinbase or not"},
1181 }},
1182 },
1184 "\nGet unspent transactions\n"
1185 + HelpExampleCli("listunspent", "") +
1186 "\nView the details\n"
1187 + HelpExampleCli("gettxout", "\"txid\" 1") +
1188 "\nAs a JSON-RPC call\n"
1189 + HelpExampleRpc("gettxout", "\"txid\", 1")
1190 },
1191 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1192{
1193 NodeContext& node = EnsureAnyNodeContext(request.context);
1195 LOCK(cs_main);
1196
1198
1199 auto hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
1200 COutPoint out{hash, request.params[1].getInt<uint32_t>()};
1201 bool fMempool = true;
1202 if (!request.params[2].isNull())
1203 fMempool = request.params[2].get_bool();
1204
1205 Chainstate& active_chainstate = chainman.ActiveChainstate();
1206 CCoinsViewCache* coins_view = &active_chainstate.CoinsTip();
1207
1208 std::optional<Coin> coin;
1209 if (fMempool) {
1210 const CTxMemPool& mempool = EnsureMemPool(node);
1211 LOCK(mempool.cs);
1212 CCoinsViewMemPool view(coins_view, mempool);
1213 if (!mempool.isSpent(out)) coin = view.GetCoin(out);
1214 } else {
1215 coin = coins_view->GetCoin(out);
1216 }
1217 if (!coin) return UniValue::VNULL;
1218
1219 const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(coins_view->GetBestBlock());
1220 ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
1221 if (coin->nHeight == MEMPOOL_HEIGHT) {
1222 ret.pushKV("confirmations", 0);
1223 } else {
1224 ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin->nHeight + 1));
1225 }
1226 ret.pushKV("value", ValueFromAmount(coin->out.nValue));
1228 ScriptToUniv(coin->out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1229 ret.pushKV("scriptPubKey", std::move(o));
1230 ret.pushKV("coinbase", (bool)coin->fCoinBase);
1231
1232 return ret;
1233},
1234 };
1235}
1236
1238{
1239 return RPCHelpMan{
1240 "verifychain",
1241 "Verifies blockchain database.\n",
1242 {
1243 {"checklevel", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, range=0-4", DEFAULT_CHECKLEVEL)},
1244 strprintf("How thorough the block verification is:\n%s", MakeUnorderedList(CHECKLEVEL_DOC))},
1245 {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, 0=all", DEFAULT_CHECKBLOCKS)}, "The number of blocks to check."},
1246 },
1247 RPCResult{
1248 RPCResult::Type::BOOL, "", "Verification finished successfully. If false, check debug.log for reason."},
1250 HelpExampleCli("verifychain", "")
1251 + HelpExampleRpc("verifychain", "")
1252 },
1253 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1254{
1255 const int check_level{request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].getInt<int>()};
1256 const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].getInt<int>()};
1257
1258 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1259 LOCK(cs_main);
1260
1261 Chainstate& active_chainstate = chainman.ActiveChainstate();
1262 return CVerifyDB(chainman.GetNotifications()).VerifyDB(
1263 active_chainstate, chainman.GetParams().GetConsensus(), active_chainstate.CoinsTip(), check_level, check_depth) == VerifyDBResult::SUCCESS;
1264},
1265 };
1266}
1267
1268static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::BuriedDeployment dep)
1269{
1270 // For buried deployments.
1271
1272 if (!DeploymentEnabled(chainman, dep)) return;
1273
1275 rv.pushKV("type", "buried");
1276 // getdeploymentinfo reports the softfork as active from when the chain height is
1277 // one below the activation height
1278 rv.pushKV("active", DeploymentActiveAfter(blockindex, chainman, dep));
1279 rv.pushKV("height", chainman.GetConsensus().DeploymentHeight(dep));
1280 softforks.pushKV(DeploymentName(dep), std::move(rv));
1281}
1282
1283static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::DeploymentPos id)
1284{
1285 // For BIP9 deployments.
1286 if (!DeploymentEnabled(chainman, id)) return;
1287 if (blockindex == nullptr) return;
1288
1290 BIP9Info info{chainman.m_versionbitscache.Info(*blockindex, chainman.GetConsensus(), id)};
1291 const auto& depparams{chainman.GetConsensus().vDeployments[id]};
1292
1293 // BIP9 parameters
1294 if (info.stats.has_value()) {
1295 bip9.pushKV("bit", depparams.bit);
1296 }
1297 bip9.pushKV("start_time", depparams.nStartTime);
1298 bip9.pushKV("timeout", depparams.nTimeout);
1299 bip9.pushKV("min_activation_height", depparams.min_activation_height);
1300
1301 // BIP9 status
1302 bip9.pushKV("status", info.current_state);
1303 bip9.pushKV("since", info.since);
1304 bip9.pushKV("status_next", info.next_state);
1305
1306 // BIP9 signalling status, if applicable
1307 if (info.stats.has_value()) {
1308 UniValue statsUV(UniValue::VOBJ);
1309 statsUV.pushKV("period", info.stats->period);
1310 statsUV.pushKV("elapsed", info.stats->elapsed);
1311 statsUV.pushKV("count", info.stats->count);
1312 if (info.stats->threshold > 0 || info.stats->possible) {
1313 statsUV.pushKV("threshold", info.stats->threshold);
1314 statsUV.pushKV("possible", info.stats->possible);
1315 }
1316 bip9.pushKV("statistics", std::move(statsUV));
1317
1318 std::string sig;
1319 sig.reserve(info.signalling_blocks.size());
1320 for (const bool s : info.signalling_blocks) {
1321 sig.push_back(s ? '#' : '-');
1322 }
1323 bip9.pushKV("signalling", sig);
1324 }
1325
1327 rv.pushKV("type", "bip9");
1328 bool is_active = false;
1329 if (info.active_since.has_value()) {
1330 rv.pushKV("height", *info.active_since);
1331 is_active = (*info.active_since <= blockindex->nHeight + 1);
1332 }
1333 rv.pushKV("active", is_active);
1334 rv.pushKV("bip9", bip9);
1335 softforks.pushKV(DeploymentName(id), std::move(rv));
1336}
1337
1338// used by rest.cpp:rest_chaininfo, so cannot be static
1340{
1341 return RPCHelpMan{"getblockchaininfo",
1342 "Returns an object containing various state info regarding blockchain processing.\n",
1343 {},
1344 RPCResult{
1345 RPCResult::Type::OBJ, "", "",
1346 {
1347 {RPCResult::Type::STR, "chain", "current network name (" LIST_CHAIN_NAMES ")"},
1348 {RPCResult::Type::NUM, "blocks", "the height of the most-work fully-validated chain. The genesis block has height 0"},
1349 {RPCResult::Type::NUM, "headers", "the current number of headers we have validated"},
1350 {RPCResult::Type::STR, "bestblockhash", "the hash of the currently best block"},
1351 {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
1352 {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
1353 {RPCResult::Type::NUM, "difficulty", "the current difficulty"},
1354 {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
1355 {RPCResult::Type::NUM_TIME, "mediantime", "The median block time expressed in " + UNIX_EPOCH_TIME},
1356 {RPCResult::Type::NUM, "verificationprogress", "estimate of verification progress [0..1]"},
1357 {RPCResult::Type::BOOL, "initialblockdownload", "(debug information) estimate of whether this node is in Initial Block Download mode"},
1358 {RPCResult::Type::STR_HEX, "chainwork", "total amount of work in active chain, in hexadecimal"},
1359 {RPCResult::Type::NUM, "size_on_disk", "the estimated size of the block and undo files on disk"},
1360 {RPCResult::Type::BOOL, "pruned", "if the blocks are subject to pruning"},
1361 {RPCResult::Type::NUM, "pruneheight", /*optional=*/true, "height of the last block pruned, plus one (only present if pruning is enabled)"},
1362 {RPCResult::Type::BOOL, "automatic_pruning", /*optional=*/true, "whether automatic pruning is enabled (only present if pruning is enabled)"},
1363 {RPCResult::Type::NUM, "prune_target_size", /*optional=*/true, "the target size used by pruning (only present if automatic pruning is enabled)"},
1364 {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "the block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
1365 (IsDeprecatedRPCEnabled("warnings") ?
1366 RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
1367 RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
1368 {
1369 {RPCResult::Type::STR, "", "warning"},
1370 }
1371 }
1372 ),
1373 }},
1375 HelpExampleCli("getblockchaininfo", "")
1376 + HelpExampleRpc("getblockchaininfo", "")
1377 },
1378 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1379{
1380 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1381 LOCK(cs_main);
1382 Chainstate& active_chainstate = chainman.ActiveChainstate();
1383
1384 const CBlockIndex& tip{*CHECK_NONFATAL(active_chainstate.m_chain.Tip())};
1385 const int height{tip.nHeight};
1387 obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
1388 obj.pushKV("blocks", height);
1389 obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
1390 obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
1391 obj.pushKV("bits", strprintf("%08x", tip.nBits));
1392 obj.pushKV("target", GetTarget(tip, chainman.GetConsensus().powLimit).GetHex());
1393 obj.pushKV("difficulty", GetDifficulty(tip));
1394 obj.pushKV("time", tip.GetBlockTime());
1395 obj.pushKV("mediantime", tip.GetMedianTimePast());
1396 obj.pushKV("verificationprogress", chainman.GuessVerificationProgress(&tip));
1397 obj.pushKV("initialblockdownload", chainman.IsInitialBlockDownload());
1398 obj.pushKV("chainwork", tip.nChainWork.GetHex());
1399 obj.pushKV("size_on_disk", chainman.m_blockman.CalculateCurrentUsage());
1400 obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
1401 if (chainman.m_blockman.IsPruneMode()) {
1402 const auto prune_height{GetPruneHeight(chainman.m_blockman, active_chainstate.m_chain)};
1403 obj.pushKV("pruneheight", prune_height ? prune_height.value() + 1 : 0);
1404
1405 const bool automatic_pruning{chainman.m_blockman.GetPruneTarget() != BlockManager::PRUNE_TARGET_MANUAL};
1406 obj.pushKV("automatic_pruning", automatic_pruning);
1407 if (automatic_pruning) {
1408 obj.pushKV("prune_target_size", chainman.m_blockman.GetPruneTarget());
1409 }
1410 }
1411 if (chainman.GetParams().GetChainType() == ChainType::SIGNET) {
1412 const std::vector<uint8_t>& signet_challenge =
1414 obj.pushKV("signet_challenge", HexStr(signet_challenge));
1415 }
1416
1417 NodeContext& node = EnsureAnyNodeContext(request.context);
1418 obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
1419 return obj;
1420},
1421 };
1422}
1423
1424namespace {
1425const std::vector<RPCResult> RPCHelpForDeployment{
1426 {RPCResult::Type::STR, "type", "one of \"buried\", \"bip9\""},
1427 {RPCResult::Type::NUM, "height", /*optional=*/true, "height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
1428 {RPCResult::Type::BOOL, "active", "true if the rules are enforced for the mempool and the next block"},
1429 {RPCResult::Type::OBJ, "bip9", /*optional=*/true, "status of bip9 softforks (only for \"bip9\" type)",
1430 {
1431 {RPCResult::Type::NUM, "bit", /*optional=*/true, "the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
1432 {RPCResult::Type::NUM_TIME, "start_time", "the minimum median time past of a block at which the bit gains its meaning"},
1433 {RPCResult::Type::NUM_TIME, "timeout", "the median time past of a block at which the deployment is considered failed if not yet locked in"},
1434 {RPCResult::Type::NUM, "min_activation_height", "minimum height of blocks for which the rules may be enforced"},
1435 {RPCResult::Type::STR, "status", "status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1436 {RPCResult::Type::NUM, "since", "height of the first block to which the status applies"},
1437 {RPCResult::Type::STR, "status_next", "status of deployment at the next block"},
1438 {RPCResult::Type::OBJ, "statistics", /*optional=*/true, "numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1439 {
1440 {RPCResult::Type::NUM, "period", "the length in blocks of the signalling period"},
1441 {RPCResult::Type::NUM, "threshold", /*optional=*/true, "the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1442 {RPCResult::Type::NUM, "elapsed", "the number of blocks elapsed since the beginning of the current period"},
1443 {RPCResult::Type::NUM, "count", "the number of blocks with the version bit set in the current period"},
1444 {RPCResult::Type::BOOL, "possible", /*optional=*/true, "returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
1445 }},
1446 {RPCResult::Type::STR, "signalling", /*optional=*/true, "indicates blocks that signalled with a # and blocks that did not with a -"},
1447 }},
1448};
1449
1450UniValue DeploymentInfo(const CBlockIndex* blockindex, const ChainstateManager& chainman)
1451{
1452 UniValue softforks(UniValue::VOBJ);
1453 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_HEIGHTINCB);
1454 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_DERSIG);
1455 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CLTV);
1456 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CSV);
1457 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_SEGWIT);
1458 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TESTDUMMY);
1459 SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TAPROOT);
1460 return softforks;
1461}
1462} // anon namespace
1463
1465{
1466 return RPCHelpMan{"getdeploymentinfo",
1467 "Returns an object containing various state info regarding deployments of consensus changes.",
1468 {
1469 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Default{"hash of current chain tip"}, "The block hash at which to query deployment state"},
1470 },
1471 RPCResult{
1472 RPCResult::Type::OBJ, "", "", {
1473 {RPCResult::Type::STR, "hash", "requested block hash (or tip)"},
1474 {RPCResult::Type::NUM, "height", "requested block height (or tip)"},
1475 {RPCResult::Type::ARR, "script_flags", "script verify flags for the block", {
1476 {RPCResult::Type::STR, "flag", "a script verify flag"},
1477 }},
1478 {RPCResult::Type::OBJ_DYN, "deployments", "", {
1479 {RPCResult::Type::OBJ, "xxxx", "name of the deployment", RPCHelpForDeployment}
1480 }},
1481 }
1482 },
1483 RPCExamples{ HelpExampleCli("getdeploymentinfo", "") + HelpExampleRpc("getdeploymentinfo", "") },
1484 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1485 {
1486 const ChainstateManager& chainman = EnsureAnyChainman(request.context);
1487 LOCK(cs_main);
1488 const Chainstate& active_chainstate = chainman.ActiveChainstate();
1489
1490 const CBlockIndex* blockindex;
1491 if (request.params[0].isNull()) {
1492 blockindex = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
1493 } else {
1494 const uint256 hash(ParseHashV(request.params[0], "blockhash"));
1495 blockindex = chainman.m_blockman.LookupBlockIndex(hash);
1496 if (!blockindex) {
1497 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1498 }
1499 }
1500
1501 UniValue deploymentinfo(UniValue::VOBJ);
1502 deploymentinfo.pushKV("hash", blockindex->GetBlockHash().ToString());
1503 deploymentinfo.pushKV("height", blockindex->nHeight);
1504 {
1505 const auto flagnames = GetScriptFlagNames(GetBlockScriptFlags(*blockindex, chainman));
1506 UniValue uv_flagnames(UniValue::VARR);
1507 uv_flagnames.push_backV(flagnames.begin(), flagnames.end());
1508 deploymentinfo.pushKV("script_flags", uv_flagnames);
1509 }
1510 deploymentinfo.pushKV("deployments", DeploymentInfo(blockindex, chainman));
1511 return deploymentinfo;
1512 },
1513 };
1514}
1515
1518{
1519 bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
1520 {
1521 /* Make sure that unequal blocks with the same height do not compare
1522 equal. Use the pointers themselves to make a distinction. */
1523
1524 if (a->nHeight != b->nHeight)
1525 return (a->nHeight > b->nHeight);
1526
1527 return a < b;
1528 }
1529};
1530
1532{
1533 return RPCHelpMan{"getchaintips",
1534 "Return information about all known tips in the block tree,"
1535 " including the main chain as well as orphaned branches.\n",
1536 {},
1537 RPCResult{
1538 RPCResult::Type::ARR, "", "",
1539 {{RPCResult::Type::OBJ, "", "",
1540 {
1541 {RPCResult::Type::NUM, "height", "height of the chain tip"},
1542 {RPCResult::Type::STR_HEX, "hash", "block hash of the tip"},
1543 {RPCResult::Type::NUM, "branchlen", "zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1544 {RPCResult::Type::STR, "status", "status of the chain, \"active\" for the main chain\n"
1545 "Possible values for status:\n"
1546 "1. \"invalid\" This branch contains at least one invalid block\n"
1547 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1548 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1549 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1550 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1551 }}}},
1553 HelpExampleCli("getchaintips", "")
1554 + HelpExampleRpc("getchaintips", "")
1555 },
1556 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1557{
1558 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1559 LOCK(cs_main);
1560 CChain& active_chain = chainman.ActiveChain();
1561
1562 /*
1563 * Idea: The set of chain tips is the active chain tip, plus orphan blocks which do not have another orphan building off of them.
1564 * Algorithm:
1565 * - Make one pass through BlockIndex(), picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
1566 * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
1567 * - Add the active chain tip
1568 */
1569 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1570 std::set<const CBlockIndex*> setOrphans;
1571 std::set<const CBlockIndex*> setPrevs;
1572
1573 for (const auto& [_, block_index] : chainman.BlockIndex()) {
1574 if (!active_chain.Contains(&block_index)) {
1575 setOrphans.insert(&block_index);
1576 setPrevs.insert(block_index.pprev);
1577 }
1578 }
1579
1580 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1581 if (setPrevs.erase(*it) == 0) {
1582 setTips.insert(*it);
1583 }
1584 }
1585
1586 // Always report the currently active tip.
1587 setTips.insert(active_chain.Tip());
1588
1589 /* Construct the output array. */
1591 for (const CBlockIndex* block : setTips) {
1593 obj.pushKV("height", block->nHeight);
1594 obj.pushKV("hash", block->phashBlock->GetHex());
1595
1596 const int branchLen = block->nHeight - active_chain.FindFork(block)->nHeight;
1597 obj.pushKV("branchlen", branchLen);
1598
1599 std::string status;
1600 if (active_chain.Contains(block)) {
1601 // This block is part of the currently active chain.
1602 status = "active";
1603 } else if (block->nStatus & BLOCK_FAILED_MASK) {
1604 // This block or one of its ancestors is invalid.
1605 status = "invalid";
1606 } else if (!block->HaveNumChainTxs()) {
1607 // This block cannot be connected because full block data for it or one of its parents is missing.
1608 status = "headers-only";
1609 } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
1610 // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
1611 status = "valid-fork";
1612 } else if (block->IsValid(BLOCK_VALID_TREE)) {
1613 // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
1614 status = "valid-headers";
1615 } else {
1616 // No clue.
1617 status = "unknown";
1618 }
1619 obj.pushKV("status", status);
1620
1621 res.push_back(std::move(obj));
1622 }
1623
1624 return res;
1625},
1626 };
1627}
1628
1630{
1631 return RPCHelpMan{
1632 "preciousblock",
1633 "Treats a block as if it were received before others with the same work.\n"
1634 "\nA later preciousblock call can override the effect of an earlier one.\n"
1635 "\nThe effects of preciousblock are not retained across restarts.\n",
1636 {
1637 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as precious"},
1638 },
1641 HelpExampleCli("preciousblock", "\"blockhash\"")
1642 + HelpExampleRpc("preciousblock", "\"blockhash\"")
1643 },
1644 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1645{
1646 uint256 hash(ParseHashV(request.params[0], "blockhash"));
1647 CBlockIndex* pblockindex;
1648
1649 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1650 {
1651 LOCK(cs_main);
1652 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1653 if (!pblockindex) {
1654 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1655 }
1656 }
1657
1659 chainman.ActiveChainstate().PreciousBlock(state, pblockindex);
1660
1661 if (!state.IsValid()) {
1663 }
1664
1665 return UniValue::VNULL;
1666},
1667 };
1668}
1669
1670void InvalidateBlock(ChainstateManager& chainman, const uint256 block_hash) {
1672 CBlockIndex* pblockindex;
1673 {
1674 LOCK(chainman.GetMutex());
1675 pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1676 if (!pblockindex) {
1677 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1678 }
1679 }
1680 chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
1681
1682 if (state.IsValid()) {
1683 chainman.ActiveChainstate().ActivateBestChain(state);
1684 }
1685
1686 if (!state.IsValid()) {
1688 }
1689}
1690
1692{
1693 return RPCHelpMan{
1694 "invalidateblock",
1695 "Permanently marks a block as invalid, as if it violated a consensus rule.\n",
1696 {
1697 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as invalid"},
1698 },
1701 HelpExampleCli("invalidateblock", "\"blockhash\"")
1702 + HelpExampleRpc("invalidateblock", "\"blockhash\"")
1703 },
1704 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1705{
1706 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1707 uint256 hash(ParseHashV(request.params[0], "blockhash"));
1708
1709 InvalidateBlock(chainman, hash);
1710
1711 return UniValue::VNULL;
1712},
1713 };
1714}
1715
1716void ReconsiderBlock(ChainstateManager& chainman, uint256 block_hash) {
1717 {
1718 LOCK(chainman.GetMutex());
1719 CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1720 if (!pblockindex) {
1721 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1722 }
1723
1724 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1725 chainman.RecalculateBestHeader();
1726 }
1727
1729 chainman.ActiveChainstate().ActivateBestChain(state);
1730
1731 if (!state.IsValid()) {
1733 }
1734}
1735
1737{
1738 return RPCHelpMan{
1739 "reconsiderblock",
1740 "Removes invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1741 "This can be used to undo the effects of invalidateblock.\n",
1742 {
1743 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to reconsider"},
1744 },
1747 HelpExampleCli("reconsiderblock", "\"blockhash\"")
1748 + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
1749 },
1750 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1751{
1752 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1753 uint256 hash(ParseHashV(request.params[0], "blockhash"));
1754
1755 ReconsiderBlock(chainman, hash);
1756
1757 return UniValue::VNULL;
1758},
1759 };
1760}
1761
1763{
1764 return RPCHelpMan{
1765 "getchaintxstats",
1766 "Compute statistics about the total number and rate of transactions in the chain.\n",
1767 {
1768 {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{"one month"}, "Size of the window in number of blocks"},
1769 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::DefaultHint{"chain tip"}, "The hash of the block that ends the window."},
1770 },
1771 RPCResult{
1772 RPCResult::Type::OBJ, "", "",
1773 {
1774 {RPCResult::Type::NUM_TIME, "time", "The timestamp for the final block in the window, expressed in " + UNIX_EPOCH_TIME},
1775 {RPCResult::Type::NUM, "txcount", /*optional=*/true,
1776 "The total number of transactions in the chain up to that point, if known. "
1777 "It may be unknown when using assumeutxo."},
1778 {RPCResult::Type::STR_HEX, "window_final_block_hash", "The hash of the final block in the window"},
1779 {RPCResult::Type::NUM, "window_final_block_height", "The height of the final block in the window."},
1780 {RPCResult::Type::NUM, "window_block_count", "Size of the window in number of blocks"},
1781 {RPCResult::Type::NUM, "window_interval", /*optional=*/true, "The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1782 {RPCResult::Type::NUM, "window_tx_count", /*optional=*/true,
1783 "The number of transactions in the window. "
1784 "Only returned if \"window_block_count\" is > 0 and if txcount exists for the start and end of the window."},
1785 {RPCResult::Type::NUM, "txrate", /*optional=*/true,
1786 "The average rate of transactions per second in the window. "
1787 "Only returned if \"window_interval\" is > 0 and if window_tx_count exists."},
1788 }},
1790 HelpExampleCli("getchaintxstats", "")
1791 + HelpExampleRpc("getchaintxstats", "2016")
1792 },
1793 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1794{
1795 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1796 const CBlockIndex* pindex;
1797 int blockcount = 30 * 24 * 60 * 60 / chainman.GetParams().GetConsensus().nPowTargetSpacing; // By default: 1 month
1798
1799 if (request.params[1].isNull()) {
1800 LOCK(cs_main);
1801 pindex = chainman.ActiveChain().Tip();
1802 } else {
1803 uint256 hash(ParseHashV(request.params[1], "blockhash"));
1804 LOCK(cs_main);
1805 pindex = chainman.m_blockman.LookupBlockIndex(hash);
1806 if (!pindex) {
1807 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1808 }
1809 if (!chainman.ActiveChain().Contains(pindex)) {
1810 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
1811 }
1812 }
1813
1814 CHECK_NONFATAL(pindex != nullptr);
1815
1816 if (request.params[0].isNull()) {
1817 blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
1818 } else {
1819 blockcount = request.params[0].getInt<int>();
1820
1821 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
1822 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
1823 }
1824 }
1825
1826 const CBlockIndex& past_block{*CHECK_NONFATAL(pindex->GetAncestor(pindex->nHeight - blockcount))};
1827 const int64_t nTimeDiff{pindex->GetMedianTimePast() - past_block.GetMedianTimePast()};
1828
1830 ret.pushKV("time", (int64_t)pindex->nTime);
1831 if (pindex->m_chain_tx_count) {
1832 ret.pushKV("txcount", pindex->m_chain_tx_count);
1833 }
1834 ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex());
1835 ret.pushKV("window_final_block_height", pindex->nHeight);
1836 ret.pushKV("window_block_count", blockcount);
1837 if (blockcount > 0) {
1838 ret.pushKV("window_interval", nTimeDiff);
1839 if (pindex->m_chain_tx_count != 0 && past_block.m_chain_tx_count != 0) {
1840 const auto window_tx_count = pindex->m_chain_tx_count - past_block.m_chain_tx_count;
1841 ret.pushKV("window_tx_count", window_tx_count);
1842 if (nTimeDiff > 0) {
1843 ret.pushKV("txrate", double(window_tx_count) / nTimeDiff);
1844 }
1845 }
1846 }
1847
1848 return ret;
1849},
1850 };
1851}
1852
1853template<typename T>
1854static T CalculateTruncatedMedian(std::vector<T>& scores)
1855{
1856 size_t size = scores.size();
1857 if (size == 0) {
1858 return 0;
1859 }
1860
1861 std::sort(scores.begin(), scores.end());
1862 if (size % 2 == 0) {
1863 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1864 } else {
1865 return scores[size / 2];
1866 }
1867}
1868
1869void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight)
1870{
1871 if (scores.empty()) {
1872 return;
1873 }
1874
1875 std::sort(scores.begin(), scores.end());
1876
1877 // 10th, 25th, 50th, 75th, and 90th percentile weight units.
1878 const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
1879 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1880 };
1881
1882 int64_t next_percentile_index = 0;
1883 int64_t cumulative_weight = 0;
1884 for (const auto& element : scores) {
1885 cumulative_weight += element.second;
1886 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1887 result[next_percentile_index] = element.first;
1888 ++next_percentile_index;
1889 }
1890 }
1891
1892 // Fill any remaining percentiles with the last value.
1893 for (int64_t i = next_percentile_index; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
1894 result[i] = scores.back().first;
1895 }
1896}
1897
1898template<typename T>
1899static inline bool SetHasKeys(const std::set<T>& set) {return false;}
1900template<typename T, typename Tk, typename... Args>
1901static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
1902{
1903 return (set.count(key) != 0) || SetHasKeys(set, args...);
1904}
1905
1906// outpoint (needed for the utxo index) + nHeight + fCoinBase
1907static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
1908
1910{
1911 return RPCHelpMan{
1912 "getblockstats",
1913 "Compute per block statistics for a given window. All amounts are in satoshis.\n"
1914 "It won't work for some heights with pruning.\n",
1915 {
1916 {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block hash or height of the target block",
1918 .skip_type_check = true,
1919 .type_str = {"", "string or numeric"},
1920 }},
1921 {"stats", RPCArg::Type::ARR, RPCArg::DefaultHint{"all values"}, "Values to plot (see result below)",
1922 {
1923 {"height", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
1924 {"time", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
1925 },
1927 },
1928 RPCResult{
1929 RPCResult::Type::OBJ, "", "",
1930 {
1931 {RPCResult::Type::NUM, "avgfee", /*optional=*/true, "Average fee in the block"},
1932 {RPCResult::Type::NUM, "avgfeerate", /*optional=*/true, "Average feerate (in satoshis per virtual byte)"},
1933 {RPCResult::Type::NUM, "avgtxsize", /*optional=*/true, "Average transaction size"},
1934 {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block hash (to check for potential reorgs)"},
1935 {RPCResult::Type::ARR_FIXED, "feerate_percentiles", /*optional=*/true, "Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
1936 {
1937 {RPCResult::Type::NUM, "10th_percentile_feerate", "The 10th percentile feerate"},
1938 {RPCResult::Type::NUM, "25th_percentile_feerate", "The 25th percentile feerate"},
1939 {RPCResult::Type::NUM, "50th_percentile_feerate", "The 50th percentile feerate"},
1940 {RPCResult::Type::NUM, "75th_percentile_feerate", "The 75th percentile feerate"},
1941 {RPCResult::Type::NUM, "90th_percentile_feerate", "The 90th percentile feerate"},
1942 }},
1943 {RPCResult::Type::NUM, "height", /*optional=*/true, "The height of the block"},
1944 {RPCResult::Type::NUM, "ins", /*optional=*/true, "The number of inputs (excluding coinbase)"},
1945 {RPCResult::Type::NUM, "maxfee", /*optional=*/true, "Maximum fee in the block"},
1946 {RPCResult::Type::NUM, "maxfeerate", /*optional=*/true, "Maximum feerate (in satoshis per virtual byte)"},
1947 {RPCResult::Type::NUM, "maxtxsize", /*optional=*/true, "Maximum transaction size"},
1948 {RPCResult::Type::NUM, "medianfee", /*optional=*/true, "Truncated median fee in the block"},
1949 {RPCResult::Type::NUM, "mediantime", /*optional=*/true, "The block median time past"},
1950 {RPCResult::Type::NUM, "mediantxsize", /*optional=*/true, "Truncated median transaction size"},
1951 {RPCResult::Type::NUM, "minfee", /*optional=*/true, "Minimum fee in the block"},
1952 {RPCResult::Type::NUM, "minfeerate", /*optional=*/true, "Minimum feerate (in satoshis per virtual byte)"},
1953 {RPCResult::Type::NUM, "mintxsize", /*optional=*/true, "Minimum transaction size"},
1954 {RPCResult::Type::NUM, "outs", /*optional=*/true, "The number of outputs"},
1955 {RPCResult::Type::NUM, "subsidy", /*optional=*/true, "The block subsidy"},
1956 {RPCResult::Type::NUM, "swtotal_size", /*optional=*/true, "Total size of all segwit transactions"},
1957 {RPCResult::Type::NUM, "swtotal_weight", /*optional=*/true, "Total weight of all segwit transactions"},
1958 {RPCResult::Type::NUM, "swtxs", /*optional=*/true, "The number of segwit transactions"},
1959 {RPCResult::Type::NUM, "time", /*optional=*/true, "The block time"},
1960 {RPCResult::Type::NUM, "total_out", /*optional=*/true, "Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
1961 {RPCResult::Type::NUM, "total_size", /*optional=*/true, "Total size of all non-coinbase transactions"},
1962 {RPCResult::Type::NUM, "total_weight", /*optional=*/true, "Total weight of all non-coinbase transactions"},
1963 {RPCResult::Type::NUM, "totalfee", /*optional=*/true, "The fee total"},
1964 {RPCResult::Type::NUM, "txs", /*optional=*/true, "The number of transactions (including coinbase)"},
1965 {RPCResult::Type::NUM, "utxo_increase", /*optional=*/true, "The increase/decrease in the number of unspent outputs (not discounting op_return and similar)"},
1966 {RPCResult::Type::NUM, "utxo_size_inc", /*optional=*/true, "The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
1967 {RPCResult::Type::NUM, "utxo_increase_actual", /*optional=*/true, "The increase/decrease in the number of unspent outputs, not counting unspendables"},
1968 {RPCResult::Type::NUM, "utxo_size_inc_actual", /*optional=*/true, "The increase/decrease in size for the utxo index, not counting unspendables"},
1969 }},
1971 HelpExampleCli("getblockstats", R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
1972 HelpExampleCli("getblockstats", R"(1000 '["minfeerate","avgfeerate"]')") +
1973 HelpExampleRpc("getblockstats", R"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
1974 HelpExampleRpc("getblockstats", R"(1000, ["minfeerate","avgfeerate"])")
1975 },
1976 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1977{
1978 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1979 const CBlockIndex& pindex{*CHECK_NONFATAL(ParseHashOrHeight(request.params[0], chainman))};
1980
1981 std::set<std::string> stats;
1982 if (!request.params[1].isNull()) {
1983 const UniValue stats_univalue = request.params[1].get_array();
1984 for (unsigned int i = 0; i < stats_univalue.size(); i++) {
1985 const std::string stat = stats_univalue[i].get_str();
1986 stats.insert(stat);
1987 }
1988 }
1989
1990 const CBlock& block = GetBlockChecked(chainman.m_blockman, pindex);
1991 const CBlockUndo& blockUndo = GetUndoChecked(chainman.m_blockman, pindex);
1992
1993 const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
1994 const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
1995 const bool do_medianfee = do_all || stats.count("medianfee") != 0;
1996 const bool do_feerate_percentiles = do_all || stats.count("feerate_percentiles") != 0;
1997 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
1998 SetHasKeys(stats, "utxo_increase", "utxo_increase_actual", "utxo_size_inc", "utxo_size_inc_actual", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
1999 const bool loop_outputs = do_all || loop_inputs || stats.count("total_out");
2000 const bool do_calculate_size = do_mediantxsize ||
2001 SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size");
2002 const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "feerate_percentiles", "minfeerate", "maxfeerate");
2003 const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight");
2004
2005 CAmount maxfee = 0;
2006 CAmount maxfeerate = 0;
2007 CAmount minfee = MAX_MONEY;
2008 CAmount minfeerate = MAX_MONEY;
2009 CAmount total_out = 0;
2010 CAmount totalfee = 0;
2011 int64_t inputs = 0;
2012 int64_t maxtxsize = 0;
2013 int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
2014 int64_t outputs = 0;
2015 int64_t swtotal_size = 0;
2016 int64_t swtotal_weight = 0;
2017 int64_t swtxs = 0;
2018 int64_t total_size = 0;
2019 int64_t total_weight = 0;
2020 int64_t utxos = 0;
2021 int64_t utxo_size_inc = 0;
2022 int64_t utxo_size_inc_actual = 0;
2023 std::vector<CAmount> fee_array;
2024 std::vector<std::pair<CAmount, int64_t>> feerate_array;
2025 std::vector<int64_t> txsize_array;
2026
2027 for (size_t i = 0; i < block.vtx.size(); ++i) {
2028 const auto& tx = block.vtx.at(i);
2029 outputs += tx->vout.size();
2030
2031 CAmount tx_total_out = 0;
2032 if (loop_outputs) {
2033 for (const CTxOut& out : tx->vout) {
2034 tx_total_out += out.nValue;
2035
2036 size_t out_size = GetSerializeSize(out) + PER_UTXO_OVERHEAD;
2037 utxo_size_inc += out_size;
2038
2039 // The Genesis block and the repeated BIP30 block coinbases don't change the UTXO
2040 // set counts, so they have to be excluded from the statistics
2041 if (pindex.nHeight == 0 || (IsBIP30Repeat(pindex) && tx->IsCoinBase())) continue;
2042 // Skip unspendable outputs since they are not included in the UTXO set
2043 if (out.scriptPubKey.IsUnspendable()) continue;
2044
2045 ++utxos;
2046 utxo_size_inc_actual += out_size;
2047 }
2048 }
2049
2050 if (tx->IsCoinBase()) {
2051 continue;
2052 }
2053
2054 inputs += tx->vin.size(); // Don't count coinbase's fake input
2055 total_out += tx_total_out; // Don't count coinbase reward
2056
2057 int64_t tx_size = 0;
2058 if (do_calculate_size) {
2059
2060 tx_size = tx->GetTotalSize();
2061 if (do_mediantxsize) {
2062 txsize_array.push_back(tx_size);
2063 }
2064 maxtxsize = std::max(maxtxsize, tx_size);
2065 mintxsize = std::min(mintxsize, tx_size);
2066 total_size += tx_size;
2067 }
2068
2069 int64_t weight = 0;
2070 if (do_calculate_weight) {
2071 weight = GetTransactionWeight(*tx);
2072 total_weight += weight;
2073 }
2074
2075 if (do_calculate_sw && tx->HasWitness()) {
2076 ++swtxs;
2077 swtotal_size += tx_size;
2078 swtotal_weight += weight;
2079 }
2080
2081 if (loop_inputs) {
2082 CAmount tx_total_in = 0;
2083 const auto& txundo = blockUndo.vtxundo.at(i - 1);
2084 for (const Coin& coin: txundo.vprevout) {
2085 const CTxOut& prevoutput = coin.out;
2086
2087 tx_total_in += prevoutput.nValue;
2088 size_t prevout_size = GetSerializeSize(prevoutput) + PER_UTXO_OVERHEAD;
2089 utxo_size_inc -= prevout_size;
2090 utxo_size_inc_actual -= prevout_size;
2091 }
2092
2093 CAmount txfee = tx_total_in - tx_total_out;
2094 CHECK_NONFATAL(MoneyRange(txfee));
2095 if (do_medianfee) {
2096 fee_array.push_back(txfee);
2097 }
2098 maxfee = std::max(maxfee, txfee);
2099 minfee = std::min(minfee, txfee);
2100 totalfee += txfee;
2101
2102 // New feerate uses satoshis per virtual byte instead of per serialized byte
2103 CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
2104 if (do_feerate_percentiles) {
2105 feerate_array.emplace_back(feerate, weight);
2106 }
2107 maxfeerate = std::max(maxfeerate, feerate);
2108 minfeerate = std::min(minfeerate, feerate);
2109 }
2110 }
2111
2112 CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
2113 CalculatePercentilesByWeight(feerate_percentiles, feerate_array, total_weight);
2114
2115 UniValue feerates_res(UniValue::VARR);
2116 for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
2117 feerates_res.push_back(feerate_percentiles[i]);
2118 }
2119
2120 UniValue ret_all(UniValue::VOBJ);
2121 ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
2122 ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
2123 ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
2124 ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
2125 ret_all.pushKV("feerate_percentiles", std::move(feerates_res));
2126 ret_all.pushKV("height", (int64_t)pindex.nHeight);
2127 ret_all.pushKV("ins", inputs);
2128 ret_all.pushKV("maxfee", maxfee);
2129 ret_all.pushKV("maxfeerate", maxfeerate);
2130 ret_all.pushKV("maxtxsize", maxtxsize);
2131 ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
2132 ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
2133 ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
2134 ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
2135 ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
2136 ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
2137 ret_all.pushKV("outs", outputs);
2138 ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight, chainman.GetParams().GetConsensus()));
2139 ret_all.pushKV("swtotal_size", swtotal_size);
2140 ret_all.pushKV("swtotal_weight", swtotal_weight);
2141 ret_all.pushKV("swtxs", swtxs);
2142 ret_all.pushKV("time", pindex.GetBlockTime());
2143 ret_all.pushKV("total_out", total_out);
2144 ret_all.pushKV("total_size", total_size);
2145 ret_all.pushKV("total_weight", total_weight);
2146 ret_all.pushKV("totalfee", totalfee);
2147 ret_all.pushKV("txs", (int64_t)block.vtx.size());
2148 ret_all.pushKV("utxo_increase", outputs - inputs);
2149 ret_all.pushKV("utxo_size_inc", utxo_size_inc);
2150 ret_all.pushKV("utxo_increase_actual", utxos - inputs);
2151 ret_all.pushKV("utxo_size_inc_actual", utxo_size_inc_actual);
2152
2153 if (do_all) {
2154 return ret_all;
2155 }
2156
2158 for (const std::string& stat : stats) {
2159 const UniValue& value = ret_all[stat];
2160 if (value.isNull()) {
2161 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic '%s'", stat));
2162 }
2163 ret.pushKV(stat, value);
2164 }
2165 return ret;
2166},
2167 };
2168}
2169
2170namespace {
2172bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>& should_abort, int64_t& count, CCoinsViewCursor* cursor, const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results, std::function<void()>& interruption_point)
2173{
2174 scan_progress = 0;
2175 count = 0;
2176 while (cursor->Valid()) {
2177 COutPoint key;
2178 Coin coin;
2179 if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
2180 if (++count % 8192 == 0) {
2181 interruption_point();
2182 if (should_abort) {
2183 // allow to abort the scan via the abort reference
2184 return false;
2185 }
2186 }
2187 if (count % 256 == 0) {
2188 // update progress reference every 256 item
2189 uint32_t high = 0x100 * *UCharCast(key.hash.begin()) + *(UCharCast(key.hash.begin()) + 1);
2190 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2191 }
2192 if (needles.count(coin.out.scriptPubKey)) {
2193 out_results.emplace(key, coin);
2194 }
2195 cursor->Next();
2196 }
2197 scan_progress = 100;
2198 return true;
2199}
2200} // namespace
2201
2203static std::atomic<int> g_scan_progress;
2204static std::atomic<bool> g_scan_in_progress;
2205static std::atomic<bool> g_should_abort_scan;
2207{
2208private:
2209 bool m_could_reserve{false};
2210public:
2211 explicit CoinsViewScanReserver() = default;
2212
2213 bool reserve() {
2215 if (g_scan_in_progress.exchange(true)) {
2216 return false;
2217 }
2219 m_could_reserve = true;
2220 return true;
2221 }
2222
2224 if (m_could_reserve) {
2225 g_scan_in_progress = false;
2226 g_scan_progress = 0;
2227 }
2228 }
2229};
2230
2231static const auto scan_action_arg_desc = RPCArg{
2232 "action", RPCArg::Type::STR, RPCArg::Optional::NO, "The action to execute\n"
2233 "\"start\" for starting a scan\n"
2234 "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2235 "\"status\" for progress report (in %) of the current scan"
2236};
2237
2238static const auto output_descriptor_obj = RPCArg{
2239 "", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with output descriptor and metadata",
2240 {
2241 {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
2242 {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "The range of HD chain indexes to explore (either end or [begin,end])"},
2243 }
2244};
2245
2246static const auto scan_objects_arg_desc = RPCArg{
2247 "scanobjects", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Array of scan objects. Required for \"start\" action\n"
2248 "Every scan object is either a string descriptor or an object:",
2249 {
2250 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
2252 },
2253 RPCArgOptions{.oneline_description="[scanobjects,...]"},
2254};
2255
2256static const auto scan_result_abort = RPCResult{
2257 "when action=='abort'", RPCResult::Type::BOOL, "success",
2258 "True if scan will be aborted (not necessarily before this RPC returns), or false if there is no scan to abort"
2259};
2261 "when action=='status' and no scan is in progress - possibly already completed", RPCResult::Type::NONE, "", ""
2262};
2264 "when action=='status' and a scan is currently in progress", RPCResult::Type::OBJ, "", "",
2265 {{RPCResult::Type::NUM, "progress", "Approximate percent complete"},}
2266};
2267
2268
2270{
2271 // raw() descriptor corresponding to mainnet address 12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S
2272 const std::string EXAMPLE_DESCRIPTOR_RAW = "raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2273
2274 return RPCHelpMan{
2275 "scantxoutset",
2276 "Scans the unspent transaction output set for entries that match certain output descriptors.\n"
2277 "Examples of output descriptors are:\n"
2278 " addr(<address>) Outputs whose output script corresponds to the specified address (does not include P2PK)\n"
2279 " raw(<hex script>) Outputs whose output script equals the specified hex-encoded bytes\n"
2280 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2281 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
2282 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2283 " tr(<pubkey>) P2TR\n"
2284 " tr(<pubkey>,{pk(<pubkey>)}) P2TR with single fallback pubkey in tapscript\n"
2285 " rawtr(<pubkey>) P2TR with the specified key as output key rather than inner\n"
2286 " wsh(and_v(v:pk(<pubkey>),after(2))) P2WSH miniscript with mandatory pubkey and a timelock\n"
2287 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2288 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2289 "unhardened or hardened child keys.\n"
2290 "In the latter case, a range needs to be specified by below if different from 1000.\n"
2291 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2292 {
2295 },
2296 {
2297 RPCResult{"when action=='start'; only returns after scan completes", RPCResult::Type::OBJ, "", "", {
2298 {RPCResult::Type::BOOL, "success", "Whether the scan was completed"},
2299 {RPCResult::Type::NUM, "txouts", "The number of unspent transaction outputs scanned"},
2300 {RPCResult::Type::NUM, "height", "The block height at which the scan was done"},
2301 {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at the tip of the chain"},
2302 {RPCResult::Type::ARR, "unspents", "",
2303 {
2304 {RPCResult::Type::OBJ, "", "",
2305 {
2306 {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
2307 {RPCResult::Type::NUM, "vout", "The vout value"},
2308 {RPCResult::Type::STR_HEX, "scriptPubKey", "The output script"},
2309 {RPCResult::Type::STR, "desc", "A specialized descriptor for the matched output script"},
2310 {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the unspent output"},
2311 {RPCResult::Type::BOOL, "coinbase", "Whether this is a coinbase output"},
2312 {RPCResult::Type::NUM, "height", "Height of the unspent transaction output"},
2313 {RPCResult::Type::STR_HEX, "blockhash", "Blockhash of the unspent transaction output"},
2314 {RPCResult::Type::NUM, "confirmations", "Number of confirmations of the unspent transaction output when the scan was done"},
2315 }},
2316 }},
2317 {RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of all found unspent outputs in " + CURRENCY_UNIT},
2318 }},
2322 },
2324 HelpExampleCli("scantxoutset", "start \'[\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]\'") +
2325 HelpExampleCli("scantxoutset", "status") +
2326 HelpExampleCli("scantxoutset", "abort") +
2327 HelpExampleRpc("scantxoutset", "\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]") +
2328 HelpExampleRpc("scantxoutset", "\"status\"") +
2329 HelpExampleRpc("scantxoutset", "\"abort\"")
2330 },
2331 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
2332{
2333 UniValue result(UniValue::VOBJ);
2334 const auto action{self.Arg<std::string_view>("action")};
2335 if (action == "status") {
2336 CoinsViewScanReserver reserver;
2337 if (reserver.reserve()) {
2338 // no scan in progress
2339 return UniValue::VNULL;
2340 }
2341 result.pushKV("progress", g_scan_progress.load());
2342 return result;
2343 } else if (action == "abort") {
2344 CoinsViewScanReserver reserver;
2345 if (reserver.reserve()) {
2346 // reserve was possible which means no scan was running
2347 return false;
2348 }
2349 // set the abort flag
2350 g_should_abort_scan = true;
2351 return true;
2352 } else if (action == "start") {
2353 CoinsViewScanReserver reserver;
2354 if (!reserver.reserve()) {
2355 throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
2356 }
2357
2358 if (request.params.size() < 2) {
2359 throw JSONRPCError(RPC_MISC_ERROR, "scanobjects argument is required for the start action");
2360 }
2361
2362 std::set<CScript> needles;
2363 std::map<CScript, std::string> descriptors;
2364 CAmount total_in = 0;
2365
2366 // loop through the scan objects
2367 for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2368 FlatSigningProvider provider;
2369 auto scripts = EvalDescriptorStringOrObject(scanobject, provider);
2370 for (CScript& script : scripts) {
2371 std::string inferred = InferDescriptor(script, provider)->ToString();
2372 needles.emplace(script);
2373 descriptors.emplace(std::move(script), std::move(inferred));
2374 }
2375 }
2376
2377 // Scan the unspent transaction output set for inputs
2378 UniValue unspents(UniValue::VARR);
2379 std::vector<CTxOut> input_txos;
2380 std::map<COutPoint, Coin> coins;
2381 g_should_abort_scan = false;
2382 int64_t count = 0;
2383 std::unique_ptr<CCoinsViewCursor> pcursor;
2384 const CBlockIndex* tip;
2385 NodeContext& node = EnsureAnyNodeContext(request.context);
2386 {
2388 LOCK(cs_main);
2389 Chainstate& active_chainstate = chainman.ActiveChainstate();
2390 active_chainstate.ForceFlushStateToDisk();
2391 pcursor = CHECK_NONFATAL(active_chainstate.CoinsDB().Cursor());
2392 tip = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
2393 }
2394 bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point);
2395 result.pushKV("success", res);
2396 result.pushKV("txouts", count);
2397 result.pushKV("height", tip->nHeight);
2398 result.pushKV("bestblock", tip->GetBlockHash().GetHex());
2399
2400 for (const auto& it : coins) {
2401 const COutPoint& outpoint = it.first;
2402 const Coin& coin = it.second;
2403 const CTxOut& txo = coin.out;
2404 const CBlockIndex& coinb_block{*CHECK_NONFATAL(tip->GetAncestor(coin.nHeight))};
2405 input_txos.push_back(txo);
2406 total_in += txo.nValue;
2407
2408 UniValue unspent(UniValue::VOBJ);
2409 unspent.pushKV("txid", outpoint.hash.GetHex());
2410 unspent.pushKV("vout", outpoint.n);
2411 unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey));
2412 unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
2413 unspent.pushKV("amount", ValueFromAmount(txo.nValue));
2414 unspent.pushKV("coinbase", coin.IsCoinBase());
2415 unspent.pushKV("height", coin.nHeight);
2416 unspent.pushKV("blockhash", coinb_block.GetBlockHash().GetHex());
2417 unspent.pushKV("confirmations", tip->nHeight - coin.nHeight + 1);
2418
2419 unspents.push_back(std::move(unspent));
2420 }
2421 result.pushKV("unspents", std::move(unspents));
2422 result.pushKV("total_amount", ValueFromAmount(total_in));
2423 } else {
2424 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid action '%s'", action));
2425 }
2426 return result;
2427},
2428 };
2429}
2430
2432static std::atomic<int> g_scanfilter_progress;
2433static std::atomic<int> g_scanfilter_progress_height;
2434static std::atomic<bool> g_scanfilter_in_progress;
2435static std::atomic<bool> g_scanfilter_should_abort_scan;
2437{
2438private:
2439 bool m_could_reserve{false};
2440public:
2441 explicit BlockFiltersScanReserver() = default;
2442
2443 bool reserve() {
2445 if (g_scanfilter_in_progress.exchange(true)) {
2446 return false;
2447 }
2448 m_could_reserve = true;
2449 return true;
2450 }
2451
2453 if (m_could_reserve) {
2455 }
2456 }
2457};
2458
2459static bool CheckBlockFilterMatches(BlockManager& blockman, const CBlockIndex& blockindex, const GCSFilter::ElementSet& needles)
2460{
2461 const CBlock block{GetBlockChecked(blockman, blockindex)};
2462 const CBlockUndo block_undo{GetUndoChecked(blockman, blockindex)};
2463
2464 // Check if any of the outputs match the scriptPubKey
2465 for (const auto& tx : block.vtx) {
2466 if (std::any_of(tx->vout.cbegin(), tx->vout.cend(), [&](const auto& txout) {
2467 return needles.count(std::vector<unsigned char>(txout.scriptPubKey.begin(), txout.scriptPubKey.end())) != 0;
2468 })) {
2469 return true;
2470 }
2471 }
2472 // Check if any of the inputs match the scriptPubKey
2473 for (const auto& txundo : block_undo.vtxundo) {
2474 if (std::any_of(txundo.vprevout.cbegin(), txundo.vprevout.cend(), [&](const auto& coin) {
2475 return needles.count(std::vector<unsigned char>(coin.out.scriptPubKey.begin(), coin.out.scriptPubKey.end())) != 0;
2476 })) {
2477 return true;
2478 }
2479 }
2480
2481 return false;
2482}
2483
2485{
2486 return RPCHelpMan{
2487 "scanblocks",
2488 "Return relevant blockhashes for given descriptors (requires blockfilterindex).\n"
2489 "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2490 {
2493 RPCArg{"start_height", RPCArg::Type::NUM, RPCArg::Default{0}, "Height to start to scan from"},
2494 RPCArg{"stop_height", RPCArg::Type::NUM, RPCArg::DefaultHint{"chain tip"}, "Height to stop to scan"},
2495 RPCArg{"filtertype", RPCArg::Type::STR, RPCArg::Default{BlockFilterTypeName(BlockFilterType::BASIC)}, "The type name of the filter"},
2497 {
2498 {"filter_false_positives", RPCArg::Type::BOOL, RPCArg::Default{false}, "Filter false positives (slower and may fail on pruned nodes). Otherwise they may occur at a rate of 1/M"},
2499 },
2501 },
2502 {
2504 RPCResult{"When action=='start'; only returns after scan completes", RPCResult::Type::OBJ, "", "", {
2505 {RPCResult::Type::NUM, "from_height", "The height we started the scan from"},
2506 {RPCResult::Type::NUM, "to_height", "The height we ended the scan at"},
2507 {RPCResult::Type::ARR, "relevant_blocks", "Blocks that may have matched a scanobject.", {
2508 {RPCResult::Type::STR_HEX, "blockhash", "A relevant blockhash"},
2509 }},
2510 {RPCResult::Type::BOOL, "completed", "true if the scan process was not aborted"}
2511 }},
2512 RPCResult{"when action=='status' and a scan is currently in progress", RPCResult::Type::OBJ, "", "", {
2513 {RPCResult::Type::NUM, "progress", "Approximate percent complete"},
2514 {RPCResult::Type::NUM, "current_height", "Height of the block currently being scanned"},
2515 },
2516 },
2518 },
2520 HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 300000") +
2521 HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 100 150 basic") +
2522 HelpExampleCli("scanblocks", "status") +
2523 HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 300000") +
2524 HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 100, 150, \"basic\"") +
2525 HelpExampleRpc("scanblocks", "\"status\"")
2526 },
2527 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
2528{
2530 auto action{self.Arg<std::string_view>("action")};
2531 if (action == "status") {
2532 BlockFiltersScanReserver reserver;
2533 if (reserver.reserve()) {
2534 // no scan in progress
2535 return NullUniValue;
2536 }
2537 ret.pushKV("progress", g_scanfilter_progress.load());
2538 ret.pushKV("current_height", g_scanfilter_progress_height.load());
2539 return ret;
2540 } else if (action == "abort") {
2541 BlockFiltersScanReserver reserver;
2542 if (reserver.reserve()) {
2543 // reserve was possible which means no scan was running
2544 return false;
2545 }
2546 // set the abort flag
2548 return true;
2549 } else if (action == "start") {
2550 BlockFiltersScanReserver reserver;
2551 if (!reserver.reserve()) {
2552 throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
2553 }
2554 auto filtertype_name{self.Arg<std::string_view>("filtertype")};
2555
2556 BlockFilterType filtertype;
2557 if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2558 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
2559 }
2560
2561 UniValue options{request.params[5].isNull() ? UniValue::VOBJ : request.params[5]};
2562 bool filter_false_positives{options.exists("filter_false_positives") ? options["filter_false_positives"].get_bool() : false};
2563
2564 BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
2565 if (!index) {
2566 throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
2567 }
2568
2569 NodeContext& node = EnsureAnyNodeContext(request.context);
2571
2572 // set the start-height
2573 const CBlockIndex* start_index = nullptr;
2574 const CBlockIndex* stop_block = nullptr;
2575 {
2576 LOCK(cs_main);
2577 CChain& active_chain = chainman.ActiveChain();
2578 start_index = active_chain.Genesis();
2579 stop_block = active_chain.Tip(); // If no stop block is provided, stop at the chain tip.
2580 if (!request.params[2].isNull()) {
2581 start_index = active_chain[request.params[2].getInt<int>()];
2582 if (!start_index) {
2583 throw JSONRPCError(RPC_MISC_ERROR, "Invalid start_height");
2584 }
2585 }
2586 if (!request.params[3].isNull()) {
2587 stop_block = active_chain[request.params[3].getInt<int>()];
2588 if (!stop_block || stop_block->nHeight < start_index->nHeight) {
2589 throw JSONRPCError(RPC_MISC_ERROR, "Invalid stop_height");
2590 }
2591 }
2592 }
2593 CHECK_NONFATAL(start_index);
2594 CHECK_NONFATAL(stop_block);
2595
2596 // loop through the scan objects, add scripts to the needle_set
2597 GCSFilter::ElementSet needle_set;
2598 for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2599 FlatSigningProvider provider;
2600 std::vector<CScript> scripts = EvalDescriptorStringOrObject(scanobject, provider);
2601 for (const CScript& script : scripts) {
2602 needle_set.emplace(script.begin(), script.end());
2603 }
2604 }
2605 UniValue blocks(UniValue::VARR);
2606 const int amount_per_chunk = 10000;
2607 std::vector<BlockFilter> filters;
2608 int start_block_height = start_index->nHeight; // for progress reporting
2609 const int total_blocks_to_process = stop_block->nHeight - start_block_height;
2610
2613 g_scanfilter_progress_height = start_block_height;
2614 bool completed = true;
2615
2616 const CBlockIndex* end_range = nullptr;
2617 do {
2618 node.rpc_interruption_point(); // allow a clean shutdown
2620 completed = false;
2621 break;
2622 }
2623
2624 // split the lookup range in chunks if we are deeper than 'amount_per_chunk' blocks from the stopping block
2625 int start_block = !end_range ? start_index->nHeight : start_index->nHeight + 1; // to not include the previous round 'end_range' block
2626 end_range = (start_block + amount_per_chunk < stop_block->nHeight) ?
2627 WITH_LOCK(::cs_main, return chainman.ActiveChain()[start_block + amount_per_chunk]) :
2628 stop_block;
2629
2630 if (index->LookupFilterRange(start_block, end_range, filters)) {
2631 for (const BlockFilter& filter : filters) {
2632 // compare the elements-set with each filter
2633 if (filter.GetFilter().MatchAny(needle_set)) {
2634 if (filter_false_positives) {
2635 // Double check the filter matches by scanning the block
2636 const CBlockIndex& blockindex = *CHECK_NONFATAL(WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(filter.GetBlockHash())));
2637
2638 if (!CheckBlockFilterMatches(chainman.m_blockman, blockindex, needle_set)) {
2639 continue;
2640 }
2641 }
2642
2643 blocks.push_back(filter.GetBlockHash().GetHex());
2644 }
2645 }
2646 }
2647 start_index = end_range;
2648
2649 // update progress
2650 int blocks_processed = end_range->nHeight - start_block_height;
2651 if (total_blocks_to_process > 0) { // avoid division by zero
2652 g_scanfilter_progress = (int)(100.0 / total_blocks_to_process * blocks_processed);
2653 } else {
2655 }
2657
2658 // Finish if we reached the stop block
2659 } while (start_index != stop_block);
2660
2661 ret.pushKV("from_height", start_block_height);
2662 ret.pushKV("to_height", start_index->nHeight); // start_index is always the last scanned block here
2663 ret.pushKV("relevant_blocks", std::move(blocks));
2664 ret.pushKV("completed", completed);
2665 } else {
2666 throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("Invalid action '%s'", action));
2667 }
2668 return ret;
2669},
2670 };
2671}
2672
2674{
2675 return RPCHelpMan{
2676 "getdescriptoractivity",
2677 "Get spend and receive activity associated with a set of descriptors for a set of blocks. "
2678 "This command pairs well with the `relevant_blocks` output of `scanblocks()`.\n"
2679 "This call may take several minutes. If you encounter timeouts, try specifying no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2680 {
2681 RPCArg{"blockhashes", RPCArg::Type::ARR, RPCArg::Optional::NO, "The list of blockhashes to examine for activity. Order doesn't matter. Must be along main chain or an error is thrown.\n", {
2682 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A valid blockhash"},
2683 }},
2684 RPCArg{"scanobjects", RPCArg::Type::ARR, RPCArg::Optional::NO, "The list of descriptors (scan objects) to examine for activity. Every scan object is either a string descriptor or an object:",
2685 {
2686 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
2688 },
2689 RPCArgOptions{.oneline_description="[scanobjects,...]"},
2690 },
2691 {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to include unconfirmed activity"},
2692 },
2693 RPCResult{
2694 RPCResult::Type::OBJ, "", "", {
2695 {RPCResult::Type::ARR, "activity", "events", {
2696 {RPCResult::Type::OBJ, "", "", {
2697 {RPCResult::Type::STR, "type", "always 'spend'"},
2698 {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the spent output"},
2699 {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The blockhash this spend appears in (omitted if unconfirmed)"},
2700 {RPCResult::Type::NUM, "height", /*optional=*/true, "Height of the spend (omitted if unconfirmed)"},
2701 {RPCResult::Type::STR_HEX, "spend_txid", "The txid of the spending transaction"},
2702 {RPCResult::Type::NUM, "spend_vin", "The input index of the spend"},
2703 {RPCResult::Type::STR_HEX, "prevout_txid", "The txid of the prevout"},
2704 {RPCResult::Type::NUM, "prevout_vout", "The vout of the prevout"},
2705 {RPCResult::Type::OBJ, "prevout_spk", "", ScriptPubKeyDoc()},
2706 }},
2707 {RPCResult::Type::OBJ, "", "", {
2708 {RPCResult::Type::STR, "type", "always 'receive'"},
2709 {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the new output"},
2710 {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block that this receive is in (omitted if unconfirmed)"},
2711 {RPCResult::Type::NUM, "height", /*optional=*/true, "The height of the receive (omitted if unconfirmed)"},
2712 {RPCResult::Type::STR_HEX, "txid", "The txid of the receiving transaction"},
2713 {RPCResult::Type::NUM, "vout", "The vout of the receiving output"},
2714 {RPCResult::Type::OBJ, "output_spk", "", ScriptPubKeyDoc()},
2715 }},
2716 // TODO is the skip_type_check avoidable with a heterogeneous ARR?
2717 }, /*skip_type_check=*/true},
2718 },
2719 },
2721 HelpExampleCli("getdescriptoractivity", "'[\"000000000000000000001347062c12fded7c528943c8ce133987e2e2f5a840ee\"]' '[\"addr(bc1qzl6nsgqzu89a66l50cvwapnkw5shh23zarqkw9)\"]'")
2722 },
2723 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
2724{
2726 UniValue activity(UniValue::VARR);
2727 NodeContext& node = EnsureAnyNodeContext(request.context);
2729
2730 struct CompareByHeightAscending {
2731 bool operator()(const CBlockIndex* a, const CBlockIndex* b) const {
2732 return a->nHeight < b->nHeight;
2733 }
2734 };
2735
2736 std::set<const CBlockIndex*, CompareByHeightAscending> blockindexes_sorted;
2737
2738 {
2739 // Validate all given blockhashes, and ensure blocks are along a single chain.
2740 LOCK(::cs_main);
2741 for (const UniValue& blockhash : request.params[0].get_array().getValues()) {
2742 uint256 bhash = ParseHashV(blockhash, "blockhash");
2743 CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(bhash);
2744 if (!pindex) {
2745 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2746 }
2747 if (!chainman.ActiveChain().Contains(pindex)) {
2748 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
2749 }
2750 blockindexes_sorted.insert(pindex);
2751 }
2752 }
2753
2754 std::set<CScript> scripts_to_watch;
2755
2756 // Determine scripts to watch.
2757 for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2758 FlatSigningProvider provider;
2759 std::vector<CScript> scripts = EvalDescriptorStringOrObject(scanobject, provider);
2760
2761 for (const CScript& script : scripts) {
2762 scripts_to_watch.insert(script);
2763 }
2764 }
2765
2766 const auto AddSpend = [&](
2767 const CScript& spk,
2768 const CAmount val,
2769 const CTransactionRef& tx,
2770 int vin,
2771 const CTxIn& txin,
2772 const CBlockIndex* index
2773 ) {
2774 UniValue event(UniValue::VOBJ);
2775 UniValue spkUv(UniValue::VOBJ);
2776 ScriptToUniv(spk, /*out=*/spkUv, /*include_hex=*/true, /*include_address=*/true);
2777
2778 event.pushKV("type", "spend");
2779 event.pushKV("amount", ValueFromAmount(val));
2780 if (index) {
2781 event.pushKV("blockhash", index->GetBlockHash().ToString());
2782 event.pushKV("height", index->nHeight);
2783 }
2784 event.pushKV("spend_txid", tx->GetHash().ToString());
2785 event.pushKV("spend_vin", vin);
2786 event.pushKV("prevout_txid", txin.prevout.hash.ToString());
2787 event.pushKV("prevout_vout", txin.prevout.n);
2788 event.pushKV("prevout_spk", spkUv);
2789
2790 return event;
2791 };
2792
2793 const auto AddReceive = [&](const CTxOut& txout, const CBlockIndex* index, int vout, const CTransactionRef& tx) {
2794 UniValue event(UniValue::VOBJ);
2795 UniValue spkUv(UniValue::VOBJ);
2796 ScriptToUniv(txout.scriptPubKey, /*out=*/spkUv, /*include_hex=*/true, /*include_address=*/true);
2797
2798 event.pushKV("type", "receive");
2799 event.pushKV("amount", ValueFromAmount(txout.nValue));
2800 if (index) {
2801 event.pushKV("blockhash", index->GetBlockHash().ToString());
2802 event.pushKV("height", index->nHeight);
2803 }
2804 event.pushKV("txid", tx->GetHash().ToString());
2805 event.pushKV("vout", vout);
2806 event.pushKV("output_spk", spkUv);
2807
2808 return event;
2809 };
2810
2811 BlockManager* blockman;
2812 Chainstate& active_chainstate = chainman.ActiveChainstate();
2813 {
2814 LOCK(::cs_main);
2815 blockman = CHECK_NONFATAL(&active_chainstate.m_blockman);
2816 }
2817
2818 for (const CBlockIndex* blockindex : blockindexes_sorted) {
2819 const CBlock block{GetBlockChecked(chainman.m_blockman, *blockindex)};
2820 const CBlockUndo block_undo{GetUndoChecked(*blockman, *blockindex)};
2821
2822 for (size_t i = 0; i < block.vtx.size(); ++i) {
2823 const auto& tx = block.vtx.at(i);
2824
2825 if (!tx->IsCoinBase()) {
2826 // skip coinbase; spends can't happen there.
2827 const auto& txundo = block_undo.vtxundo.at(i - 1);
2828
2829 for (size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2830 const auto& coin = txundo.vprevout.at(vin_idx);
2831 const auto& txin = tx->vin.at(vin_idx);
2832 if (scripts_to_watch.contains(coin.out.scriptPubKey)) {
2833 activity.push_back(AddSpend(
2834 coin.out.scriptPubKey, coin.out.nValue, tx, vin_idx, txin, blockindex));
2835 }
2836 }
2837 }
2838
2839 for (size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2840 const auto& vout = tx->vout.at(vout_idx);
2841 if (scripts_to_watch.contains(vout.scriptPubKey)) {
2842 activity.push_back(AddReceive(vout, blockindex, vout_idx, tx));
2843 }
2844 }
2845 }
2846 }
2847
2848 bool search_mempool = true;
2849 if (!request.params[2].isNull()) {
2850 search_mempool = request.params[2].get_bool();
2851 }
2852
2853 if (search_mempool) {
2854 const CTxMemPool& mempool = EnsureMemPool(node);
2855 LOCK(::cs_main);
2856 LOCK(mempool.cs);
2857 const CCoinsViewCache& coins_view = &active_chainstate.CoinsTip();
2858
2859 for (const CTxMemPoolEntry& e : mempool.entryAll()) {
2860 const auto& tx = e.GetSharedTx();
2861
2862 for (size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2863 CScript scriptPubKey;
2864 CAmount value;
2865 const auto& txin = tx->vin.at(vin_idx);
2866 std::optional<Coin> coin = coins_view.GetCoin(txin.prevout);
2867
2868 // Check if the previous output is in the chain
2869 if (!coin) {
2870 // If not found in the chain, check the mempool. Likely, this is a
2871 // child transaction of another transaction in the mempool.
2872 CTransactionRef prev_tx = CHECK_NONFATAL(mempool.get(txin.prevout.hash));
2873
2874 if (txin.prevout.n >= prev_tx->vout.size()) {
2875 throw std::runtime_error("Invalid output index");
2876 }
2877 const CTxOut& out = prev_tx->vout[txin.prevout.n];
2878 scriptPubKey = out.scriptPubKey;
2879 value = out.nValue;
2880 } else {
2881 // Coin found in the chain
2882 const CTxOut& out = coin->out;
2883 scriptPubKey = out.scriptPubKey;
2884 value = out.nValue;
2885 }
2886
2887 if (scripts_to_watch.contains(scriptPubKey)) {
2888 UniValue event(UniValue::VOBJ);
2889 activity.push_back(AddSpend(
2890 scriptPubKey, value, tx, vin_idx, txin, nullptr));
2891 }
2892 }
2893
2894 for (size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2895 const auto& vout = tx->vout.at(vout_idx);
2896 if (scripts_to_watch.contains(vout.scriptPubKey)) {
2897 activity.push_back(AddReceive(vout, nullptr, vout_idx, tx));
2898 }
2899 }
2900 }
2901 }
2902
2903 ret.pushKV("activity", activity);
2904 return ret;
2905},
2906 };
2907}
2908
2910{
2911 return RPCHelpMan{
2912 "getblockfilter",
2913 "Retrieve a BIP 157 content filter for a particular block.\n",
2914 {
2915 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the block"},
2916 {"filtertype", RPCArg::Type::STR, RPCArg::Default{BlockFilterTypeName(BlockFilterType::BASIC)}, "The type name of the filter"},
2917 },
2918 RPCResult{
2919 RPCResult::Type::OBJ, "", "",
2920 {
2921 {RPCResult::Type::STR_HEX, "filter", "the hex-encoded filter data"},
2922 {RPCResult::Type::STR_HEX, "header", "the hex-encoded filter header"},
2923 }},
2925 HelpExampleCli("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2926 HelpExampleRpc("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2927 },
2928 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
2929{
2930 uint256 block_hash = ParseHashV(request.params[0], "blockhash");
2931 auto filtertype_name{self.Arg<std::string_view>("filtertype")};
2932
2933 BlockFilterType filtertype;
2934 if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2935 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
2936 }
2937
2938 BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
2939 if (!index) {
2940 throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
2941 }
2942
2943 const CBlockIndex* block_index;
2944 bool block_was_connected;
2945 {
2946 ChainstateManager& chainman = EnsureAnyChainman(request.context);
2947 LOCK(cs_main);
2948 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
2949 if (!block_index) {
2950 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2951 }
2952 block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
2953 }
2954
2955 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2956
2957 BlockFilter filter;
2958 uint256 filter_header;
2959 if (!index->LookupFilter(block_index, filter) ||
2960 !index->LookupFilterHeader(block_index, filter_header)) {
2961 int err_code;
2962 std::string errmsg = "Filter not found.";
2963
2964 if (!block_was_connected) {
2965 err_code = RPC_INVALID_ADDRESS_OR_KEY;
2966 errmsg += " Block was not connected to active chain.";
2967 } else if (!index_ready) {
2968 err_code = RPC_MISC_ERROR;
2969 errmsg += " Block filters are still in the process of being indexed.";
2970 } else {
2971 err_code = RPC_INTERNAL_ERROR;
2972 errmsg += " This error is unexpected and indicates index corruption.";
2973 }
2974
2975 throw JSONRPCError(err_code, errmsg);
2976 }
2977
2979 ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
2980 ret.pushKV("header", filter_header.GetHex());
2981 return ret;
2982},
2983 };
2984}
2985
2991{
2993public:
2994 NetworkDisable(CConnman& connman) : m_connman(connman) {
2997 throw JSONRPCError(RPC_MISC_ERROR, "Network activity could not be suspended.");
2998 }
2999 };
3002 };
3003};
3004
3010{
3013public:
3014 TemporaryRollback(ChainstateManager& chainman, const CBlockIndex& index) : m_chainman(chainman), m_invalidate_index(index) {
3016 };
3019 };
3020};
3021
3028{
3029 return RPCHelpMan{
3030 "dumptxoutset",
3031 "Write the serialized UTXO set to a file. This can be used in loadtxoutset afterwards if this snapshot height is supported in the chainparams as well.\n\n"
3032 "Unless the \"latest\" type is requested, the node will roll back to the requested height and network activity will be suspended during this process. "
3033 "Because of this it is discouraged to interact with the node in any other way during the execution of this call to avoid inconsistent results and race conditions, particularly RPCs that interact with blockstorage.\n\n"
3034 "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
3035 {
3036 {"path", RPCArg::Type::STR, RPCArg::Optional::NO, "Path to the output file. If relative, will be prefixed by datadir."},
3037 {"type", RPCArg::Type::STR, RPCArg::Default(""), "The type of snapshot to create. Can be \"latest\" to create a snapshot of the current UTXO set or \"rollback\" to temporarily roll back the state of the node to a historical block before creating the snapshot of a historical UTXO set. This parameter can be omitted if a separate \"rollback\" named parameter is specified indicating the height or hash of a specific historical block. If \"rollback\" is specified and separate \"rollback\" named parameter is not specified, this will roll back to the latest valid snapshot block that can currently be loaded with loadtxoutset."},
3039 {
3041 "Height or hash of the block to roll back to before creating the snapshot. Note: The further this number is from the tip, the longer this process will take. Consider setting a higher -rpcclienttimeout value in this case.",
3042 RPCArgOptions{.skip_type_check = true, .type_str = {"", "string or numeric"}}},
3043 },
3044 },
3045 },
3046 RPCResult{
3047 RPCResult::Type::OBJ, "", "",
3048 {
3049 {RPCResult::Type::NUM, "coins_written", "the number of coins written in the snapshot"},
3050 {RPCResult::Type::STR_HEX, "base_hash", "the hash of the base of the snapshot"},
3051 {RPCResult::Type::NUM, "base_height", "the height of the base of the snapshot"},
3052 {RPCResult::Type::STR, "path", "the absolute path that the snapshot was written to"},
3053 {RPCResult::Type::STR_HEX, "txoutset_hash", "the hash of the UTXO set contents"},
3054 {RPCResult::Type::NUM, "nchaintx", "the number of transactions in the chain up to and including the base block"},
3055 }
3056 },
3058 HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat latest") +
3059 HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat rollback") +
3060 HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset", R"(utxo.dat rollback=853456)")
3061 },
3062 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
3063{
3064 NodeContext& node = EnsureAnyNodeContext(request.context);
3065 const CBlockIndex* tip{WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Tip())};
3066 const CBlockIndex* target_index{nullptr};
3067 const auto snapshot_type{self.Arg<std::string_view>("type")};
3068 const UniValue options{request.params[2].isNull() ? UniValue::VOBJ : request.params[2]};
3069 if (options.exists("rollback")) {
3070 if (!snapshot_type.empty() && snapshot_type != "rollback") {
3071 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid snapshot type \"%s\" specified with rollback option", snapshot_type));
3072 }
3073 target_index = ParseHashOrHeight(options["rollback"], *node.chainman);
3074 } else if (snapshot_type == "rollback") {
3075 auto snapshot_heights = node.chainman->GetParams().GetAvailableSnapshotHeights();
3076 CHECK_NONFATAL(snapshot_heights.size() > 0);
3077 auto max_height = std::max_element(snapshot_heights.begin(), snapshot_heights.end());
3078 target_index = ParseHashOrHeight(*max_height, *node.chainman);
3079 } else if (snapshot_type == "latest") {
3080 target_index = tip;
3081 } else {
3082 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid snapshot type \"%s\" specified. Please specify \"rollback\" or \"latest\"", snapshot_type));
3083 }
3084
3085 const ArgsManager& args{EnsureAnyArgsman(request.context)};
3086 const fs::path path = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(self.Arg<std::string_view>("path")));
3087 // Write to a temporary path and then move into `path` on completion
3088 // to avoid confusion due to an interruption.
3089 const fs::path temppath = path + ".incomplete";
3090
3091 if (fs::exists(path)) {
3092 throw JSONRPCError(
3094 path.utf8string() + " already exists. If you are sure this is what you want, "
3095 "move it out of the way first");
3096 }
3097
3098 FILE* file{fsbridge::fopen(temppath, "wb")};
3099 AutoFile afile{file};
3100 if (afile.IsNull()) {
3101 throw JSONRPCError(
3103 "Couldn't open file " + temppath.utf8string() + " for writing.");
3104 }
3105
3106 CConnman& connman = EnsureConnman(node);
3107 const CBlockIndex* invalidate_index{nullptr};
3108 std::optional<NetworkDisable> disable_network;
3109 std::optional<TemporaryRollback> temporary_rollback;
3110
3111 // If the user wants to dump the txoutset of the current tip, we don't have
3112 // to roll back at all
3113 if (target_index != tip) {
3114 // If the node is running in pruned mode we ensure all necessary block
3115 // data is available before starting to roll back.
3116 if (node.chainman->m_blockman.IsPruneMode()) {
3117 LOCK(node.chainman->GetMutex());
3118 const CBlockIndex* current_tip{node.chainman->ActiveChain().Tip()};
3119 const CBlockIndex* first_block{node.chainman->m_blockman.GetFirstBlock(*current_tip, /*status_mask=*/BLOCK_HAVE_MASK)};
3120 if (first_block->nHeight > target_index->nHeight) {
3121 throw JSONRPCError(RPC_MISC_ERROR, "Could not roll back to requested height since necessary block data is already pruned.");
3122 }
3123 }
3124
3125 // Suspend network activity for the duration of the process when we are
3126 // rolling back the chain to get a utxo set from a past height. We do
3127 // this so we don't punish peers that send us that send us data that
3128 // seems wrong in this temporary state. For example a normal new block
3129 // would be classified as a block connecting an invalid block.
3130 // Skip if the network is already disabled because this
3131 // automatically re-enables the network activity at the end of the
3132 // process which may not be what the user wants.
3133 if (connman.GetNetworkActive()) {
3134 disable_network.emplace(connman);
3135 }
3136
3137 invalidate_index = WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Next(target_index));
3138 temporary_rollback.emplace(*node.chainman, *invalidate_index);
3139 }
3140
3141 Chainstate* chainstate;
3142 std::unique_ptr<CCoinsViewCursor> cursor;
3143 CCoinsStats stats;
3144 {
3145 // Lock the chainstate before calling PrepareUtxoSnapshot, to be able
3146 // to get a UTXO database cursor while the chain is pointing at the
3147 // target block. After that, release the lock while calling
3148 // WriteUTXOSnapshot. The cursor will remain valid and be used by
3149 // WriteUTXOSnapshot to write a consistent snapshot even if the
3150 // chainstate changes.
3151 LOCK(node.chainman->GetMutex());
3152 chainstate = &node.chainman->ActiveChainstate();
3153 // In case there is any issue with a block being read from disk we need
3154 // to stop here, otherwise the dump could still be created for the wrong
3155 // height.
3156 // The new tip could also not be the target block if we have a stale
3157 // sister block of invalidate_index. This block (or a descendant) would
3158 // be activated as the new tip and we would not get to new_tip_index.
3159 if (target_index != chainstate->m_chain.Tip()) {
3160 LogWarning("dumptxoutset failed to roll back to requested height, reverting to tip.\n");
3161 throw JSONRPCError(RPC_MISC_ERROR, "Could not roll back to requested height.");
3162 } else {
3163 std::tie(cursor, stats, tip) = PrepareUTXOSnapshot(*chainstate, node.rpc_interruption_point);
3164 }
3165 }
3166
3167 UniValue result = WriteUTXOSnapshot(*chainstate,
3168 cursor.get(),
3169 &stats,
3170 tip,
3171 std::move(afile),
3172 path,
3173 temppath,
3174 node.rpc_interruption_point);
3175 fs::rename(temppath, path);
3176
3177 result.pushKV("path", path.utf8string());
3178 return result;
3179},
3180 };
3181}
3182
3183std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex*>
3185 Chainstate& chainstate,
3186 const std::function<void()>& interruption_point)
3187{
3188 std::unique_ptr<CCoinsViewCursor> pcursor;
3189 std::optional<CCoinsStats> maybe_stats;
3190 const CBlockIndex* tip;
3191
3192 {
3193 // We need to lock cs_main to ensure that the coinsdb isn't written to
3194 // between (i) flushing coins cache to disk (coinsdb), (ii) getting stats
3195 // based upon the coinsdb, and (iii) constructing a cursor to the
3196 // coinsdb for use in WriteUTXOSnapshot.
3197 //
3198 // Cursors returned by leveldb iterate over snapshots, so the contents
3199 // of the pcursor will not be affected by simultaneous writes during
3200 // use below this block.
3201 //
3202 // See discussion here:
3203 // https://github.com/bitcoin/bitcoin/pull/15606#discussion_r274479369
3204 //
3206
3207 chainstate.ForceFlushStateToDisk();
3208
3209 maybe_stats = GetUTXOStats(&chainstate.CoinsDB(), chainstate.m_blockman, CoinStatsHashType::HASH_SERIALIZED, interruption_point);
3210 if (!maybe_stats) {
3211 throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
3212 }
3213
3214 pcursor = chainstate.CoinsDB().Cursor();
3215 tip = CHECK_NONFATAL(chainstate.m_blockman.LookupBlockIndex(maybe_stats->hashBlock));
3216 }
3217
3218 return {std::move(pcursor), *CHECK_NONFATAL(maybe_stats), tip};
3219}
3220
3222 Chainstate& chainstate,
3223 CCoinsViewCursor* pcursor,
3224 CCoinsStats* maybe_stats,
3225 const CBlockIndex* tip,
3226 AutoFile&& afile,
3227 const fs::path& path,
3228 const fs::path& temppath,
3229 const std::function<void()>& interruption_point)
3230{
3231 LOG_TIME_SECONDS(strprintf("writing UTXO snapshot at height %s (%s) to file %s (via %s)",
3232 tip->nHeight, tip->GetBlockHash().ToString(),
3233 fs::PathToString(path), fs::PathToString(temppath)));
3234
3235 SnapshotMetadata metadata{chainstate.m_chainman.GetParams().MessageStart(), tip->GetBlockHash(), maybe_stats->coins_count};
3236
3237 afile << metadata;
3238
3239 COutPoint key;
3240 Txid last_hash;
3241 Coin coin;
3242 unsigned int iter{0};
3243 size_t written_coins_count{0};
3244 std::vector<std::pair<uint32_t, Coin>> coins;
3245
3246 // To reduce space the serialization format of the snapshot avoids
3247 // duplication of tx hashes. The code takes advantage of the guarantee by
3248 // leveldb that keys are lexicographically sorted.
3249 // In the coins vector we collect all coins that belong to a certain tx hash
3250 // (key.hash) and when we have them all (key.hash != last_hash) we write
3251 // them to file using the below lambda function.
3252 // See also https://github.com/bitcoin/bitcoin/issues/25675
3253 auto write_coins_to_file = [&](AutoFile& afile, const Txid& last_hash, const std::vector<std::pair<uint32_t, Coin>>& coins, size_t& written_coins_count) {
3254 afile << last_hash;
3255 WriteCompactSize(afile, coins.size());
3256 for (const auto& [n, coin] : coins) {
3257 WriteCompactSize(afile, n);
3258 afile << coin;
3259 ++written_coins_count;
3260 }
3261 };
3262
3263 pcursor->GetKey(key);
3264 last_hash = key.hash;
3265 while (pcursor->Valid()) {
3266 if (iter % 5000 == 0) interruption_point();
3267 ++iter;
3268 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3269 if (key.hash != last_hash) {
3270 write_coins_to_file(afile, last_hash, coins, written_coins_count);
3271 last_hash = key.hash;
3272 coins.clear();
3273 }
3274 coins.emplace_back(key.n, coin);
3275 }
3276 pcursor->Next();
3277 }
3278
3279 if (!coins.empty()) {
3280 write_coins_to_file(afile, last_hash, coins, written_coins_count);
3281 }
3282
3283 CHECK_NONFATAL(written_coins_count == maybe_stats->coins_count);
3284
3285 if (afile.fclose() != 0) {
3286 throw std::ios_base::failure(
3287 strprintf("Error closing %s: %s", fs::PathToString(temppath), SysErrorString(errno)));
3288 }
3289
3290 UniValue result(UniValue::VOBJ);
3291 result.pushKV("coins_written", written_coins_count);
3292 result.pushKV("base_hash", tip->GetBlockHash().ToString());
3293 result.pushKV("base_height", tip->nHeight);
3294 result.pushKV("path", path.utf8string());
3295 result.pushKV("txoutset_hash", maybe_stats->hashSerialized.ToString());
3296 result.pushKV("nchaintx", tip->m_chain_tx_count);
3297 return result;
3298}
3299
3302 Chainstate& chainstate,
3303 AutoFile&& afile,
3304 const fs::path& path,
3305 const fs::path& tmppath)
3306{
3307 auto [cursor, stats, tip]{WITH_LOCK(::cs_main, return PrepareUTXOSnapshot(chainstate, node.rpc_interruption_point))};
3308 return WriteUTXOSnapshot(chainstate,
3309 cursor.get(),
3310 &stats,
3311 tip,
3312 std::move(afile),
3313 path,
3314 tmppath,
3315 node.rpc_interruption_point);
3316}
3317
3319{
3320 return RPCHelpMan{
3321 "loadtxoutset",
3322 "Load the serialized UTXO set from a file.\n"
3323 "Once this snapshot is loaded, its contents will be "
3324 "deserialized into a second chainstate data structure, which is then used to sync to "
3325 "the network's tip. "
3326 "Meanwhile, the original chainstate will complete the initial block download process in "
3327 "the background, eventually validating up to the block that the snapshot is based upon.\n\n"
3328
3329 "The result is a usable bitcoind instance that is current with the network tip in a "
3330 "matter of minutes rather than hours. UTXO snapshot are typically obtained from "
3331 "third-party sources (HTTP, torrent, etc.) which is reasonable since their "
3332 "contents are always checked by hash.\n\n"
3333
3334 "You can find more information on this process in the `assumeutxo` design "
3335 "document (<https://github.com/bitcoin/bitcoin/blob/master/doc/design/assumeutxo.md>).",
3336 {
3337 {"path",
3340 "path to the snapshot file. If relative, will be prefixed by datadir."},
3341 },
3342 RPCResult{
3343 RPCResult::Type::OBJ, "", "",
3344 {
3345 {RPCResult::Type::NUM, "coins_loaded", "the number of coins loaded from the snapshot"},
3346 {RPCResult::Type::STR_HEX, "tip_hash", "the hash of the base of the snapshot"},
3347 {RPCResult::Type::NUM, "base_height", "the height of the base of the snapshot"},
3348 {RPCResult::Type::STR, "path", "the absolute path that the snapshot was loaded from"},
3349 }
3350 },
3352 HelpExampleCli("-rpcclienttimeout=0 loadtxoutset", "utxo.dat")
3353 },
3354 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
3355{
3356 NodeContext& node = EnsureAnyNodeContext(request.context);
3358 const fs::path path{AbsPathForConfigVal(EnsureArgsman(node), fs::u8path(self.Arg<std::string_view>("path")))};
3359
3360 FILE* file{fsbridge::fopen(path, "rb")};
3361 AutoFile afile{file};
3362 if (afile.IsNull()) {
3363 throw JSONRPCError(
3365 "Couldn't open file " + path.utf8string() + " for reading.");
3366 }
3367
3368 SnapshotMetadata metadata{chainman.GetParams().MessageStart()};
3369 try {
3370 afile >> metadata;
3371 } catch (const std::ios_base::failure& e) {
3372 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Unable to parse metadata: %s", e.what()));
3373 }
3374
3375 auto activation_result{chainman.ActivateSnapshot(afile, metadata, false)};
3376 if (!activation_result) {
3377 throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Unable to load UTXO snapshot: %s. (%s)", util::ErrorString(activation_result).original, path.utf8string()));
3378 }
3379
3380 // Because we can't provide historical blocks during tip or background sync.
3381 // Update local services to reflect we are a limited peer until we are fully sync.
3382 node.connman->RemoveLocalServices(NODE_NETWORK);
3383 // Setting the limited state is usually redundant because the node can always
3384 // provide the last 288 blocks, but it doesn't hurt to set it.
3385 node.connman->AddLocalServices(NODE_NETWORK_LIMITED);
3386
3387 CBlockIndex& snapshot_index{*CHECK_NONFATAL(*activation_result)};
3388
3389 UniValue result(UniValue::VOBJ);
3390 result.pushKV("coins_loaded", metadata.m_coins_count);
3391 result.pushKV("tip_hash", snapshot_index.GetBlockHash().ToString());
3392 result.pushKV("base_height", snapshot_index.nHeight);
3393 result.pushKV("path", fs::PathToString(path));
3394 return result;
3395},
3396 };
3397}
3398
3399const std::vector<RPCResult> RPCHelpForChainstate{
3400 {RPCResult::Type::NUM, "blocks", "number of blocks in this chainstate"},
3401 {RPCResult::Type::STR_HEX, "bestblockhash", "blockhash of the tip"},
3402 {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
3403 {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
3404 {RPCResult::Type::NUM, "difficulty", "difficulty of the tip"},
3405 {RPCResult::Type::NUM, "verificationprogress", "progress towards the network tip"},
3406 {RPCResult::Type::STR_HEX, "snapshot_blockhash", /*optional=*/true, "the base block of the snapshot this chainstate is based on, if any"},
3407 {RPCResult::Type::NUM, "coins_db_cache_bytes", "size of the coinsdb cache"},
3408 {RPCResult::Type::NUM, "coins_tip_cache_bytes", "size of the coinstip cache"},
3409 {RPCResult::Type::BOOL, "validated", "whether the chainstate is fully validated. True if all blocks in the chainstate were validated, false if the chain is based on a snapshot and the snapshot has not yet been validated."},
3410};
3411
3413{
3414return RPCHelpMan{
3415 "getchainstates",
3416 "Return information about chainstates.\n",
3417 {},
3418 RPCResult{
3419 RPCResult::Type::OBJ, "", "", {
3420 {RPCResult::Type::NUM, "headers", "the number of headers seen so far"},
3421 {RPCResult::Type::ARR, "chainstates", "list of the chainstates ordered by work, with the most-work (active) chainstate last", {{RPCResult::Type::OBJ, "", "", RPCHelpForChainstate},}},
3422 }
3423 },
3425 HelpExampleCli("getchainstates", "")
3426 + HelpExampleRpc("getchainstates", "")
3427 },
3428 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
3429{
3430 LOCK(cs_main);
3432
3433 ChainstateManager& chainman = EnsureAnyChainman(request.context);
3434
3435 auto make_chain_data = [&](const Chainstate& cs, bool validated) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
3438 if (!cs.m_chain.Tip()) {
3439 return data;
3440 }
3441 const CChain& chain = cs.m_chain;
3442 const CBlockIndex* tip = chain.Tip();
3443
3444 data.pushKV("blocks", (int)chain.Height());
3445 data.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
3446 data.pushKV("bits", strprintf("%08x", tip->nBits));
3447 data.pushKV("target", GetTarget(*tip, chainman.GetConsensus().powLimit).GetHex());
3448 data.pushKV("difficulty", GetDifficulty(*tip));
3449 data.pushKV("verificationprogress", chainman.GuessVerificationProgress(tip));
3450 data.pushKV("coins_db_cache_bytes", cs.m_coinsdb_cache_size_bytes);
3451 data.pushKV("coins_tip_cache_bytes", cs.m_coinstip_cache_size_bytes);
3452 if (cs.m_from_snapshot_blockhash) {
3453 data.pushKV("snapshot_blockhash", cs.m_from_snapshot_blockhash->ToString());
3454 }
3455 data.pushKV("validated", validated);
3456 return data;
3457 };
3458
3459 obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
3460
3461 const auto& chainstates = chainman.GetAll();
3462 UniValue obj_chainstates{UniValue::VARR};
3463 for (Chainstate* cs : chainstates) {
3464 obj_chainstates.push_back(make_chain_data(*cs, !cs->m_from_snapshot_blockhash || chainstates.size() == 1));
3465 }
3466 obj.pushKV("chainstates", std::move(obj_chainstates));
3467 return obj;
3468}
3469 };
3470}
3471
3472
3474{
3475 static const CRPCCommand commands[]{
3476 {"blockchain", &getblockchaininfo},
3477 {"blockchain", &getchaintxstats},
3478 {"blockchain", &getblockstats},
3479 {"blockchain", &getbestblockhash},
3480 {"blockchain", &getblockcount},
3481 {"blockchain", &getblock},
3482 {"blockchain", &getblockfrompeer},
3483 {"blockchain", &getblockhash},
3484 {"blockchain", &getblockheader},
3485 {"blockchain", &getchaintips},
3486 {"blockchain", &getdifficulty},
3487 {"blockchain", &getdeploymentinfo},
3488 {"blockchain", &gettxout},
3489 {"blockchain", &gettxoutsetinfo},
3490 {"blockchain", &pruneblockchain},
3491 {"blockchain", &verifychain},
3492 {"blockchain", &preciousblock},
3493 {"blockchain", &scantxoutset},
3494 {"blockchain", &scanblocks},
3495 {"blockchain", &getdescriptoractivity},
3496 {"blockchain", &getblockfilter},
3497 {"blockchain", &dumptxoutset},
3498 {"blockchain", &loadtxoutset},
3499 {"blockchain", &getchainstates},
3500 {"hidden", &invalidateblock},
3501 {"hidden", &reconsiderblock},
3502 {"blockchain", &waitfornewblock},
3503 {"blockchain", &waitforblock},
3504 {"blockchain", &waitforblockheight},
3506 };
3507 for (const auto& c : commands) {
3508 t.appendCommand(c.name, &c);
3509 }
3510}
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
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: config.cpp:226
static void pool cs
int ret
ArgsManager & args
Definition: bitcoind.cpp:282
static RPCHelpMan getblock()
Definition: blockchain.cpp:743
static RPCHelpMan getdifficulty()
Definition: blockchain.cpp:471
static const auto scan_result_abort
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
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:116
CoinStatsHashType ParseHashType(std::string_view hash_type_input)
Definition: blockchain.cpp:942
const RPCResult getblock_vin
Definition: blockchain.cpp:719
static RPCHelpMan syncwithvalidationinterfacequeue()
Definition: blockchain.cpp:451
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex &blockindex)
Definition: blockchain.cpp:700
static std::vector< std::byte > GetRawBlockChecked(BlockManager &blockman, const CBlockIndex &blockindex)
Definition: blockchain.cpp:681
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 getchaintips()
static RPCHelpMan loadtxoutset()
static RPCHelpMan gettxoutsetinfo()
Definition: blockchain.cpp:985
static RPCHelpMan getchainstates()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point)
static std::atomic< int > g_scanfilter_progress_height
static RPCHelpMan getblockstats()
static const auto output_descriptor_obj
void CheckBlockDataAvailability(BlockManager &blockman, const CBlockIndex &blockindex, bool check_for_undo)
Definition: blockchain.cpp:649
static std::atomic< bool > g_scanfilter_should_abort_scan
static std::atomic< int > g_scanfilter_progress
RAII object to prevent concurrency issue when scanning blockfilters.
static void SoftForkDescPushBack(const CBlockIndex *blockindex, UniValue &softforks, const ChainstateManager &chainman, Consensus::BuriedDeployment dep)
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
static RPCHelpMan getdescriptoractivity()
double GetDifficulty(const CBlockIndex &blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:96
static const auto scan_objects_arg_desc
static RPCHelpMan scantxoutset()
static bool CheckBlockFilterMatches(BlockManager &blockman, const CBlockIndex &blockindex, const GCSFilter::ElementSet &needles)
void InvalidateBlock(ChainstateManager &chainman, const uint256 block_hash)
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 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:664
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
Return height of highest block that has been pruned, or std::nullopt if no blocks have been pruned.
Definition: blockchain.cpp:858
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity, const uint256 pow_limit)
Block description to JSON.
Definition: blockchain.cpp:184
RPCHelpMan getdeploymentinfo()
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
Definition: blockchain.cpp:247
RPCHelpMan getblockchaininfo()
void ReconsiderBlock(ChainstateManager &chainman, uint256 block_hash)
static RPCHelpMan getchaintxstats()
static RPCHelpMan waitforblock()
Definition: blockchain.cpp:327
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex, const uint256 pow_limit)
Block header to JSON.
Definition: blockchain.cpp:154
static RPCHelpMan getblockfrompeer()
Definition: blockchain.cpp:492
static const auto scan_result_status_some
static RPCHelpMan getblockhash()
Definition: blockchain.cpp:547
void RegisterBlockchainRPCCommands(CRPCTable &t)
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector< std::pair< CAmount, int64_t > > &scores, int64_t total_weight)
Used by getblockstats to get feerates at different percentiles by weight
static std::optional< kernel::CCoinsStats > GetUTXOStats(CCoinsView *view, node::BlockManager &blockman, kernel::CoinStatsHashType hash_type, const std::function< void()> &interruption_point={}, const CBlockIndex *pindex=nullptr, bool index_requested=true)
Calculate statistics about the unspent transaction output set.
Definition: blockchain.cpp:960
static RPCHelpMan gettxout()
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
const std::vector< RPCResult > RPCHelpForChainstate
static const auto scan_action_arg_desc
static RPCHelpMan waitforblockheight()
Definition: blockchain.cpp:388
static const CBlockIndex * ParseHashOrHeight(const UniValue &param, ChainstateManager &chainman)
Definition: blockchain.cpp:126
static RPCHelpMan pruneblockchain()
Definition: blockchain.cpp:883
static RPCHelpMan getblockheader()
Definition: blockchain.cpp:577
static RPCHelpMan scanblocks()
static std::atomic< bool > g_scanfilter_in_progress
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
Definition: blockchain.cpp:225
static RPCHelpMan waitfornewblock()
Definition: blockchain.cpp:268
static const auto scan_result_status_none
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES
Definition: blockchain.h:28
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
bool BlockFilterTypeByName(std::string_view name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterType
Definition: blockfilter.h:94
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:118
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:100
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:125
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:124
@ BLOCK_FAILED_MASK
Definition: chain.h:130
@ BLOCK_HAVE_MASK
Definition: chain.h:126
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:37
#define LIST_CHAIN_NAMES
List of possible chain / network names
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:111
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:235
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:371
int fclose()
Definition: streams.h:405
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:116
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
Definition: blockfilter.h:139
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
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.
BlockFiltersScanReserver()=default
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:144
uint256 hashMerkleRoot
Definition: chain.h:191
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:300
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:150
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:179
CBlockHeader GetBlockHeader() const
Definition: chain.h:235
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:168
uint32_t nTime
Definition: chain.h:192
uint32_t nNonce
Definition: chain.h:194
uint256 GetBlockHash() const
Definition: chain.h:248
int64_t GetBlockTime() const
Definition: chain.h:271
int64_t GetMedianTimePast() const
Definition: chain.h:283
uint32_t nBits
Definition: chain.h:193
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:173
int32_t nVersion
block header
Definition: chain.h:190
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:116
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:156
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:213
Undo information for a CBlock.
Definition: undo.h:63
std::vector< CTxUndo > vtxundo
Definition: undo.h:65
An in-memory indexed chain of blocks.
Definition: chain.h:422
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:438
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:432
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:67
int Height() const
Return the maximal height in the chain.
Definition: chain.h:467
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:56
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:452
std::string GetChainTypeString() const
Return the chain type string.
Definition: chainparams.h:110
const MessageStartChars & MessageStart() const
Definition: chainparams.h:91
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:90
uint64_t PruneAfterHeight() const
Definition: chainparams.h:102
ChainType GetChainType() const
Return the chain type.
Definition: chainparams.h:112
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:361
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:176
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:66
Cursor for iterating over CoinsView state.
Definition: coins.h:235
virtual void Next()=0
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: txdb.cpp:185
Abstract view on the open txout dataset.
Definition: coins.h:308
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:17
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:919
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:1009
Definition: net.h:1060
bool GetNetworkActive() const
Definition: net.h:1149
void SetNetworkActive(bool active)
Definition: net.cpp:3214
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
uint32_t n
Definition: transaction.h:32
Txid hash
Definition: transaction.h:31
RPC command dispatcher.
Definition: server.h:87
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
An input of a transaction.
Definition: transaction.h:67
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:66
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:281
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:367
CTransactionRef get(const Txid &hash) const
Definition: txmempool.cpp:879
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:846
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:419
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
CAmount nValue
Definition: transaction.h:152
Undo information for a CTransaction.
Definition: undo.h:53
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:432
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, 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:532
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:614
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:640
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:648
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:574
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:569
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:899
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1140
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:1125
double GuessVerificationProgress(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
kernel::Notifications & GetNotifications() const
Definition: validation.h:1012
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:1032
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1128
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1149
const CChainParams & GetParams() const
Definition: validation.h:1007
const Consensus::Params & GetConsensus() const
Definition: validation.h:1008
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:1126
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1095
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1038
A UTXO entry.
Definition: coins.h:33
bool IsCoinBase() const
Definition: coins.h:57
CTxOut out
unspent transaction output
Definition: coins.h:36
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:42
CoinsViewScanReserver()=default
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:130
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:33
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(NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:444
RAII class that temporarily rolls back the local chain in it's constructor and rolls it forward again...
TemporaryRollback(ChainstateManager &chainman, const CBlockIndex &index)
const CBlockIndex & m_invalidate_index
ChainstateManager & m_chainman
void push_back(UniValue val)
Definition: univalue.cpp:104
const std::string & get_str() const
@ VNULL
Definition: univalue.h:24
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
bool isNull() const
Definition: univalue.h:81
size_t size() const
Definition: univalue.h:71
const std::vector< UniValue > & getValues() const
Int getInt() const
Definition: univalue.h:140
const UniValue & get_array() const
void reserve(size_t new_cap)
Definition: univalue.cpp:243
bool isNum() const
Definition: univalue.h:86
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
void push_backV(const std::vector< UniValue > &vec)
Definition: univalue.cpp:111
bool IsValid() const
Definition: validation.h:105
std::string ToString() const
Definition: validation.h:111
BIP9Info Info(const CBlockIndex &block_index, const Consensus::Params &params, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
256-bit unsigned big integer.
std::string ToString() const
Definition: uint256.cpp:21
std::string GetHex() const
Definition: uint256.cpp:11
uint64_t GetLow64() const
std::string GetHex() const
Hex encoding of the number (with the most significant digits first).
Interface giving clients (RPC, Stratum v2 Template Provider in the future) ability to create block te...
Definition: mining.h:80
virtual std::optional< BlockRef > waitTipChanged(uint256 current_tip, MillisecondsDouble timeout=MillisecondsDouble::max())=0
Waits for the connected tip to change.
virtual std::optional< BlockRef > getTip()=0
Returns the hash and height for the tip of this chain.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:139
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
Definition: blockstorage.h:352
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool ReadRawBlock(std::vector< std::byte > &block, const FlatFilePos &pos) const
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:349
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:34
constexpr const std::byte * begin() const
std::string GetHex() const
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:196
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:136
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:132
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
Definition: consensus.h:13
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
Definition: core_write.cpp:171
TxVerbosity
Verbose level for block's transaction.
Definition: core_io.h:28
@ 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 ScriptToUniv(const CScript &script, UniValue &out, bool include_hex=true, bool include_address=false, const SigningProvider *provider=nullptr)
Definition: core_write.cpp:150
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:26
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
std::string DeploymentName(Consensus::BuriedDeployment dep)
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
bool DeploymentEnabled(const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
const std::string CURRENCY_UNIT
Definition: feerate.h:18
static path u8path(std::string_view utf8_str)
Definition: fs.h:81
static bool exists(const path &p)
Definition: fs.h:95
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:157
#define T(expected, seed, data)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:31
std::vector< std::string > GetScriptFlagNames(script_verify_flags flags)
#define LogWarning(...)
Definition: logging.h:357
#define LogDebug(category,...)
Definition: logging.h:381
unsigned int nHeight
@ RPC
Definition: logging.h:73
@ NONE
Definition: logging.h:65
DeploymentPos
Definition: params.h:34
@ DEPLOYMENT_TAPROOT
Definition: params.h:36
@ DEPLOYMENT_TESTDUMMY
Definition: params.h:35
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
Definition: params.h:24
@ DEPLOYMENT_DERSIG
Definition: params.h:28
@ DEPLOYMENT_CSV
Definition: params.h:29
@ DEPLOYMENT_SEGWIT
Definition: params.h:30
@ DEPLOYMENT_HEIGHTINCB
Definition: params.h:26
@ DEPLOYMENT_CLTV
Definition: params.h:27
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:36
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:116
CoinStatsHashType
Definition: coinstats.h:27
Definition: messages.h:21
UniValue GetWarningsForRpc(const Warnings &warnings, bool use_deprecated)
RPC helper function that wraps warnings.GetMessages().
Definition: warnings.cpp:54
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Definition: string.h:225
int64_t NodeId
Definition: net.h:99
static constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:196
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ NODE_NETWORK_LIMITED
Definition: protocol.h:327
@ NODE_NETWORK
Definition: protocol.h:315
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:40
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:44
@ RPC_INTERNAL_ERROR
Definition: protocol.h:36
@ RPC_DATABASE_ERROR
Database error.
Definition: protocol.h:45
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:46
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider, const bool expand_priv)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:1329
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:186
uint256 GetTarget(const CBlockIndex &blockindex, const uint256 pow_limit)
Definition: util.cpp:1406
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:204
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:46
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:49
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
Definition: util.cpp:86
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:120
std::vector< RPCResult > ScriptPubKeyDoc()
Definition: util.cpp:1395
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1094
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1088
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:339
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:82
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:25
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:34
PeerManager & EnsurePeerman(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:74
ArgsManager & EnsureArgsman(const NodeContext &node)
Definition: server_util.cpp:61
interfaces::Mining & EnsureMining(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
ArgsManager & EnsureAnyArgsman(const std::any &context)
Definition: server_util.cpp:69
unsigned char * UCharCast(char *c)
Definition: span.h:95
Detailed status of an enabled BIP9 deployment.
Definition: versionbits.h:50
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
std::vector< uint8_t > signet_challenge
Definition: params.h:137
uint256 powLimit
Proof of work parameters.
Definition: params.h:112
int DeploymentHeight(BuriedDeployment dep) const
Definition: params.h:139
std::array< BIP9Deployment, MAX_VERSION_BITS_DEPLOYMENTS > vDeployments
Definition: params.h:110
int64_t nPowTargetSpacing
Definition: params.h:120
Definition: util.h:186
@ 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:220
@ 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:222
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:171
bool skip_type_check
Definition: util.h:170
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
Hash/height pair to help track and identify blocks.
Definition: types.h:13
arith_uint256 total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
Definition: coinstats.h:66
std::optional< CAmount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
Definition: coinstats.h:42
uint64_t nDiskSize
Definition: coinstats.h:40
CAmount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
Definition: coinstats.h:59
uint64_t coins_count
The number of coins contained.
Definition: coinstats.h:45
uint64_t nTransactions
Definition: coinstats.h:36
arith_uint256 total_coinbase_amount
Total cumulative amount of coinbase outputs up to and including this block.
Definition: coinstats.h:70
uint64_t nTransactionOutputs
Definition: coinstats.h:37
uint64_t nBogoSize
Definition: coinstats.h:38
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
Definition: coinstats.h:48
CAmount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
Definition: coinstats.h:57
CAmount total_unspendables_genesis_block
The unspendable coinbase amount from the genesis block.
Definition: coinstats.h:55
uint256 hashSerialized
Definition: coinstats.h:39
arith_uint256 total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
Definition: coinstats.h:68
CAmount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block.
Definition: coinstats.h:61
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
#define AssertLockNotHeld(cs)
Definition: sync.h:142
#define LOCK(cs)
Definition: sync.h:259
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:290
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:19
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
#define LOG_TIME_SECONDS(end_msg)
Definition: timer.h:107
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
Definition: txmempool.h:50
const UniValue NullUniValue
Definition: univalue.cpp:16
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:88
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:101
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
AssertLockHeld(pool.cs)
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:74
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:72
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:73