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