LCOV - code coverage report
Current view: top level - src/rpc - blockchain.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.3 % 1694 1598
Test Date: 2024-11-04 05:10:19 Functions: 97.7 % 130 127
Branches: 51.5 % 6643 3422

             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                 :       24449 : double GetDifficulty(const CBlockIndex& blockindex)
      90                 :             : {
      91                 :       24449 :     int nShift = (blockindex.nBits >> 24) & 0xff;
      92                 :       24449 :     double dDiff =
      93                 :       24449 :         (double)0x0000ffff / (double)(blockindex.nBits & 0x00ffffff);
      94                 :             : 
      95         [ +  + ]:       24461 :     while (nShift < 29)
      96                 :             :     {
      97                 :          12 :         dDiff *= 256.0;
      98                 :          12 :         nShift++;
      99                 :             :     }
     100         [ +  + ]:       97778 :     while (nShift > 29)
     101                 :             :     {
     102                 :       73329 :         dDiff /= 256.0;
     103                 :       73329 :         nShift--;
     104                 :             :     }
     105                 :             : 
     106                 :       24449 :     return dDiff;
     107                 :             : }
     108                 :             : 
     109                 :        3804 : static int ComputeNextBlockAndDepth(const CBlockIndex& tip, const CBlockIndex& blockindex, const CBlockIndex*& next)
     110                 :             : {
     111                 :        3804 :     next = tip.GetAncestor(blockindex.nHeight + 1);
     112   [ +  +  +  + ]:        3804 :     if (next && next->pprev == &blockindex) {
     113                 :        1540 :         return tip.nHeight - blockindex.nHeight + 1;
     114                 :             :     }
     115                 :        2264 :     next = nullptr;
     116         [ +  + ]:        2264 :     return &blockindex == &tip ? 1 : -1;
     117                 :             : }
     118                 :             : 
     119                 :         140 : static const CBlockIndex* ParseHashOrHeight(const UniValue& param, ChainstateManager& chainman)
     120                 :             : {
     121                 :         140 :     LOCK(::cs_main);
     122         [ +  - ]:         140 :     CChain& active_chain = chainman.ActiveChain();
     123                 :             : 
     124         [ +  + ]:         140 :     if (param.isNum()) {
     125         [ +  - ]:         124 :         const int height{param.getInt<int>()};
     126         [ +  + ]:         124 :         if (height < 0) {
     127   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
     128                 :             :         }
     129         [ +  + ]:         123 :         const int current_tip{active_chain.Height()};
     130         [ +  + ]:         123 :         if (height > current_tip) {
     131   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
     132                 :             :         }
     133                 :             : 
     134   [ +  -  +  - ]:         258 :         return active_chain[height];
     135                 :             :     } else {
     136         [ +  - ]:          16 :         const uint256 hash{ParseHashV(param, "hash_or_height")};
     137         [ +  - ]:          16 :         const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
     138                 :             : 
     139         [ +  + ]:          16 :         if (!pindex) {
     140   [ +  -  +  - ]:           4 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
     141                 :             :         }
     142                 :             : 
     143                 :             :         return pindex;
     144                 :             :     }
     145                 :         136 : }
     146                 :             : 
     147                 :        3804 : UniValue blockheaderToJSON(const CBlockIndex& tip, const CBlockIndex& blockindex)
     148                 :             : {
     149                 :             :     // Serialize passed information without accessing chain state of the active chain!
     150                 :        3804 :     AssertLockNotHeld(cs_main); // For performance reasons
     151                 :             : 
     152                 :        3804 :     UniValue result(UniValue::VOBJ);
     153   [ +  -  +  -  :        7608 :     result.pushKV("hash", blockindex.GetBlockHash().GetHex());
             +  -  +  - ]
     154                 :        3804 :     const CBlockIndex* pnext;
     155         [ +  - ]:        3804 :     int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
     156   [ +  -  +  -  :        7608 :     result.pushKV("confirmations", confirmations);
                   +  - ]
     157   [ +  -  +  -  :        7608 :     result.pushKV("height", blockindex.nHeight);
                   +  - ]
     158   [ +  -  +  -  :        7608 :     result.pushKV("version", blockindex.nVersion);
                   +  - ]
     159   [ +  -  +  -  :        7608 :     result.pushKV("versionHex", strprintf("%08x", blockindex.nVersion));
             +  -  +  - ]
     160   [ +  -  +  -  :        7608 :     result.pushKV("merkleroot", blockindex.hashMerkleRoot.GetHex());
             +  -  +  - ]
     161   [ +  -  +  - ]:       11412 :     result.pushKV("time", blockindex.nTime);
     162   [ +  -  +  -  :        7608 :     result.pushKV("mediantime", blockindex.GetMedianTimePast());
                   +  - ]
     163   [ +  -  +  -  :        7608 :     result.pushKV("nonce", blockindex.nNonce);
                   +  - ]
     164   [ +  -  +  -  :        7608 :     result.pushKV("bits", strprintf("%08x", blockindex.nBits));
             +  -  +  - ]
     165   [ +  -  +  -  :        7608 :     result.pushKV("difficulty", GetDifficulty(blockindex));
             +  -  +  - ]
     166   [ +  -  +  -  :        7608 :     result.pushKV("chainwork", blockindex.nChainWork.GetHex());
             +  -  +  - ]
     167   [ +  -  +  -  :        7608 :     result.pushKV("nTx", blockindex.nTx);
                   +  - ]
     168                 :             : 
     169         [ +  + ]:        3804 :     if (blockindex.pprev)
     170   [ +  -  +  -  :        7564 :         result.pushKV("previousblockhash", blockindex.pprev->GetBlockHash().GetHex());
             +  -  +  - ]
     171         [ +  + ]:        3804 :     if (pnext)
     172   [ +  -  +  -  :        3080 :         result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
             +  -  +  - ]
     173                 :        3804 :     return result;
     174                 :           0 : }
     175                 :             : 
     176                 :        1307 : UniValue blockToJSON(BlockManager& blockman, const CBlock& block, const CBlockIndex& tip, const CBlockIndex& blockindex, TxVerbosity verbosity)
     177                 :             : {
     178                 :        1307 :     UniValue result = blockheaderToJSON(tip, blockindex);
     179                 :             : 
     180   [ +  -  +  -  :        2614 :     result.pushKV("strippedsize", (int)::GetSerializeSize(TX_NO_WITNESS(block)));
                   +  - ]
     181   [ +  -  +  -  :        2614 :     result.pushKV("size", (int)::GetSerializeSize(TX_WITH_WITNESS(block)));
                   +  - ]
     182   [ +  -  +  -  :        1307 :     result.pushKV("weight", (int)::GetBlockWeight(block));
                   +  - ]
     183                 :        1307 :     UniValue txs(UniValue::VARR);
     184                 :             : 
     185      [ +  +  - ]:        1307 :     switch (verbosity) {
     186                 :        1176 :         case TxVerbosity::SHOW_TXID:
     187         [ +  + ]:        5364 :             for (const CTransactionRef& tx : block.vtx) {
     188   [ +  -  +  -  :        4188 :                 txs.push_back(tx->GetHash().GetHex());
                   +  - ]
     189                 :             :             }
     190                 :             :             break;
     191                 :             : 
     192                 :         131 :         case TxVerbosity::SHOW_DETAILS:
     193                 :         131 :         case TxVerbosity::SHOW_DETAILS_AND_PREVOUT:
     194                 :         131 :             CBlockUndo blockUndo;
     195   [ +  -  +  -  :         393 :             const bool is_not_pruned{WITH_LOCK(::cs_main, return !blockman.IsBlockPruned(blockindex))};
                   +  - ]
     196   [ +  -  +  -  :         380 :             bool have_undo{is_not_pruned && WITH_LOCK(::cs_main, return blockindex.nStatus & BLOCK_HAVE_UNDO)};
             +  +  +  - ]
     197   [ +  -  +  + ]:         122 :             if (have_undo && !blockman.UndoReadFromDisk(blockUndo, blockindex)) {
     198   [ +  -  +  - ]:           8 :                 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         [ +  + ]:         286 :             for (size_t i = 0; i < block.vtx.size(); ++i) {
     201         [ +  - ]:         159 :                 const CTransactionRef& tx = block.vtx.at(i);
     202                 :             :                 // coinbase transaction (i.e. i == 0) doesn't have undo data
     203   [ +  +  +  - ]:         159 :                 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.vtxundo.at(i - 1) : nullptr;
     204                 :         159 :                 UniValue objTx(UniValue::VOBJ);
     205         [ +  - ]:         159 :                 TxToUniv(*tx, /*block_hash=*/uint256(), /*entry=*/objTx, /*include_hex=*/true, txundo, verbosity);
     206         [ +  - ]:         159 :                 txs.push_back(std::move(objTx));
     207                 :         159 :             }
     208                 :         127 :             break;
     209                 :             :     }
     210                 :             : 
     211   [ +  -  +  - ]:        2606 :     result.pushKV("tx", std::move(txs));
     212                 :             : 
     213                 :        1303 :     return result;
     214                 :        1311 : }
     215                 :             : 
     216                 :        5606 : static RPCHelpMan getblockcount()
     217                 :             : {
     218                 :        5606 :     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   [ +  -  +  -  :       11212 :                     RPCResult::Type::NUM, "", "The current block count"},
                   +  - ]
     224                 :        5606 :                 RPCExamples{
     225   [ +  -  +  -  :       11212 :                     HelpExampleCli("getblockcount", "")
                   +  - ]
     226   [ +  -  +  -  :       22424 :             + HelpExampleRpc("getblockcount", "")
             +  -  +  - ]
     227         [ +  - ]:        5606 :                 },
     228                 :        3544 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     229                 :             : {
     230                 :        3544 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     231                 :        3544 :     LOCK(cs_main);
     232   [ +  -  +  - ]:        3544 :     return chainman.ActiveChain().Height();
     233                 :        3544 : },
     234   [ +  -  +  -  :       33636 :     };
             +  -  +  - ]
     235                 :             : }
     236                 :             : 
     237                 :       13728 : static RPCHelpMan getbestblockhash()
     238                 :             : {
     239                 :       13728 :     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   [ +  -  +  -  :       27456 :                     RPCResult::Type::STR_HEX, "", "the block hash, hex-encoded"},
                   +  - ]
     244                 :       13728 :                 RPCExamples{
     245   [ +  -  +  -  :       27456 :                     HelpExampleCli("getbestblockhash", "")
                   +  - ]
     246   [ +  -  +  -  :       54912 :             + HelpExampleRpc("getbestblockhash", "")
             +  -  +  - ]
     247         [ +  - ]:       13728 :                 },
     248                 :       11666 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     249                 :             : {
     250                 :       11666 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     251                 :       11666 :     LOCK(cs_main);
     252   [ +  -  +  -  :       34998 :     return chainman.ActiveChain().Tip()->GetBlockHash().GetHex();
          +  -  +  -  +  
                      - ]
     253                 :       11666 : },
     254   [ +  -  +  -  :       82368 :     };
             +  -  +  - ]
     255                 :             : }
     256                 :             : 
     257                 :        2058 : static RPCHelpMan waitfornewblock()
     258                 :             : {
     259                 :        2058 :     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         [ +  - ]:        4116 :                     {"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   [ +  -  +  -  :        8232 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     272                 :        2058 :                 RPCExamples{
     273   [ +  -  +  -  :        4116 :                     HelpExampleCli("waitfornewblock", "1000")
                   +  - ]
     274   [ +  -  +  -  :        8232 :             + HelpExampleRpc("waitfornewblock", "1000")
             +  -  +  - ]
     275         [ +  - ]:        2058 :                 },
     276                 :           5 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     277                 :             : {
     278                 :           5 :     int timeout = 0;
     279         [ +  + ]:           5 :     if (!request.params[0].isNull())
     280                 :           4 :         timeout = request.params[0].getInt<int>();
     281   [ -  +  -  -  :           4 :     if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
                   -  - ]
     282                 :             : 
     283                 :           5 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     284                 :           5 :     Mining& miner = EnsureMining(node);
     285                 :             : 
     286         [ +  - ]:           5 :     auto block{CHECK_NONFATAL(miner.getTip()).value()};
     287         [ +  - ]:           5 :     if (IsRPCRunning()) {
     288         [ +  + ]:           5 :         block = timeout ? miner.waitTipChanged(block.hash, std::chrono::milliseconds(timeout)) : miner.waitTipChanged(block.hash);
     289                 :             :     }
     290                 :             : 
     291                 :           5 :     UniValue ret(UniValue::VOBJ);
     292   [ +  -  +  -  :          10 :     ret.pushKV("hash", block.hash.GetHex());
             +  -  +  - ]
     293   [ +  -  +  -  :          10 :     ret.pushKV("height", block.height);
                   +  - ]
     294                 :           5 :     return ret;
     295                 :           0 : },
     296   [ +  -  +  -  :       22638 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     297   [ +  -  +  -  :       12348 : }
          +  -  +  -  +  
                -  -  - ]
     298                 :             : 
     299                 :        2057 : static RPCHelpMan waitforblock()
     300                 :             : {
     301                 :        2057 :     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         [ +  - ]:        2057 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Block hash to wait for."},
     307         [ +  - ]:        4114 :                     {"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   [ +  -  +  -  :        8228 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     315                 :        2057 :                 RPCExamples{
     316   [ +  -  +  -  :        4114 :                     HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
                   +  - ]
     317   [ +  -  +  -  :        8228 :             + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
             +  -  +  - ]
     318         [ +  - ]:        2057 :                 },
     319                 :           4 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     320                 :             : {
     321                 :           4 :     int timeout = 0;
     322                 :             : 
     323                 :           4 :     uint256 hash(ParseHashV(request.params[0], "blockhash"));
     324                 :             : 
     325         [ +  - ]:           4 :     if (!request.params[1].isNull())
     326                 :           4 :         timeout = request.params[1].getInt<int>();
     327   [ -  +  -  -  :           4 :     if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
                   -  - ]
     328                 :             : 
     329                 :           4 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     330                 :           4 :     Mining& miner = EnsureMining(node);
     331                 :             : 
     332         [ +  - ]:           4 :     auto block{CHECK_NONFATAL(miner.getTip()).value()};
     333                 :           4 :     const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
     334   [ +  -  +  + ]:          10 :     while (IsRPCRunning() && block.hash != hash) {
     335         [ +  - ]:           4 :         if (timeout) {
     336                 :           4 :             auto now{std::chrono::steady_clock::now()};
     337         [ +  + ]:           4 :             if (now >= deadline) break;
     338                 :           2 :             const MillisecondsDouble remaining{deadline - now};
     339                 :           2 :             block = miner.waitTipChanged(block.hash, remaining);
     340                 :             :         } else {
     341                 :           0 :             block = miner.waitTipChanged(block.hash);
     342                 :             :         }
     343                 :             :     }
     344                 :             : 
     345                 :           4 :     UniValue ret(UniValue::VOBJ);
     346   [ +  -  +  -  :           8 :     ret.pushKV("hash", block.hash.GetHex());
             +  -  +  - ]
     347   [ +  -  +  -  :           8 :     ret.pushKV("height", block.height);
                   +  - ]
     348                 :           4 :     return ret;
     349                 :           0 : },
     350   [ +  -  +  -  :       28798 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     351   [ +  -  +  -  :       16456 : }
          +  -  +  -  +  
          -  +  -  -  -  
                   -  - ]
     352                 :             : 
     353                 :        2063 : static RPCHelpMan waitforblockheight()
     354                 :             : {
     355                 :        2063 :     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         [ +  - ]:        2063 :                     {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Block height to wait for."},
     362         [ +  - ]:        4126 :                     {"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   [ +  -  +  -  :        8252 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     370                 :        2063 :                 RPCExamples{
     371   [ +  -  +  -  :        4126 :                     HelpExampleCli("waitforblockheight", "100 1000")
                   +  - ]
     372   [ +  -  +  -  :        8252 :             + HelpExampleRpc("waitforblockheight", "100, 1000")
             +  -  +  - ]
     373         [ +  - ]:        2063 :                 },
     374                 :          10 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     375                 :             : {
     376                 :          10 :     int timeout = 0;
     377                 :             : 
     378                 :          10 :     int height = request.params[0].getInt<int>();
     379                 :             : 
     380         [ +  + ]:          10 :     if (!request.params[1].isNull())
     381                 :           8 :         timeout = request.params[1].getInt<int>();
     382   [ -  +  -  -  :           8 :     if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
                   -  - ]
     383                 :             : 
     384                 :          10 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     385                 :          10 :     Mining& miner = EnsureMining(node);
     386                 :             : 
     387         [ +  - ]:          10 :     auto block{CHECK_NONFATAL(miner.getTip()).value()};
     388                 :          10 :     const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
     389                 :             : 
     390   [ +  -  +  + ]:          32 :     while (IsRPCRunning() && block.height < height) {
     391         [ +  + ]:          14 :         if (timeout) {
     392                 :           4 :             auto now{std::chrono::steady_clock::now()};
     393         [ +  + ]:           4 :             if (now >= deadline) break;
     394                 :           2 :             const MillisecondsDouble remaining{deadline - now};
     395                 :           2 :             block = miner.waitTipChanged(block.hash, remaining);
     396                 :             :         } else {
     397                 :          10 :             block = miner.waitTipChanged(block.hash);
     398                 :             :         }
     399                 :             :     }
     400                 :             : 
     401                 :          10 :     UniValue ret(UniValue::VOBJ);
     402   [ +  -  +  -  :          20 :     ret.pushKV("hash", block.hash.GetHex());
             +  -  +  - ]
     403   [ +  -  +  -  :          20 :     ret.pushKV("height", block.height);
                   +  - ]
     404                 :          10 :     return ret;
     405                 :           0 : },
     406   [ +  -  +  -  :       28882 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     407   [ +  -  +  -  :       16504 : }
          +  -  +  -  +  
          -  +  -  -  -  
                   -  - ]
     408                 :             : 
     409                 :        5778 : static RPCHelpMan syncwithvalidationinterfacequeue()
     410                 :             : {
     411                 :        5778 :     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   [ +  -  +  -  :       11556 :                 RPCResult{RPCResult::Type::NONE, "", ""},
                   +  - ]
     415                 :        5778 :                 RPCExamples{
     416   [ +  -  +  -  :       11556 :                     HelpExampleCli("syncwithvalidationinterfacequeue","")
                   +  - ]
     417   [ +  -  +  -  :       23112 :             + HelpExampleRpc("syncwithvalidationinterfacequeue","")
             +  -  +  - ]
     418         [ +  - ]:        5778 :                 },
     419                 :        3725 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     420                 :             : {
     421                 :        3725 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     422                 :        3725 :     CHECK_NONFATAL(node.validation_signals)->SyncWithValidationInterfaceQueue();
     423                 :        3725 :     return UniValue::VNULL;
     424                 :             : },
     425   [ +  -  +  -  :       34668 :     };
             +  -  +  - ]
     426                 :             : }
     427                 :             : 
     428                 :        2064 : static RPCHelpMan getdifficulty()
     429                 :             : {
     430                 :        2064 :     return RPCHelpMan{"getdifficulty",
     431                 :             :                 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
     432                 :             :                 {},
     433                 :           0 :                 RPCResult{
     434   [ +  -  +  -  :        4128 :                     RPCResult::Type::NUM, "", "the proof-of-work difficulty as a multiple of the minimum difficulty."},
                   +  - ]
     435                 :        2064 :                 RPCExamples{
     436   [ +  -  +  -  :        4128 :                     HelpExampleCli("getdifficulty", "")
                   +  - ]
     437   [ +  -  +  -  :        8256 :             + HelpExampleRpc("getdifficulty", "")
             +  -  +  - ]
     438         [ +  - ]:        2064 :                 },
     439                 :           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     440                 :             : {
     441                 :           2 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     442                 :           2 :     LOCK(cs_main);
     443   [ +  -  +  -  :           4 :     return GetDifficulty(*CHECK_NONFATAL(chainman.ActiveChain().Tip()));
          +  -  +  -  +  
                      - ]
     444                 :           2 : },
     445   [ +  -  +  -  :       12384 :     };
             +  -  +  - ]
     446                 :             : }
     447                 :             : 
     448                 :        2074 : static RPCHelpMan getblockfrompeer()
     449                 :             : {
     450                 :        2074 :     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         [ +  - ]:        2074 :             {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash to try to fetch"},
     462         [ +  - ]:        2074 :             {"peer_id", RPCArg::Type::NUM, RPCArg::Optional::NO, "The peer to fetch it from (see getpeerinfo for peer IDs)"},
     463                 :             :         },
     464   [ +  -  +  -  :        4148 :         RPCResult{RPCResult::Type::OBJ, "", /*optional=*/false, "", {}},
                   +  - ]
     465                 :        2074 :         RPCExamples{
     466   [ +  -  +  -  :        4148 :             HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
                   +  - ]
     467   [ +  -  +  -  :        8296 :             + HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
             +  -  +  - ]
     468         [ +  - ]:        2074 :         },
     469                 :          10 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     470                 :             : {
     471                 :          10 :     const NodeContext& node = EnsureAnyNodeContext(request.context);
     472                 :          10 :     ChainstateManager& chainman = EnsureChainman(node);
     473                 :          10 :     PeerManager& peerman = EnsurePeerman(node);
     474                 :             : 
     475                 :          10 :     const uint256& block_hash{ParseHashV(request.params[0], "blockhash")};
     476                 :           9 :     const NodeId peer_id{request.params[1].getInt<int64_t>()};
     477                 :             : 
     478   [ +  -  +  - ]:          27 :     const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(block_hash););
     479                 :             : 
     480         [ +  + ]:           9 :     if (!index) {
     481   [ +  -  +  - ]:           2 :         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   [ +  +  +  +  :          14 :     if (chainman.m_blockman.IsPruneMode() && index->nHeight > WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()->nHeight)) {
             +  -  +  - ]
     487   [ +  -  +  - ]:           2 :         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         [ +  - ]:          14 :     const bool block_has_data = WITH_LOCK(::cs_main, return index->nStatus & BLOCK_HAVE_DATA);
     491         [ +  + ]:           7 :     if (block_has_data) {
     492   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
     493                 :             :     }
     494                 :             : 
     495         [ +  + ]:           6 :     if (const auto err{peerman.FetchBlock(peer_id, *index)}) {
     496   [ +  -  +  - ]:           3 :         throw JSONRPCError(RPC_MISC_ERROR, err.value());
     497                 :           6 :     }
     498                 :           3 :     return UniValue::VOBJ;
     499                 :             : },
     500   [ +  -  +  -  :       24888 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     501   [ +  -  +  -  :       10370 : }
             +  -  -  - ]
     502                 :             : 
     503                 :        6778 : static RPCHelpMan getblockhash()
     504                 :             : {
     505                 :        6778 :     return RPCHelpMan{"getblockhash",
     506                 :             :                 "\nReturns hash of block in best-block-chain at height provided.\n",
     507                 :             :                 {
     508         [ +  - ]:        6778 :                     {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The height index"},
     509                 :             :                 },
     510                 :           0 :                 RPCResult{
     511   [ +  -  +  -  :       13556 :                     RPCResult::Type::STR_HEX, "", "The block hash"},
                   +  - ]
     512                 :        6778 :                 RPCExamples{
     513   [ +  -  +  -  :       13556 :                     HelpExampleCli("getblockhash", "1000")
                   +  - ]
     514   [ +  -  +  -  :       27112 :             + HelpExampleRpc("getblockhash", "1000")
             +  -  +  - ]
     515         [ +  - ]:        6778 :                 },
     516                 :        4716 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     517                 :             : {
     518                 :        4716 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     519                 :        4716 :     LOCK(cs_main);
     520         [ +  - ]:        4716 :     const CChain& active_chain = chainman.ActiveChain();
     521                 :             : 
     522   [ +  -  +  - ]:        4716 :     int nHeight = request.params[0].getInt<int>();
     523   [ +  -  +  + ]:        4716 :     if (nHeight < 0 || nHeight > active_chain.Height())
     524   [ +  -  +  - ]:           4 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
     525                 :             : 
     526                 :        4714 :     const CBlockIndex* pblockindex = active_chain[nHeight];
     527   [ +  -  +  -  :        9428 :     return pblockindex->GetBlockHash().GetHex();
                   +  - ]
     528                 :        4714 : },
     529   [ +  -  +  -  :       61002 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     530   [ +  -  +  - ]:       20334 : }
     531                 :             : 
     532                 :        4988 : static RPCHelpMan getblockheader()
     533                 :             : {
     534                 :        4988 :     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         [ +  - ]:        4988 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
     539         [ +  - ]:        9976 :                     {"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         [ +  - ]:        9976 :                             {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
     552         [ +  - ]:        9976 :                             {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   [ +  -  +  -  :      104748 :                         }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
     561                 :             :                     RPCResult{"for verbose=false",
     562   [ +  -  +  -  :        9976 :                         RPCResult::Type::STR_HEX, "", "A string that is serialized, hex-encoded data for block 'hash'"},
             +  -  +  - ]
     563                 :             :                 },
     564                 :        4988 :                 RPCExamples{
     565   [ +  -  +  -  :        9976 :                     HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
                   +  - ]
     566   [ +  -  +  -  :       19952 :             + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
             +  -  +  - ]
     567         [ +  - ]:        4988 :                 },
     568                 :        2926 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     569                 :             : {
     570                 :        2926 :     uint256 hash(ParseHashV(request.params[0], "hash"));
     571                 :             : 
     572                 :        2922 :     bool fVerbose = true;
     573         [ +  + ]:        2922 :     if (!request.params[1].isNull())
     574                 :         450 :         fVerbose = request.params[1].get_bool();
     575                 :             : 
     576                 :        2922 :     const CBlockIndex* pblockindex;
     577                 :        2922 :     const CBlockIndex* tip;
     578                 :        2922 :     {
     579                 :        2922 :         ChainstateManager& chainman = EnsureAnyChainman(request.context);
     580                 :        2922 :         LOCK(cs_main);
     581         [ +  - ]:        2922 :         pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
     582   [ +  -  +  -  :        5844 :         tip = chainman.ActiveChain().Tip();
                   +  - ]
     583                 :           0 :     }
     584                 :             : 
     585         [ +  + ]:        2922 :     if (!pblockindex) {
     586   [ +  -  +  - ]:           6 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
     587                 :             :     }
     588                 :             : 
     589         [ +  + ]:        2919 :     if (!fVerbose)
     590                 :             :     {
     591                 :         430 :         DataStream ssBlock{};
     592         [ +  - ]:         430 :         ssBlock << pblockindex->GetBlockHeader();
     593         [ +  - ]:         430 :         std::string strHex = HexStr(ssBlock);
     594         [ +  - ]:         430 :         return strHex;
     595                 :         430 :     }
     596                 :             : 
     597                 :        2489 :     return blockheaderToJSON(*tip, *pblockindex);
     598                 :             : },
     599   [ +  -  +  -  :       84796 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  -  -  
                   -  - ]
     600   [ +  -  +  -  :      114724 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
             -  -  -  - ]
     601                 :             : 
     602                 :        3325 : void CheckBlockDataAvailability(BlockManager& blockman, const CBlockIndex& blockindex, bool check_for_undo)
     603                 :             : {
     604                 :        3325 :     AssertLockHeld(cs_main);
     605         [ +  + ]:        3325 :     uint32_t flag = check_for_undo ? BLOCK_HAVE_UNDO : BLOCK_HAVE_DATA;
     606         [ +  + ]:        3325 :     if (!(blockindex.nStatus & flag)) {
     607         [ +  + ]:         511 :         if (blockman.IsBlockPruned(blockindex)) {
     608   [ +  -  +  -  :          15 :             throw JSONRPCError(RPC_MISC_ERROR, strprintf("%s not available (pruned data)", check_for_undo ? "Undo data" : "Block"));
                   +  - ]
     609                 :             :         }
     610         [ -  + ]:         506 :         if (check_for_undo) {
     611   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_MISC_ERROR, "Undo data not available");
     612                 :             :         }
     613   [ +  -  +  - ]:        1012 :         throw JSONRPCError(RPC_MISC_ERROR, "Block not available (not fully downloaded)");
     614                 :             :     }
     615                 :        2814 : }
     616                 :             : 
     617                 :         113 : static CBlock GetBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
     618                 :             : {
     619                 :         113 :     CBlock block;
     620                 :         113 :     {
     621         [ +  - ]:         113 :         LOCK(cs_main);
     622         [ +  + ]:         113 :         CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
     623                 :           2 :     }
     624                 :             : 
     625   [ +  -  +  + ]:         111 :     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   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
     629                 :             :     }
     630                 :             : 
     631                 :         110 :     return block;
     632                 :           3 : }
     633                 :             : 
     634                 :        3091 : static std::vector<uint8_t> GetRawBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
     635                 :             : {
     636                 :        3091 :     std::vector<uint8_t> data{};
     637                 :        3091 :     FlatFilePos pos{};
     638                 :        3091 :     {
     639         [ +  - ]:        3091 :         LOCK(cs_main);
     640         [ +  + ]:        3091 :         CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
     641         [ +  - ]:        2583 :         pos = blockindex.GetBlockPos();
     642                 :         508 :     }
     643                 :             : 
     644   [ +  -  +  + ]:        2583 :     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   [ +  -  +  - ]:           4 :         throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
     648                 :             :     }
     649                 :             : 
     650                 :        2581 :     return data;
     651                 :         510 : }
     652                 :             : 
     653                 :         110 : static CBlockUndo GetUndoChecked(BlockManager& blockman, const CBlockIndex& blockindex)
     654                 :             : {
     655                 :         110 :     CBlockUndo blockUndo;
     656                 :             : 
     657                 :             :     // The Genesis block does not have undo data
     658         [ +  + ]:         110 :     if (blockindex.nHeight == 0) return blockUndo;
     659                 :             : 
     660                 :         107 :     {
     661         [ +  - ]:         107 :         LOCK(cs_main);
     662         [ +  - ]:         107 :         CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/true);
     663                 :           0 :     }
     664                 :             : 
     665   [ +  -  -  + ]:         107 :     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                 :        5176 : static RPCHelpMan getblock()
     697                 :             : {
     698                 :        5176 :     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         [ +  - ]:        5176 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
     705         [ +  - ]:       10352 :                     {"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         [ +  - ]:       10352 :                      RPCArgOptions{.skip_type_check = true}},
     707                 :             :                 },
     708                 :             :                 {
     709                 :             :                     RPCResult{"for verbosity = 0",
     710   [ +  -  +  -  :       10352 :                 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         [ +  - ]:       10352 :                     {RPCResult::Type::NUM_TIME, "time",       "The block time expressed in " + UNIX_EPOCH_TIME},
     726         [ +  - ]:       10352 :                     {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   [ +  -  +  -  :      139752 :                 }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  +  +  +  -  
                -  -  - ]
     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         [ +  - ]:       10352 :                             {RPCResult::Type::NUM, "fee", "The transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
     745                 :             :                         }},
     746                 :             :                     }},
     747   [ +  -  +  -  :       56936 :                 }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
          +  +  +  -  -  
             -  -  -  - ]
     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   [ +  -  +  -  :       51760 :                 }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
          +  +  +  -  -  
             -  -  -  - ]
     760                 :             :         },
     761                 :        5176 :                 RPCExamples{
     762   [ +  -  +  -  :       10352 :                     HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
                   +  - ]
     763   [ +  -  +  -  :       20704 :             + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
             +  -  +  - ]
     764         [ +  - ]:        5176 :                 },
     765                 :        3114 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     766                 :             : {
     767                 :        3114 :     uint256 hash(ParseHashV(request.params[0], "blockhash"));
     768                 :             : 
     769                 :        3114 :     int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/1, /*allow_bool=*/true)};
     770                 :             : 
     771                 :        3112 :     const CBlockIndex* pblockindex;
     772                 :        3112 :     const CBlockIndex* tip;
     773                 :        3112 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     774                 :        3112 :     {
     775                 :        3112 :         LOCK(cs_main);
     776         [ +  - ]:        3112 :         pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
     777   [ +  -  +  - ]:        3112 :         tip = chainman.ActiveChain().Tip();
     778                 :             : 
     779         [ +  + ]:        3112 :         if (!pblockindex) {
     780   [ +  -  +  - ]:          42 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
     781                 :             :         }
     782                 :          21 :     }
     783                 :             : 
     784                 :        3091 :     const std::vector<uint8_t> block_data{GetRawBlockChecked(chainman.m_blockman, *pblockindex)};
     785                 :             : 
     786         [ +  + ]:        2581 :     if (verbosity <= 0) {
     787   [ +  -  +  - ]:        2556 :         return HexStr(block_data);
     788                 :             :     }
     789                 :             : 
     790         [ +  - ]:        1303 :     DataStream block_stream{block_data};
     791                 :        1303 :     CBlock block{};
     792         [ +  - ]:        1303 :     block_stream >> TX_WITH_WITNESS(block);
     793                 :             : 
     794                 :        1303 :     TxVerbosity tx_verbosity;
     795         [ +  + ]:        1303 :     if (verbosity == 1) {
     796                 :             :         tx_verbosity = TxVerbosity::SHOW_TXID;
     797         [ +  + ]:         128 :     } else if (verbosity == 2) {
     798                 :             :         tx_verbosity = TxVerbosity::SHOW_DETAILS;
     799                 :             :     } else {
     800                 :          12 :         tx_verbosity = TxVerbosity::SHOW_DETAILS_AND_PREVOUT;
     801                 :             :     }
     802                 :             : 
     803         [ +  + ]:        1303 :     return blockToJSON(chainman.m_blockman, block, *tip, *pblockindex, tx_verbosity);
     804                 :        3884 : },
     805   [ +  -  +  -  :       98344 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  -  -  
                   -  - ]
     806   [ +  -  +  -  :      196688 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  -  -  -  -  
                   -  - ]
     807                 :             : 
     808                 :             : //! Return height of highest block that has been pruned, or std::nullopt if no blocks have been pruned
     809                 :          69 : std::optional<int> GetPruneHeight(const BlockManager& blockman, const CChain& chain) {
     810                 :          69 :     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         [ +  - ]:          69 :     const CBlockIndex* first_block{chain[1]};
     816         [ +  - ]:          69 :     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         [ -  + ]:          69 :     if (!first_block || !chain_tip) return std::nullopt;
     820                 :             : 
     821                 :             :     // If the chain tip is pruned, everything is pruned.
     822         [ +  + ]:          69 :     if (!((chain_tip->nStatus & BLOCK_HAVE_MASK) == BLOCK_HAVE_MASK)) return chain_tip->nHeight;
     823                 :             : 
     824                 :          67 :     const auto& first_unpruned{*CHECK_NONFATAL(blockman.GetFirstBlock(*chain_tip, /*status_mask=*/BLOCK_HAVE_MASK, first_block))};
     825         [ +  + ]:          67 :     if (&first_unpruned == first_block) {
     826                 :             :         // All blocks between first_block and chain_tip have data, so nothing is pruned.
     827                 :          31 :         return std::nullopt;
     828                 :             :     }
     829                 :             : 
     830                 :             :     // Block before the first unpruned block is the last pruned block.
     831                 :          36 :     return CHECK_NONFATAL(first_unpruned.pprev)->nHeight;
     832                 :             : }
     833                 :             : 
     834                 :        2098 : static RPCHelpMan pruneblockchain()
     835                 :             : {
     836                 :        2098 :     return RPCHelpMan{"pruneblockchain", "",
     837                 :             :                 {
     838         [ +  - ]:        4196 :                     {"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                 :        2098 :             "                  to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
     840                 :             :                 },
     841                 :           0 :                 RPCResult{
     842   [ +  -  +  -  :        4196 :                     RPCResult::Type::NUM, "", "Height of the last block pruned"},
                   +  - ]
     843                 :        2098 :                 RPCExamples{
     844   [ +  -  +  -  :        4196 :                     HelpExampleCli("pruneblockchain", "1000")
                   +  - ]
     845   [ +  -  +  -  :        8392 :             + HelpExampleRpc("pruneblockchain", "1000")
             +  -  +  - ]
     846         [ +  - ]:        2098 :                 },
     847                 :          36 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     848                 :             : {
     849                 :          36 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
     850         [ +  + ]:          36 :     if (!chainman.m_blockman.IsPruneMode()) {
     851   [ +  -  +  - ]:           4 :         throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
     852                 :             :     }
     853                 :             : 
     854                 :          34 :     LOCK(cs_main);
     855         [ +  - ]:          34 :     Chainstate& active_chainstate = chainman.ActiveChainstate();
     856                 :          34 :     CChain& active_chain = active_chainstate.m_chain;
     857                 :             : 
     858   [ +  -  +  - ]:          34 :     int heightParam = request.params[0].getInt<int>();
     859         [ +  + ]:          34 :     if (heightParam < 0) {
     860   [ +  -  +  - ]:           4 :         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         [ +  + ]:          32 :     if (heightParam > 1000000000) {
     866                 :             :         // Add a 2 hour buffer to include blocks which might have had old timestamps
     867         [ +  - ]:           8 :         const CBlockIndex* pindex = active_chain.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0);
     868         [ +  + ]:           8 :         if (!pindex) {
     869   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
     870                 :             :         }
     871                 :           7 :         heightParam = pindex->nHeight;
     872                 :             :     }
     873                 :             : 
     874                 :          31 :     unsigned int height = (unsigned int) heightParam;
     875         [ +  + ]:          31 :     unsigned int chainHeight = (unsigned int) active_chain.Height();
     876         [ +  + ]:          31 :     if (chainHeight < chainman.GetParams().PruneAfterHeight()) {
     877   [ +  -  +  - ]:           4 :         throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
     878         [ +  + ]:          29 :     } else if (height > chainHeight) {
     879   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
     880         [ +  + ]:          28 :     } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
     881   [ +  -  +  -  :           6 :         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         [ +  - ]:          28 :     PruneBlockFilesManual(active_chainstate, height);
     886   [ +  -  +  +  :          52 :     return GetPruneHeight(chainman.m_blockman, active_chain).value_or(-1);
                   +  - ]
     887                 :          28 : },
     888   [ +  -  +  -  :       18882 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     889   [ +  -  +  - ]:        6294 : }
     890                 :             : 
     891                 :          55 : CoinStatsHashType ParseHashType(const std::string& hash_type_input)
     892                 :             : {
     893         [ +  + ]:          55 :     if (hash_type_input == "hash_serialized_3") {
     894                 :             :         return CoinStatsHashType::HASH_SERIALIZED;
     895         [ +  + ]:          49 :     } else if (hash_type_input == "muhash") {
     896                 :             :         return CoinStatsHashType::MUHASH;
     897         [ +  + ]:          14 :     } else if (hash_type_input == "none") {
     898                 :             :         return CoinStatsHashType::NONE;
     899                 :             :     } else {
     900   [ +  -  +  - ]:           4 :         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                 :         124 : 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   [ +  +  +  +  :         124 :     if ((hash_type == kernel::CoinStatsHashType::MUHASH || hash_type == kernel::CoinStatsHashType::NONE) && g_coin_stats_index && index_requested) {
                   +  + ]
     917         [ +  - ]:          60 :         if (pindex) {
     918                 :          60 :             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   [ +  +  +  - ]:          88 :     CHECK_NONFATAL(!pindex || pindex->GetBlockHash() == view->GetBestBlock());
     930                 :             : 
     931                 :          64 :     return kernel::ComputeUTXOStats(hash_type, view, blockman, interruption_point);
     932                 :             : }
     933                 :             : 
     934                 :        2128 : static RPCHelpMan gettxoutsetinfo()
     935                 :             : {
     936                 :        2128 :     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         [ +  - ]:        4256 :                     {"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         [ +  - ]:        4256 :                     {"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         [ +  - ]:        4256 :                      RPCArgOptions{
     943                 :             :                          .skip_type_check = true,
     944                 :             :                          .type_str = {"", "string or numeric"},
     945                 :             :                      }},
     946         [ +  - ]:        4256 :                     {"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   [ +  -  +  -  :       51072 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  +  +  
          -  -  -  -  -  
                      - ]
     976                 :        2128 :                 RPCExamples{
     977   [ +  -  +  -  :        4256 :                     HelpExampleCli("gettxoutsetinfo", "") +
                   +  - ]
     978   [ +  -  +  -  :        8512 :                     HelpExampleCli("gettxoutsetinfo", R"("none")") +
             +  -  +  - ]
     979   [ +  -  +  -  :        8512 :                     HelpExampleCli("gettxoutsetinfo", R"("none" 1000)") +
             +  -  +  - ]
     980   [ +  -  +  -  :        8512 :                     HelpExampleCli("gettxoutsetinfo", R"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
             +  -  +  - ]
     981   [ +  -  +  -  :        8512 :                     HelpExampleCli("-named gettxoutsetinfo", R"(hash_type='muhash' use_index='false')") +
             +  -  +  - ]
     982   [ +  -  +  -  :        8512 :                     HelpExampleRpc("gettxoutsetinfo", "") +
             +  -  +  - ]
     983   [ +  -  +  -  :        8512 :                     HelpExampleRpc("gettxoutsetinfo", R"("none")") +
             +  -  +  - ]
     984   [ +  -  +  -  :        8512 :                     HelpExampleRpc("gettxoutsetinfo", R"("none", 1000)") +
             +  -  +  - ]
     985   [ +  -  +  -  :        6384 :                     HelpExampleRpc("gettxoutsetinfo", R"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
             +  -  +  - ]
     986         [ +  - ]:        2128 :                 },
     987                 :          66 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     988                 :             : {
     989                 :          66 :     UniValue ret(UniValue::VOBJ);
     990                 :             : 
     991                 :          66 :     const CBlockIndex* pindex{nullptr};
     992   [ +  -  +  +  :          66 :     const CoinStatsHashType hash_type{request.params[0].isNull() ? CoinStatsHashType::HASH_SERIALIZED : ParseHashType(request.params[0].get_str())};
          +  -  +  -  +  
                      + ]
     993   [ +  -  +  +  :          64 :     bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
          +  -  +  -  +  
                      + ]
     994                 :             : 
     995         [ +  - ]:          64 :     NodeContext& node = EnsureAnyNodeContext(request.context);
     996         [ +  - ]:          64 :     ChainstateManager& chainman = EnsureChainman(node);
     997         [ +  - ]:          64 :     Chainstate& active_chainstate = chainman.ActiveChainstate();
     998         [ +  - ]:          64 :     active_chainstate.ForceFlushStateToDisk();
     999                 :             : 
    1000                 :          64 :     CCoinsView* coins_view;
    1001                 :          64 :     BlockManager* blockman;
    1002                 :          64 :     {
    1003         [ +  - ]:          64 :         LOCK(::cs_main);
    1004         [ +  - ]:          64 :         coins_view = &active_chainstate.CoinsDB();
    1005                 :          64 :         blockman = &active_chainstate.m_blockman;
    1006   [ +  -  +  -  :          64 :         pindex = blockman->LookupBlockIndex(coins_view->GetBestBlock());
                   +  - ]
    1007                 :           0 :     }
    1008                 :             : 
    1009   [ +  -  +  + ]:          64 :     if (!request.params[1].isNull()) {
    1010         [ +  + ]:          30 :         if (!g_coin_stats_index) {
    1011   [ +  -  +  - ]:           8 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Querying specific block heights requires coinstatsindex");
    1012                 :             :         }
    1013                 :             : 
    1014         [ +  + ]:          26 :         if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
    1015   [ +  -  +  - ]:           8 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "hash_serialized_3 hash type cannot be queried for a specific block");
    1016                 :             :         }
    1017                 :             : 
    1018         [ -  + ]:          22 :         if (!index_requested) {
    1019   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot set use_index to false when querying for a specific block");
    1020                 :             :         }
    1021   [ +  -  +  + ]:          22 :         pindex = ParseHashOrHeight(request.params[1], chainman);
    1022                 :             :     }
    1023                 :             : 
    1024   [ +  +  +  + ]:          55 :     if (index_requested && g_coin_stats_index) {
    1025   [ +  -  -  + ]:          31 :         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         [ +  - ]:          55 :     const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex, index_requested);
    1037         [ +  - ]:          55 :     if (maybe_stats.has_value()) {
    1038         [ +  - ]:          55 :         const CCoinsStats& stats = maybe_stats.value();
    1039   [ +  -  +  -  :         110 :         ret.pushKV("height", (int64_t)stats.nHeight);
                   +  - ]
    1040   [ +  -  +  -  :         110 :         ret.pushKV("bestblock", stats.hashBlock.GetHex());
             +  -  +  - ]
    1041   [ +  -  +  -  :         110 :         ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs);
                   +  - ]
    1042   [ +  -  +  -  :         110 :         ret.pushKV("bogosize", (int64_t)stats.nBogoSize);
                   +  - ]
    1043         [ +  + ]:          55 :         if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
    1044   [ +  -  +  -  :          26 :             ret.pushKV("hash_serialized_3", stats.hashSerialized.GetHex());
             +  -  +  - ]
    1045                 :             :         }
    1046         [ +  + ]:          55 :         if (hash_type == CoinStatsHashType::MUHASH) {
    1047   [ +  -  +  -  :          64 :             ret.pushKV("muhash", stats.hashSerialized.GetHex());
             +  -  +  - ]
    1048                 :             :         }
    1049         [ +  - ]:          55 :         CHECK_NONFATAL(stats.total_amount.has_value());
    1050   [ +  -  +  -  :         110 :         ret.pushKV("total_amount", ValueFromAmount(stats.total_amount.value()));
             +  -  +  - ]
    1051         [ +  + ]:          55 :         if (!stats.index_used) {
    1052   [ +  -  +  -  :          48 :             ret.pushKV("transactions", static_cast<int64_t>(stats.nTransactions));
                   +  - ]
    1053   [ +  -  +  -  :          48 :             ret.pushKV("disk_size", stats.nDiskSize);
                   +  - ]
    1054                 :             :         } else {
    1055   [ +  -  +  -  :          62 :             ret.pushKV("total_unspendable_amount", ValueFromAmount(stats.total_unspendable_amount));
                   +  - ]
    1056                 :             : 
    1057                 :          31 :             CCoinsStats prev_stats{};
    1058         [ +  + ]:          31 :             if (pindex->nHeight > 0) {
    1059         [ +  - ]:          29 :                 const std::optional<CCoinsStats> maybe_prev_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex->pprev, index_requested);
    1060         [ -  + ]:          29 :                 if (!maybe_prev_stats) {
    1061   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
    1062                 :             :                 }
    1063                 :          29 :                 prev_stats = maybe_prev_stats.value();
    1064                 :             :             }
    1065                 :             : 
    1066                 :          31 :             UniValue block_info(UniValue::VOBJ);
    1067   [ +  -  +  -  :          62 :             block_info.pushKV("prevout_spent", ValueFromAmount(stats.total_prevout_spent_amount - prev_stats.total_prevout_spent_amount));
                   +  - ]
    1068   [ +  -  +  -  :          62 :             block_info.pushKV("coinbase", ValueFromAmount(stats.total_coinbase_amount - prev_stats.total_coinbase_amount));
                   +  - ]
    1069   [ +  -  +  -  :          62 :             block_info.pushKV("new_outputs_ex_coinbase", ValueFromAmount(stats.total_new_outputs_ex_coinbase_amount - prev_stats.total_new_outputs_ex_coinbase_amount));
                   +  - ]
    1070   [ +  -  +  -  :          62 :             block_info.pushKV("unspendable", ValueFromAmount(stats.total_unspendable_amount - prev_stats.total_unspendable_amount));
                   +  - ]
    1071                 :             : 
    1072                 :          31 :             UniValue unspendables(UniValue::VOBJ);
    1073   [ +  -  +  -  :          62 :             unspendables.pushKV("genesis_block", ValueFromAmount(stats.total_unspendables_genesis_block - prev_stats.total_unspendables_genesis_block));
                   +  - ]
    1074   [ +  -  +  -  :          62 :             unspendables.pushKV("bip30", ValueFromAmount(stats.total_unspendables_bip30 - prev_stats.total_unspendables_bip30));
                   +  - ]
    1075   [ +  -  +  -  :          62 :             unspendables.pushKV("scripts", ValueFromAmount(stats.total_unspendables_scripts - prev_stats.total_unspendables_scripts));
                   +  - ]
    1076   [ +  -  +  -  :          62 :             unspendables.pushKV("unclaimed_rewards", ValueFromAmount(stats.total_unspendables_unclaimed_rewards - prev_stats.total_unspendables_unclaimed_rewards));
                   +  - ]
    1077   [ +  -  +  - ]:          62 :             block_info.pushKV("unspendables", std::move(unspendables));
    1078                 :             : 
    1079   [ +  -  +  - ]:          62 :             ret.pushKV("block_info", std::move(block_info));
    1080                 :          31 :         }
    1081                 :             :     } else {
    1082   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
    1083                 :             :     }
    1084                 :          55 :     return ret;
    1085                 :          11 : },
    1086   [ +  -  +  -  :       44688 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
    1087   [ +  -  +  -  :       57456 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  -  -  
             -  -  -  - ]
    1088                 :             : 
    1089                 :        2078 : static RPCHelpMan gettxout()
    1090                 :             : {
    1091                 :        2078 :     return RPCHelpMan{"gettxout",
    1092                 :             :         "\nReturns details about an unspent transaction output.\n",
    1093                 :             :         {
    1094         [ +  - ]:        2078 :             {"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
    1095         [ +  - ]:        2078 :             {"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
    1096         [ +  - ]:        4156 :             {"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   [ +  -  +  -  :        4156 :             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         [ +  - ]:        4156 :                 {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   [ +  -  +  -  :       31170 :             }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
    1113                 :             :         },
    1114                 :        2078 :         RPCExamples{
    1115                 :             :             "\nGet unspent transactions\n"
    1116   [ +  -  +  -  :        4156 :             + HelpExampleCli("listunspent", "") +
             +  -  +  - ]
    1117                 :        2078 :             "\nView the details\n"
    1118   [ +  -  +  -  :        8312 :             + HelpExampleCli("gettxout", "\"txid\" 1") +
             +  -  +  - ]
    1119                 :        2078 :             "\nAs a JSON-RPC call\n"
    1120   [ +  -  +  -  :        8312 :             + HelpExampleRpc("gettxout", "\"txid\", 1")
             +  -  +  - ]
    1121         [ +  - ]:        2078 :                 },
    1122                 :          16 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1123                 :             : {
    1124                 :          16 :     NodeContext& node = EnsureAnyNodeContext(request.context);
    1125                 :          16 :     ChainstateManager& chainman = EnsureChainman(node);
    1126                 :          16 :     LOCK(cs_main);
    1127                 :             : 
    1128                 :          16 :     UniValue ret(UniValue::VOBJ);
    1129                 :             : 
    1130   [ +  -  +  - ]:          16 :     auto hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
    1131   [ +  -  +  -  :          16 :     COutPoint out{hash, request.params[1].getInt<uint32_t>()};
                   +  - ]
    1132                 :          16 :     bool fMempool = true;
    1133   [ +  -  +  + ]:          16 :     if (!request.params[2].isNull())
    1134   [ +  -  +  - ]:           7 :         fMempool = request.params[2].get_bool();
    1135                 :             : 
    1136         [ +  - ]:          16 :     Chainstate& active_chainstate = chainman.ActiveChainstate();
    1137         [ +  - ]:          16 :     CCoinsViewCache* coins_view = &active_chainstate.CoinsTip();
    1138                 :             : 
    1139                 :          16 :     std::optional<Coin> coin;
    1140         [ +  + ]:          16 :     if (fMempool) {
    1141         [ +  - ]:          13 :         const CTxMemPool& mempool = EnsureMemPool(node);
    1142         [ +  - ]:          13 :         LOCK(mempool.cs);
    1143         [ +  - ]:          13 :         CCoinsViewMemPool view(coins_view, mempool);
    1144   [ +  -  +  +  :          23 :         if (!mempool.isSpent(out)) coin = view.GetCoin(out);
                   +  - ]
    1145         [ +  - ]:          26 :     } else {
    1146         [ +  - ]:           6 :         coin = coins_view->GetCoin(out);
    1147                 :             :     }
    1148         [ +  + ]:          16 :     if (!coin) return UniValue::VNULL;
    1149                 :             : 
    1150   [ +  -  +  - ]:          12 :     const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(coins_view->GetBestBlock());
    1151   [ +  -  +  -  :          24 :     ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
             +  -  +  - ]
    1152         [ +  + ]:          12 :     if (coin->nHeight == MEMPOOL_HEIGHT) {
    1153   [ +  -  +  -  :           4 :         ret.pushKV("confirmations", 0);
                   +  - ]
    1154                 :             :     } else {
    1155   [ +  -  +  -  :          20 :         ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin->nHeight + 1));
                   +  - ]
    1156                 :             :     }
    1157   [ +  -  +  -  :          24 :     ret.pushKV("value", ValueFromAmount(coin->out.nValue));
                   +  - ]
    1158                 :          12 :     UniValue o(UniValue::VOBJ);
    1159         [ +  - ]:          12 :     ScriptToUniv(coin->out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
    1160   [ +  -  +  - ]:          24 :     ret.pushKV("scriptPubKey", std::move(o));
    1161   [ +  -  +  -  :          24 :     ret.pushKV("coinbase", (bool)coin->fCoinBase);
                   +  - ]
    1162                 :             : 
    1163                 :          12 :     return ret;
    1164         [ +  - ]:          44 : },
    1165   [ +  -  +  -  :       41560 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  +  
          +  +  -  -  -  
                      - ]
    1166   [ +  -  +  -  :       41560 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
                -  -  - ]
    1167                 :             : 
    1168                 :        2066 : static RPCHelpMan verifychain()
    1169                 :             : {
    1170                 :        2066 :     return RPCHelpMan{"verifychain",
    1171                 :             :                 "\nVerifies blockchain database.\n",
    1172                 :             :                 {
    1173         [ +  - ]:        4132 :                     {"checklevel", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, range=0-4", DEFAULT_CHECKLEVEL)},
    1174         [ +  - ]:        4132 :                         strprintf("How thorough the block verification is:\n%s", MakeUnorderedList(CHECKLEVEL_DOC))},
    1175         [ +  - ]:        4132 :                     {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, 0=all", DEFAULT_CHECKBLOCKS)}, "The number of blocks to check."},
    1176                 :             :                 },
    1177                 :           0 :                 RPCResult{
    1178   [ +  -  +  -  :        4132 :                     RPCResult::Type::BOOL, "", "Verification finished successfully. If false, check debug.log for reason."},
                   +  - ]
    1179                 :        2066 :                 RPCExamples{
    1180   [ +  -  +  -  :        4132 :                     HelpExampleCli("verifychain", "")
                   +  - ]
    1181   [ +  -  +  -  :        8264 :             + HelpExampleRpc("verifychain", "")
             +  -  +  - ]
    1182         [ +  - ]:        2066 :                 },
    1183                 :           4 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1184                 :             : {
    1185         [ +  - ]:           4 :     const int check_level{request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].getInt<int>()};
    1186         [ +  - ]:           4 :     const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].getInt<int>()};
    1187                 :             : 
    1188                 :           4 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1189                 :           4 :     LOCK(cs_main);
    1190                 :             : 
    1191         [ +  - ]:           4 :     Chainstate& active_chainstate = chainman.ActiveChainstate();
    1192   [ +  -  +  -  :          12 :     return CVerifyDB(chainman.GetNotifications()).VerifyDB(
                   +  - ]
    1193   [ +  -  +  -  :           4 :                active_chainstate, chainman.GetParams().GetConsensus(), active_chainstate.CoinsTip(), check_level, check_depth) == VerifyDBResult::SUCCESS;
                   +  - ]
    1194                 :           4 : },
    1195   [ +  -  +  -  :       33056 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
    1196   [ +  -  +  -  :       10330 : }
             +  -  -  - ]
    1197                 :             : 
    1198                 :         455 : static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::BuriedDeployment dep)
    1199                 :             : {
    1200                 :             :     // For buried deployments.
    1201                 :             : 
    1202         [ +  - ]:         455 :     if (!DeploymentEnabled(chainman, dep)) return;
    1203                 :             : 
    1204                 :         455 :     UniValue rv(UniValue::VOBJ);
    1205   [ +  -  +  -  :         910 :     rv.pushKV("type", "buried");
                   +  - ]
    1206                 :             :     // getdeploymentinfo reports the softfork as active from when the chain height is
    1207                 :             :     // one below the activation height
    1208   [ +  -  +  -  :         910 :     rv.pushKV("active", DeploymentActiveAfter(blockindex, chainman, dep));
                   +  - ]
    1209   [ +  -  +  -  :         910 :     rv.pushKV("height", chainman.GetConsensus().DeploymentHeight(dep));
                   +  - ]
    1210   [ +  -  +  - ]:         910 :     softforks.pushKV(DeploymentName(dep), std::move(rv));
    1211                 :         455 : }
    1212                 :             : 
    1213                 :         182 : static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::DeploymentPos id)
    1214                 :             : {
    1215                 :             :     // For BIP9 deployments.
    1216                 :             : 
    1217         [ +  - ]:         182 :     if (!DeploymentEnabled(chainman, id)) return;
    1218         [ +  - ]:         182 :     if (blockindex == nullptr) return;
    1219                 :             : 
    1220                 :         546 :     auto get_state_name = [](const ThresholdState state) -> std::string {
    1221   [ +  +  +  +  :         364 :         switch (state) {
                   -  - ]
    1222                 :         114 :         case ThresholdState::DEFINED: return "defined";
    1223                 :          62 :         case ThresholdState::STARTED: return "started";
    1224                 :           5 :         case ThresholdState::LOCKED_IN: return "locked_in";
    1225                 :         183 :         case ThresholdState::ACTIVE: return "active";
    1226                 :           0 :         case ThresholdState::FAILED: return "failed";
    1227                 :             :         }
    1228                 :           0 :         return "invalid";
    1229                 :             :     };
    1230                 :             : 
    1231                 :         182 :     UniValue bip9(UniValue::VOBJ);
    1232                 :             : 
    1233         [ +  - ]:         182 :     const ThresholdState next_state = chainman.m_versionbitscache.State(blockindex, chainman.GetConsensus(), id);
    1234         [ +  - ]:         182 :     const ThresholdState current_state = chainman.m_versionbitscache.State(blockindex->pprev, chainman.GetConsensus(), id);
    1235                 :             : 
    1236                 :         182 :     const bool has_signal = (ThresholdState::STARTED == current_state || ThresholdState::LOCKED_IN == current_state);
    1237                 :             : 
    1238                 :             :     // BIP9 parameters
    1239         [ +  + ]:         182 :     if (has_signal) {
    1240   [ +  -  +  -  :          68 :         bip9.pushKV("bit", chainman.GetConsensus().vDeployments[id].bit);
                   +  - ]
    1241                 :             :     }
    1242   [ +  -  +  -  :         364 :     bip9.pushKV("start_time", chainman.GetConsensus().vDeployments[id].nStartTime);
                   +  - ]
    1243   [ +  -  +  -  :         364 :     bip9.pushKV("timeout", chainman.GetConsensus().vDeployments[id].nTimeout);
                   +  - ]
    1244   [ +  -  +  -  :         364 :     bip9.pushKV("min_activation_height", chainman.GetConsensus().vDeployments[id].min_activation_height);
                   +  - ]
    1245                 :             : 
    1246                 :             :     // BIP9 status
    1247   [ +  -  +  -  :         364 :     bip9.pushKV("status", get_state_name(current_state));
             +  -  +  - ]
    1248   [ +  -  +  -  :         364 :     bip9.pushKV("since", chainman.m_versionbitscache.StateSinceHeight(blockindex->pprev, chainman.GetConsensus(), id));
             +  -  +  - ]
    1249   [ +  -  +  -  :         364 :     bip9.pushKV("status_next", get_state_name(next_state));
             +  -  +  - ]
    1250                 :             : 
    1251                 :             :     // BIP9 signalling status, if applicable
    1252         [ +  + ]:         182 :     if (has_signal) {
    1253                 :          34 :         UniValue statsUV(UniValue::VOBJ);
    1254                 :          34 :         std::vector<bool> signals;
    1255         [ +  - ]:          34 :         BIP9Stats statsStruct = chainman.m_versionbitscache.Statistics(blockindex, chainman.GetConsensus(), id, &signals);
    1256   [ +  -  +  -  :          68 :         statsUV.pushKV("period", statsStruct.period);
                   +  - ]
    1257   [ +  -  +  -  :          68 :         statsUV.pushKV("elapsed", statsStruct.elapsed);
                   +  - ]
    1258   [ +  -  +  -  :          68 :         statsUV.pushKV("count", statsStruct.count);
                   +  - ]
    1259         [ +  + ]:          34 :         if (ThresholdState::LOCKED_IN != current_state) {
    1260   [ +  -  +  -  :          64 :             statsUV.pushKV("threshold", statsStruct.threshold);
                   +  - ]
    1261   [ +  -  +  -  :          64 :             statsUV.pushKV("possible", statsStruct.possible);
                   +  - ]
    1262                 :             :         }
    1263   [ +  -  +  - ]:          68 :         bip9.pushKV("statistics", std::move(statsUV));
    1264                 :             : 
    1265         [ +  - ]:          34 :         std::string sig;
    1266         [ +  - ]:          34 :         sig.reserve(signals.size());
    1267   [ +  +  -  + ]:       10537 :         for (const bool s : signals) {
    1268   [ +  +  +  - ]:        4311 :             sig.push_back(s ? '#' : '-');
    1269                 :             :         }
    1270   [ +  -  +  -  :          68 :         bip9.pushKV("signalling", sig);
                   +  - ]
    1271                 :          34 :     }
    1272                 :             : 
    1273                 :         182 :     UniValue rv(UniValue::VOBJ);
    1274   [ +  -  +  -  :         364 :     rv.pushKV("type", "bip9");
                   +  - ]
    1275         [ +  + ]:         182 :     if (ThresholdState::ACTIVE == next_state) {
    1276   [ +  -  +  -  :         184 :         rv.pushKV("height", chainman.m_versionbitscache.StateSinceHeight(blockindex, chainman.GetConsensus(), id));
             +  -  +  - ]
    1277                 :             :     }
    1278   [ +  -  +  -  :         364 :     rv.pushKV("active", ThresholdState::ACTIVE == next_state);
                   +  - ]
    1279   [ +  -  +  - ]:         364 :     rv.pushKV("bip9", std::move(bip9));
    1280                 :             : 
    1281   [ +  -  +  - ]:         364 :     softforks.pushKV(DeploymentName(id), std::move(rv));
    1282                 :         182 : }
    1283                 :             : 
    1284                 :             : // used by rest.cpp:rest_chaininfo, so cannot be static
    1285                 :       22164 : RPCHelpMan getblockchaininfo()
    1286                 :             : {
    1287                 :       22164 :     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         [ +  - ]:       44328 :                 {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
    1299         [ +  - ]:       44328 :                 {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   [ +  -  +  -  :       22164 :                 (IsDeprecatedRPCEnabled("warnings") ?
                   -  + ]
    1309   [ -  -  -  -  :       22164 :                     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   [ +  -  +  -  :      177312 :                     }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
             -  -  -  -  
                      - ]
    1315                 :             :                 ),
    1316   [ +  -  +  -  :      531936 :             }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
    1317                 :       22164 :         RPCExamples{
    1318   [ +  -  +  -  :       44328 :             HelpExampleCli("getblockchaininfo", "")
                   +  - ]
    1319   [ +  -  +  -  :       88656 :             + HelpExampleRpc("getblockchaininfo", "")
             +  -  +  - ]
    1320         [ +  - ]:       22164 :         },
    1321                 :       20101 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1322                 :             : {
    1323                 :       20101 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1324                 :       20101 :     LOCK(cs_main);
    1325         [ +  - ]:       20101 :     Chainstate& active_chainstate = chainman.ActiveChainstate();
    1326                 :             : 
    1327   [ +  -  +  - ]:       40202 :     const CBlockIndex& tip{*CHECK_NONFATAL(active_chainstate.m_chain.Tip())};
    1328                 :       20101 :     const int height{tip.nHeight};
    1329                 :       20101 :     UniValue obj(UniValue::VOBJ);
    1330   [ +  -  +  -  :       40202 :     obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
             +  -  +  - ]
    1331   [ +  -  +  -  :       40202 :     obj.pushKV("blocks", height);
                   +  - ]
    1332   [ +  -  +  -  :       40202 :     obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
             +  -  +  - ]
    1333   [ +  -  +  -  :       40202 :     obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
             +  -  +  - ]
    1334   [ +  -  +  -  :       40202 :     obj.pushKV("difficulty", GetDifficulty(tip));
             +  -  +  - ]
    1335   [ +  -  +  -  :       40202 :     obj.pushKV("time", tip.GetBlockTime());
                   +  - ]
    1336   [ +  -  +  -  :       40202 :     obj.pushKV("mediantime", tip.GetMedianTimePast());
                   +  - ]
    1337   [ +  -  +  -  :       40202 :     obj.pushKV("verificationprogress", GuessVerificationProgress(chainman.GetParams().TxData(), &tip));
             +  -  +  - ]
    1338   [ +  -  +  -  :       40202 :     obj.pushKV("initialblockdownload", chainman.IsInitialBlockDownload());
             +  -  +  - ]
    1339   [ +  -  +  -  :       40202 :     obj.pushKV("chainwork", tip.nChainWork.GetHex());
             +  -  +  - ]
    1340   [ +  -  +  -  :       40202 :     obj.pushKV("size_on_disk", chainman.m_blockman.CalculateCurrentUsage());
             +  -  +  - ]
    1341   [ +  -  +  -  :       40202 :     obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
                   +  - ]
    1342         [ +  + ]:       20101 :     if (chainman.m_blockman.IsPruneMode()) {
    1343         [ +  - ]:          37 :         const auto prune_height{GetPruneHeight(chainman.m_blockman, active_chainstate.m_chain)};
    1344   [ +  +  +  -  :          74 :         obj.pushKV("pruneheight", prune_height ? prune_height.value() + 1 : 0);
             +  -  +  - ]
    1345                 :             : 
    1346         [ +  - ]:          37 :         const bool automatic_pruning{chainman.m_blockman.GetPruneTarget() != BlockManager::PRUNE_TARGET_MANUAL};
    1347   [ +  -  +  -  :          74 :         obj.pushKV("automatic_pruning",  automatic_pruning);
                   +  - ]
    1348         [ +  + ]:          37 :         if (automatic_pruning) {
    1349   [ +  -  +  -  :          16 :             obj.pushKV("prune_target_size", chainman.m_blockman.GetPruneTarget());
                   +  - ]
    1350                 :             :         }
    1351                 :             :     }
    1352                 :             : 
    1353         [ +  - ]:       20101 :     NodeContext& node = EnsureAnyNodeContext(request.context);
    1354   [ +  -  +  -  :       40202 :     obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
          +  -  +  -  +  
                -  +  - ]
    1355         [ +  - ]:       20101 :     return obj;
    1356                 :       20101 : },
    1357   [ +  -  +  -  :      132984 :     };
             +  -  +  - ]
    1358   [ +  -  +  -  :      398952 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  -  
                      - ]
    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                 :          91 : UniValue DeploymentInfo(const CBlockIndex* blockindex, const ChainstateManager& chainman)
    1387                 :             : {
    1388                 :          91 :     UniValue softforks(UniValue::VOBJ);
    1389         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_HEIGHTINCB);
    1390         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_DERSIG);
    1391         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CLTV);
    1392         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CSV);
    1393         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_SEGWIT);
    1394         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TESTDUMMY);
    1395         [ +  - ]:          91 :     SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TAPROOT);
    1396                 :          91 :     return softforks;
    1397                 :           0 : }
    1398                 :             : } // anon namespace
    1399                 :             : 
    1400                 :        2153 : RPCHelpMan getdeploymentinfo()
    1401                 :             : {
    1402                 :        2153 :     return RPCHelpMan{"getdeploymentinfo",
    1403                 :             :         "Returns an object containing various state info regarding deployments of consensus changes.",
    1404                 :             :         {
    1405         [ +  - ]:        4306 :             {"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   [ +  -  +  -  :       17224 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  +  
          +  +  -  -  -  
                      - ]
    1416   [ +  -  +  -  :        6459 :         RPCExamples{ HelpExampleCli("getdeploymentinfo", "") + HelpExampleRpc("getdeploymentinfo", "") },
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1417                 :          91 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1418                 :             :         {
    1419                 :          91 :             const ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1420                 :          91 :             LOCK(cs_main);
    1421         [ +  - ]:          91 :             const Chainstate& active_chainstate = chainman.ActiveChainstate();
    1422                 :             : 
    1423                 :          91 :             const CBlockIndex* blockindex;
    1424   [ +  -  +  + ]:          91 :             if (request.params[0].isNull()) {
    1425   [ +  -  +  - ]:         174 :                 blockindex = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
    1426                 :             :             } else {
    1427   [ +  -  +  - ]:           4 :                 const uint256 hash(ParseHashV(request.params[0], "blockhash"));
    1428         [ +  - ]:           4 :                 blockindex = chainman.m_blockman.LookupBlockIndex(hash);
    1429         [ -  + ]:           4 :                 if (!blockindex) {
    1430   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    1431                 :             :                 }
    1432                 :             :             }
    1433                 :             : 
    1434                 :          91 :             UniValue deploymentinfo(UniValue::VOBJ);
    1435   [ +  -  +  -  :         182 :             deploymentinfo.pushKV("hash", blockindex->GetBlockHash().ToString());
             +  -  +  - ]
    1436   [ +  -  +  -  :         182 :             deploymentinfo.pushKV("height", blockindex->nHeight);
                   +  - ]
    1437   [ +  -  +  -  :         182 :             deploymentinfo.pushKV("deployments", DeploymentInfo(blockindex, chainman));
                   +  - ]
    1438         [ +  - ]:          91 :             return deploymentinfo;
    1439                 :          91 :         },
    1440   [ +  -  +  -  :       23683 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    1441   [ +  -  +  -  :       17224 : }
          +  -  +  -  +  
          -  +  -  +  -  
                   -  - ]
    1442                 :             : 
    1443                 :             : /** Comparison function for sorting the getchaintips heads.  */
    1444                 :             : struct CompareBlocksByHeight
    1445                 :             : {
    1446                 :         172 :     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   [ +  +  +  +  :         172 :         if (a->nHeight != b->nHeight)
             +  +  +  + ]
    1452                 :          98 :           return (a->nHeight > b->nHeight);
    1453                 :             : 
    1454                 :          74 :         return a < b;
    1455                 :             :     }
    1456                 :             : };
    1457                 :             : 
    1458                 :        2103 : static RPCHelpMan getchaintips()
    1459                 :             : {
    1460                 :        2103 :     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   [ +  -  +  -  :       16824 :                         }}}},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  -  -  
                   -  - ]
    1479                 :        2103 :                 RPCExamples{
    1480   [ +  -  +  -  :        4206 :                     HelpExampleCli("getchaintips", "")
                   +  - ]
    1481   [ +  -  +  -  :        8412 :             + HelpExampleRpc("getchaintips", "")
             +  -  +  - ]
    1482         [ +  - ]:        2103 :                 },
    1483                 :          41 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1484                 :             : {
    1485                 :          41 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1486                 :          41 :     LOCK(cs_main);
    1487         [ +  - ]:          41 :     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                 :          41 :     std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
    1497                 :          41 :     std::set<const CBlockIndex*> setOrphans;
    1498                 :          41 :     std::set<const CBlockIndex*> setPrevs;
    1499                 :             : 
    1500   [ +  +  +  + ]:        7557 :     for (const auto& [_, block_index] : chainman.BlockIndex()) {
    1501         [ +  + ]:        7516 :         if (!active_chain.Contains(&block_index)) {
    1502         [ +  - ]:        2482 :             setOrphans.insert(&block_index);
    1503         [ +  - ]:        2482 :             setPrevs.insert(block_index.pprev);
    1504                 :             :         }
    1505                 :             :     }
    1506                 :             : 
    1507         [ +  + ]:        2523 :     for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
    1508         [ +  + ]:        2482 :         if (setPrevs.erase(*it) == 0) {
    1509         [ +  - ]:          51 :             setTips.insert(*it);
    1510                 :             :         }
    1511                 :             :     }
    1512                 :             : 
    1513                 :             :     // Always report the currently active tip.
    1514   [ +  -  +  - ]:          82 :     setTips.insert(active_chain.Tip());
    1515                 :             : 
    1516                 :             :     /* Construct the output array.  */
    1517                 :          41 :     UniValue res(UniValue::VARR);
    1518         [ +  + ]:         133 :     for (const CBlockIndex* block : setTips) {
    1519                 :          92 :         UniValue obj(UniValue::VOBJ);
    1520   [ +  -  +  -  :         184 :         obj.pushKV("height", block->nHeight);
                   +  - ]
    1521   [ +  -  +  -  :         184 :         obj.pushKV("hash", block->phashBlock->GetHex());
             +  -  +  - ]
    1522                 :             : 
    1523         [ +  - ]:          92 :         const int branchLen = block->nHeight - active_chain.FindFork(block)->nHeight;
    1524   [ +  -  +  -  :         184 :         obj.pushKV("branchlen", branchLen);
                   +  - ]
    1525                 :             : 
    1526         [ +  + ]:          92 :         std::string status;
    1527         [ +  + ]:          92 :         if (active_chain.Contains(block)) {
    1528                 :             :             // This block is part of the currently active chain.
    1529         [ +  - ]:          41 :             status = "active";
    1530         [ +  + ]:          51 :         } else if (block->nStatus & BLOCK_FAILED_MASK) {
    1531                 :             :             // This block or one of its ancestors is invalid.
    1532         [ +  - ]:          17 :             status = "invalid";
    1533         [ +  + ]:          34 :         } else if (!block->HaveNumChainTxs()) {
    1534                 :             :             // This block cannot be connected because full block data for it or one of its parents is missing.
    1535         [ +  - ]:          32 :             status = "headers-only";
    1536         [ +  - ]:           2 :         } 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         [ +  - ]:           2 :             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   [ +  -  +  -  :         184 :         obj.pushKV("status", status);
                   +  - ]
    1547                 :             : 
    1548         [ +  - ]:          92 :         res.push_back(std::move(obj));
    1549                 :          92 :     }
    1550                 :             : 
    1551                 :          41 :     return res;
    1552         [ +  - ]:          82 : },
    1553   [ +  -  +  -  :       12618 :     };
             +  -  +  - ]
    1554   [ +  -  +  -  :       12618 : }
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    1555                 :             : 
    1556                 :        2072 : static RPCHelpMan preciousblock()
    1557                 :             : {
    1558                 :        2072 :     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         [ +  - ]:        2072 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as precious"},
    1564                 :             :                 },
    1565   [ +  -  +  -  :        4144 :                 RPCResult{RPCResult::Type::NONE, "", ""},
                   +  - ]
    1566                 :        2072 :                 RPCExamples{
    1567   [ +  -  +  -  :        4144 :                     HelpExampleCli("preciousblock", "\"blockhash\"")
                   +  - ]
    1568   [ +  -  +  -  :        8288 :             + HelpExampleRpc("preciousblock", "\"blockhash\"")
             +  -  +  - ]
    1569         [ +  - ]:        2072 :                 },
    1570                 :          10 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1571                 :             : {
    1572                 :          10 :     uint256 hash(ParseHashV(request.params[0], "blockhash"));
    1573                 :          10 :     CBlockIndex* pblockindex;
    1574                 :             : 
    1575                 :          10 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1576                 :          10 :     {
    1577                 :          10 :         LOCK(cs_main);
    1578         [ +  - ]:          10 :         pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
    1579         [ -  + ]:          10 :         if (!pblockindex) {
    1580   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    1581                 :             :         }
    1582                 :           0 :     }
    1583                 :             : 
    1584         [ +  - ]:          10 :     BlockValidationState state;
    1585   [ +  -  +  - ]:          10 :     chainman.ActiveChainstate().PreciousBlock(state, pblockindex);
    1586                 :             : 
    1587         [ -  + ]:          10 :     if (!state.IsValid()) {
    1588   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
    1589                 :             :     }
    1590                 :             : 
    1591                 :          10 :     return UniValue::VNULL;
    1592                 :          10 : },
    1593   [ +  -  +  -  :       18648 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    1594   [ +  -  +  - ]:        6216 : }
    1595                 :             : 
    1596                 :          88 : void InvalidateBlock(ChainstateManager& chainman, const uint256 block_hash) {
    1597         [ +  - ]:          88 :     BlockValidationState state;
    1598                 :          88 :     CBlockIndex* pblockindex;
    1599                 :          88 :     {
    1600         [ +  - ]:          88 :         LOCK(chainman.GetMutex());
    1601         [ +  - ]:          88 :         pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
    1602         [ +  + ]:          88 :         if (!pblockindex) {
    1603   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    1604                 :             :         }
    1605                 :           1 :     }
    1606   [ +  -  +  - ]:          87 :     chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
    1607                 :             : 
    1608         [ +  - ]:          87 :     if (state.IsValid()) {
    1609   [ +  -  +  - ]:         174 :         chainman.ActiveChainstate().ActivateBestChain(state);
    1610                 :             :     }
    1611                 :             : 
    1612         [ -  + ]:          87 :     if (!state.IsValid()) {
    1613   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
    1614                 :             :     }
    1615                 :          87 : }
    1616                 :             : 
    1617                 :        2135 : static RPCHelpMan invalidateblock()
    1618                 :             : {
    1619                 :        2135 :     return RPCHelpMan{"invalidateblock",
    1620                 :             :                 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
    1621                 :             :                 {
    1622         [ +  - ]:        2135 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as invalid"},
    1623                 :             :                 },
    1624   [ +  -  +  -  :        4270 :                 RPCResult{RPCResult::Type::NONE, "", ""},
                   +  - ]
    1625                 :        2135 :                 RPCExamples{
    1626   [ +  -  +  -  :        4270 :                     HelpExampleCli("invalidateblock", "\"blockhash\"")
                   +  - ]
    1627   [ +  -  +  -  :        8540 :             + HelpExampleRpc("invalidateblock", "\"blockhash\"")
             +  -  +  - ]
    1628         [ +  - ]:        2135 :                 },
    1629                 :          82 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1630                 :             : {
    1631                 :          82 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1632                 :          82 :     uint256 hash(ParseHashV(request.params[0], "blockhash"));
    1633                 :             : 
    1634                 :          82 :     InvalidateBlock(chainman, hash);
    1635                 :             : 
    1636                 :          81 :     return UniValue::VNULL;
    1637                 :             : },
    1638   [ +  -  +  -  :       19215 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    1639   [ +  -  +  - ]:        6405 : }
    1640                 :             : 
    1641                 :          28 : void ReconsiderBlock(ChainstateManager& chainman, uint256 block_hash) {
    1642                 :          28 :     {
    1643                 :          28 :         LOCK(chainman.GetMutex());
    1644         [ +  - ]:          28 :         CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
    1645         [ -  + ]:          28 :         if (!pblockindex) {
    1646   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    1647                 :             :         }
    1648                 :             : 
    1649   [ +  -  +  - ]:          28 :         chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
    1650                 :           0 :     }
    1651                 :             : 
    1652         [ +  - ]:          28 :     BlockValidationState state;
    1653   [ +  -  +  - ]:          28 :     chainman.ActiveChainstate().ActivateBestChain(state);
    1654                 :             : 
    1655         [ -  + ]:          28 :     if (!state.IsValid()) {
    1656   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
    1657                 :             :     }
    1658                 :          28 : }
    1659                 :             : 
    1660                 :        2075 : static RPCHelpMan reconsiderblock()
    1661                 :             : {
    1662                 :        2075 :     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         [ +  - ]:        2075 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to reconsider"},
    1667                 :             :                 },
    1668   [ +  -  +  -  :        4150 :                 RPCResult{RPCResult::Type::NONE, "", ""},
                   +  - ]
    1669                 :        2075 :                 RPCExamples{
    1670   [ +  -  +  -  :        4150 :                     HelpExampleCli("reconsiderblock", "\"blockhash\"")
                   +  - ]
    1671   [ +  -  +  -  :        8300 :             + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
             +  -  +  - ]
    1672         [ +  - ]:        2075 :                 },
    1673                 :          22 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1674                 :             : {
    1675                 :          22 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1676                 :          22 :     uint256 hash(ParseHashV(request.params[0], "blockhash"));
    1677                 :             : 
    1678                 :          22 :     ReconsiderBlock(chainman, hash);
    1679                 :             : 
    1680                 :          22 :     return UniValue::VNULL;
    1681                 :             : },
    1682   [ +  -  +  -  :       18675 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    1683   [ +  -  +  - ]:        6225 : }
    1684                 :             : 
    1685                 :        2288 : static RPCHelpMan getchaintxstats()
    1686                 :             : {
    1687                 :        2288 :     return RPCHelpMan{"getchaintxstats",
    1688                 :             :                 "\nCompute statistics about the total number and rate of transactions in the chain.\n",
    1689                 :             :                 {
    1690         [ +  - ]:        4576 :                     {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{"one month"}, "Size of the window in number of blocks"},
    1691         [ +  - ]:        4576 :                     {"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         [ +  - ]:        4576 :                         {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   [ +  -  +  -  :       27456 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
    1711                 :        2288 :                 RPCExamples{
    1712   [ +  -  +  -  :        4576 :                     HelpExampleCli("getchaintxstats", "")
                   +  - ]
    1713   [ +  -  +  -  :        9152 :             + HelpExampleRpc("getchaintxstats", "2016")
             +  -  +  - ]
    1714         [ +  - ]:        2288 :                 },
    1715                 :         220 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1716                 :             : {
    1717                 :         220 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1718                 :         220 :     const CBlockIndex* pindex;
    1719                 :         220 :     int blockcount = 30 * 24 * 60 * 60 / chainman.GetParams().GetConsensus().nPowTargetSpacing; // By default: 1 month
    1720                 :             : 
    1721         [ +  + ]:         220 :     if (request.params[1].isNull()) {
    1722                 :           8 :         LOCK(cs_main);
    1723   [ +  -  +  -  :          16 :         pindex = chainman.ActiveChain().Tip();
                   +  - ]
    1724                 :           8 :     } else {
    1725                 :         212 :         uint256 hash(ParseHashV(request.params[1], "blockhash"));
    1726                 :         208 :         LOCK(cs_main);
    1727         [ +  - ]:         208 :         pindex = chainman.m_blockman.LookupBlockIndex(hash);
    1728         [ +  + ]:         208 :         if (!pindex) {
    1729   [ +  -  +  - ]:           4 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    1730                 :             :         }
    1731   [ +  -  +  + ]:         206 :         if (!chainman.ActiveChain().Contains(pindex)) {
    1732   [ +  -  +  - ]:           4 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
    1733                 :             :         }
    1734                 :         208 :     }
    1735                 :             : 
    1736                 :         212 :     CHECK_NONFATAL(pindex != nullptr);
    1737                 :             : 
    1738         [ +  + ]:         212 :     if (request.params[0].isNull()) {
    1739   [ +  -  +  + ]:          10 :         blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
    1740                 :             :     } else {
    1741                 :         208 :         blockcount = request.params[0].getInt<int>();
    1742                 :             : 
    1743   [ +  +  +  -  :         208 :         if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
                   +  + ]
    1744   [ +  -  +  - ]:           8 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
    1745                 :             :         }
    1746                 :             :     }
    1747                 :             : 
    1748                 :         208 :     const CBlockIndex& past_block{*CHECK_NONFATAL(pindex->GetAncestor(pindex->nHeight - blockcount))};
    1749                 :         208 :     const int64_t nTimeDiff{pindex->GetMedianTimePast() - past_block.GetMedianTimePast()};
    1750                 :             : 
    1751                 :         208 :     UniValue ret(UniValue::VOBJ);
    1752   [ +  -  +  -  :         416 :     ret.pushKV("time", (int64_t)pindex->nTime);
                   +  - ]
    1753         [ +  + ]:         208 :     if (pindex->m_chain_tx_count) {
    1754   [ +  -  +  -  :         218 :         ret.pushKV("txcount", pindex->m_chain_tx_count);
                   +  - ]
    1755                 :             :     }
    1756   [ +  -  +  -  :         416 :     ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex());
             +  -  +  - ]
    1757   [ +  -  +  -  :         416 :     ret.pushKV("window_final_block_height", pindex->nHeight);
                   +  - ]
    1758   [ +  -  +  -  :         416 :     ret.pushKV("window_block_count", blockcount);
                   +  - ]
    1759         [ +  + ]:         208 :     if (blockcount > 0) {
    1760   [ +  -  +  -  :         412 :         ret.pushKV("window_interval", nTimeDiff);
                   +  - ]
    1761   [ +  +  +  + ]:         206 :         if (pindex->m_chain_tx_count != 0 && past_block.m_chain_tx_count != 0) {
    1762                 :         106 :             const auto window_tx_count = pindex->m_chain_tx_count - past_block.m_chain_tx_count;
    1763   [ +  -  +  -  :         212 :             ret.pushKV("window_tx_count", window_tx_count);
                   +  - ]
    1764         [ +  + ]:         106 :             if (nTimeDiff > 0) {
    1765   [ +  -  +  -  :          44 :                 ret.pushKV("txrate", double(window_tx_count) / nTimeDiff);
                   +  - ]
    1766                 :             :             }
    1767                 :             :         }
    1768                 :             :     }
    1769                 :             : 
    1770                 :         208 :     return ret;
    1771                 :           0 : },
    1772   [ +  -  +  -  :       36608 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
    1773   [ +  -  +  -  :       32032 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
    1774                 :             : 
    1775                 :             : template<typename T>
    1776         [ +  + ]:         214 : static T CalculateTruncatedMedian(std::vector<T>& scores)
    1777                 :             : {
    1778                 :         214 :     size_t size = scores.size();
    1779         [ +  + ]:         214 :     if (size == 0) {
    1780                 :             :         return 0;
    1781                 :             :     }
    1782                 :             : 
    1783                 :          14 :     std::sort(scores.begin(), scores.end());
    1784         [ +  + ]:          14 :     if (size % 2 == 0) {
    1785                 :           8 :         return (scores[size / 2 - 1] + scores[size / 2]) / 2;
    1786                 :             :     } else {
    1787                 :           6 :         return scores[size / 2];
    1788                 :             :     }
    1789                 :             : }
    1790                 :             : 
    1791                 :         111 : void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight)
    1792                 :             : {
    1793         [ +  + ]:         111 :     if (scores.empty()) {
    1794                 :             :         return;
    1795                 :             :     }
    1796                 :             : 
    1797                 :          11 :     std::sort(scores.begin(), scores.end());
    1798                 :             : 
    1799                 :             :     // 10th, 25th, 50th, 75th, and 90th percentile weight units.
    1800                 :          11 :     const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
    1801                 :          11 :         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                 :          11 :     };
    1803                 :             : 
    1804                 :          11 :     int64_t next_percentile_index = 0;
    1805                 :          11 :     int64_t cumulative_weight = 0;
    1806         [ +  + ]:         246 :     for (const auto& element : scores) {
    1807                 :         235 :         cumulative_weight += element.second;
    1808   [ +  +  +  + ]:         290 :         while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
    1809                 :          55 :             result[next_percentile_index] = element.first;
    1810                 :          55 :             ++next_percentile_index;
    1811                 :             :         }
    1812                 :             :     }
    1813                 :             : 
    1814                 :             :     // Fill any remaining percentiles with the last value.
    1815         [ -  + ]:          11 :     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                 :        2220 : static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
    1824                 :             : {
    1825   [ +  +  +  -  :        4121 :     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                 :        2176 : static RPCHelpMan getblockstats()
    1832                 :             : {
    1833                 :        2176 :     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         [ +  - ]:        2176 :                     {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block hash or height of the target block",
    1838         [ +  - ]:        4352 :                      RPCArgOptions{
    1839                 :             :                          .skip_type_check = true,
    1840                 :             :                          .type_str = {"", "string or numeric"},
    1841                 :             :                      }},
    1842         [ +  - ]:        4352 :                     {"stats", RPCArg::Type::ARR, RPCArg::DefaultHint{"all values"}, "Values to plot (see result below)",
    1843                 :             :                         {
    1844         [ +  - ]:        2176 :                             {"height", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
    1845         [ +  - ]:        2176 :                             {"time", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
    1846                 :             :                         },
    1847   [ +  -  +  - ]:        2176 :                         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   [ +  -  +  -  :       84864 :             }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  +  +  +  -  
                -  -  - ]
    1891                 :        2176 :                 RPCExamples{
    1892   [ +  -  +  -  :        4352 :                     HelpExampleCli("getblockstats", R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
                   +  - ]
    1893   [ +  -  +  -  :        8704 :                     HelpExampleCli("getblockstats", R"(1000 '["minfeerate","avgfeerate"]')") +
             +  -  +  - ]
    1894   [ +  -  +  -  :        8704 :                     HelpExampleRpc("getblockstats", R"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
             +  -  +  - ]
    1895   [ +  -  +  -  :        6528 :                     HelpExampleRpc("getblockstats", R"(1000, ["minfeerate","avgfeerate"])")
             +  -  +  - ]
    1896         [ +  - ]:        2176 :                 },
    1897                 :         112 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    1898                 :             : {
    1899                 :         112 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    1900                 :         112 :     const CBlockIndex& pindex{*CHECK_NONFATAL(ParseHashOrHeight(request.params[0], chainman))};
    1901                 :             : 
    1902         [ +  - ]:         109 :     std::set<std::string> stats;
    1903   [ +  -  +  + ]:         109 :     if (!request.params[1].isNull()) {
    1904   [ +  -  +  -  :          99 :         const UniValue stats_univalue = request.params[1].get_array();
                   +  - ]
    1905         [ +  + ]:         204 :         for (unsigned int i = 0; i < stats_univalue.size(); i++) {
    1906   [ +  -  +  -  :         105 :             const std::string stat = stats_univalue[i].get_str();
                   +  - ]
    1907         [ +  - ]:         105 :             stats.insert(stat);
    1908                 :         105 :         }
    1909                 :          99 :     }
    1910                 :             : 
    1911         [ +  + ]:         109 :     const CBlock& block = GetBlockChecked(chainman.m_blockman, pindex);
    1912         [ +  - ]:         107 :     const CBlockUndo& blockUndo = GetUndoChecked(chainman.m_blockman, pindex);
    1913                 :             : 
    1914         [ +  + ]:         107 :     const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
    1915   [ +  +  +  -  :         206 :     const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
                   +  + ]
    1916   [ +  +  +  -  :         206 :     const bool do_medianfee = do_all || stats.count("medianfee") != 0;
                   +  + ]
    1917   [ +  +  +  -  :         206 :     const bool do_feerate_percentiles = do_all || stats.count("feerate_percentiles") != 0;
                   +  + ]
    1918   [ +  +  +  +  :         200 :     const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
                   +  + ]
    1919   [ +  -  +  + ]:         200 :         SetHasKeys(stats, "utxo_increase", "utxo_increase_actual", "utxo_size_inc", "utxo_size_inc_actual", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
    1920   [ +  -  +  -  :         110 :     const bool loop_outputs = do_all || loop_inputs || stats.count("total_out");
                   +  + ]
    1921   [ +  +  +  + ]:         203 :     const bool do_calculate_size = do_mediantxsize ||
    1922         [ +  - ]:          96 :         SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size");
    1923   [ +  +  +  -  :         107 :     const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "feerate_percentiles", "minfeerate", "maxfeerate");
                   +  + ]
    1924   [ +  -  +  -  :          99 :     const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight");
                   +  + ]
    1925                 :             : 
    1926                 :         107 :     CAmount maxfee = 0;
    1927                 :         107 :     CAmount maxfeerate = 0;
    1928                 :         107 :     CAmount minfee = MAX_MONEY;
    1929                 :         107 :     CAmount minfeerate = MAX_MONEY;
    1930                 :         107 :     CAmount total_out = 0;
    1931                 :         107 :     CAmount totalfee = 0;
    1932                 :         107 :     int64_t inputs = 0;
    1933                 :         107 :     int64_t maxtxsize = 0;
    1934                 :         107 :     int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
    1935                 :         107 :     int64_t outputs = 0;
    1936                 :         107 :     int64_t swtotal_size = 0;
    1937                 :         107 :     int64_t swtotal_weight = 0;
    1938                 :         107 :     int64_t swtxs = 0;
    1939                 :         107 :     int64_t total_size = 0;
    1940                 :         107 :     int64_t total_weight = 0;
    1941                 :         107 :     int64_t utxos = 0;
    1942                 :         107 :     int64_t utxo_size_inc = 0;
    1943                 :         107 :     int64_t utxo_size_inc_actual = 0;
    1944                 :         107 :     std::vector<CAmount> fee_array;
    1945                 :         107 :     std::vector<std::pair<CAmount, int64_t>> feerate_array;
    1946                 :         107 :     std::vector<int64_t> txsize_array;
    1947                 :             : 
    1948         [ +  + ]:         383 :     for (size_t i = 0; i < block.vtx.size(); ++i) {
    1949         [ +  - ]:         276 :         const auto& tx = block.vtx.at(i);
    1950         [ +  + ]:         276 :         outputs += tx->vout.size();
    1951                 :             : 
    1952                 :         276 :         CAmount tx_total_out = 0;
    1953         [ +  + ]:         276 :         if (loop_outputs) {
    1954         [ +  + ]:         416 :             for (const CTxOut& out : tx->vout) {
    1955                 :         277 :                 tx_total_out += out.nValue;
    1956                 :             : 
    1957                 :         277 :                 size_t out_size = GetSerializeSize(out) + PER_UTXO_OVERHEAD;
    1958                 :         277 :                 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   [ +  +  +  -  :         277 :                 if (pindex.nHeight == 0 || (IsBIP30Repeat(pindex) && tx->IsCoinBase())) continue;
             -  +  -  - ]
    1963                 :             :                 // Skip unspendable outputs since they are not included in the UTXO set
    1964         [ +  + ]:         276 :                 if (out.scriptPubKey.IsUnspendable()) continue;
    1965                 :             : 
    1966                 :         205 :                 ++utxos;
    1967                 :         205 :                 utxo_size_inc_actual += out_size;
    1968                 :             :             }
    1969                 :             :         }
    1970                 :             : 
    1971         [ +  + ]:         276 :         if (tx->IsCoinBase()) {
    1972                 :         107 :             continue;
    1973                 :             :         }
    1974                 :             : 
    1975         [ +  + ]:         169 :         inputs += tx->vin.size(); // Don't count coinbase's fake input
    1976                 :         169 :         total_out += tx_total_out; // Don't count coinbase reward
    1977                 :             : 
    1978                 :         169 :         int64_t tx_size = 0;
    1979         [ +  + ]:         169 :         if (do_calculate_size) {
    1980                 :             : 
    1981         [ +  - ]:          44 :             tx_size = tx->GetTotalSize();
    1982         [ +  + ]:          44 :             if (do_mediantxsize) {
    1983         [ +  - ]:          19 :                 txsize_array.push_back(tx_size);
    1984                 :             :             }
    1985         [ +  + ]:          44 :             maxtxsize = std::max(maxtxsize, tx_size);
    1986         [ +  + ]:          44 :             mintxsize = std::min(mintxsize, tx_size);
    1987                 :          44 :             total_size += tx_size;
    1988                 :             :         }
    1989                 :             : 
    1990                 :         169 :         int64_t weight = 0;
    1991         [ +  + ]:         169 :         if (do_calculate_weight) {
    1992                 :          44 :             weight = GetTransactionWeight(*tx);
    1993                 :          44 :             total_weight += weight;
    1994                 :             :         }
    1995                 :             : 
    1996   [ +  +  +  + ]:         169 :         if (do_calculate_sw && tx->HasWitness()) {
    1997                 :          24 :             ++swtxs;
    1998                 :          24 :             swtotal_size += tx_size;
    1999                 :          24 :             swtotal_weight += weight;
    2000                 :             :         }
    2001                 :             : 
    2002         [ +  + ]:         169 :         if (loop_inputs) {
    2003                 :          79 :             CAmount tx_total_in = 0;
    2004         [ +  - ]:          79 :             const auto& txundo = blockUndo.vtxundo.at(i - 1);
    2005         [ +  + ]:         158 :             for (const Coin& coin: txundo.vprevout) {
    2006                 :          79 :                 const CTxOut& prevoutput = coin.out;
    2007                 :             : 
    2008                 :          79 :                 tx_total_in += prevoutput.nValue;
    2009                 :          79 :                 size_t prevout_size = GetSerializeSize(prevoutput) + PER_UTXO_OVERHEAD;
    2010                 :          79 :                 utxo_size_inc -= prevout_size;
    2011                 :          79 :                 utxo_size_inc_actual -= prevout_size;
    2012                 :             :             }
    2013                 :             : 
    2014                 :          79 :             CAmount txfee = tx_total_in - tx_total_out;
    2015         [ +  - ]:          79 :             CHECK_NONFATAL(MoneyRange(txfee));
    2016         [ +  + ]:          79 :             if (do_medianfee) {
    2017         [ +  - ]:          19 :                 fee_array.push_back(txfee);
    2018                 :             :             }
    2019         [ +  + ]:          79 :             maxfee = std::max(maxfee, txfee);
    2020         [ +  + ]:          79 :             minfee = std::min(minfee, txfee);
    2021                 :          79 :             totalfee += txfee;
    2022                 :             : 
    2023                 :             :             // New feerate uses satoshis per virtual byte instead of per serialized byte
    2024         [ +  + ]:          79 :             CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
    2025         [ +  + ]:          79 :             if (do_feerate_percentiles) {
    2026         [ +  - ]:          19 :                 feerate_array.emplace_back(feerate, weight);
    2027                 :             :             }
    2028         [ +  + ]:          79 :             maxfeerate = std::max(maxfeerate, feerate);
    2029         [ +  + ]:         127 :             minfeerate = std::min(minfeerate, feerate);
    2030                 :             :         }
    2031                 :             :     }
    2032                 :             : 
    2033                 :         107 :     CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
    2034         [ +  - ]:         107 :     CalculatePercentilesByWeight(feerate_percentiles, feerate_array, total_weight);
    2035                 :             : 
    2036                 :         107 :     UniValue feerates_res(UniValue::VARR);
    2037         [ +  + ]:         642 :     for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
    2038   [ +  -  +  - ]:         535 :         feerates_res.push_back(feerate_percentiles[i]);
    2039                 :             :     }
    2040                 :             : 
    2041                 :         107 :     UniValue ret_all(UniValue::VOBJ);
    2042   [ +  +  +  -  :         214 :     ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
             +  -  +  - ]
    2043   [ +  +  +  -  :         214 :     ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
             +  -  +  - ]
    2044   [ +  +  +  -  :         214 :     ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
             +  -  +  - ]
    2045   [ +  -  +  -  :         214 :     ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
             +  -  +  - ]
    2046   [ +  -  +  - ]:         214 :     ret_all.pushKV("feerate_percentiles", std::move(feerates_res));
    2047   [ +  -  +  -  :         214 :     ret_all.pushKV("height", (int64_t)pindex.nHeight);
                   +  - ]
    2048   [ +  -  +  -  :         214 :     ret_all.pushKV("ins", inputs);
                   +  - ]
    2049   [ +  -  +  -  :         214 :     ret_all.pushKV("maxfee", maxfee);
                   +  - ]
    2050   [ +  -  +  -  :         214 :     ret_all.pushKV("maxfeerate", maxfeerate);
                   +  - ]
    2051   [ +  -  +  -  :         214 :     ret_all.pushKV("maxtxsize", maxtxsize);
                   +  - ]
    2052   [ +  -  +  -  :         214 :     ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
                   +  - ]
    2053   [ +  -  +  -  :         214 :     ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
                   +  - ]
    2054   [ +  -  +  -  :         214 :     ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
                   +  - ]
    2055   [ +  +  +  -  :         245 :     ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
             +  -  +  - ]
    2056   [ +  +  +  -  :         245 :     ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
             +  -  +  - ]
    2057   [ +  +  +  -  :         231 :     ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
             +  -  +  - ]
    2058   [ +  -  +  -  :         214 :     ret_all.pushKV("outs", outputs);
                   +  - ]
    2059   [ +  -  +  -  :         214 :     ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight, chainman.GetParams().GetConsensus()));
             +  -  +  - ]
    2060   [ +  -  +  -  :         214 :     ret_all.pushKV("swtotal_size", swtotal_size);
                   +  - ]
    2061   [ +  -  +  -  :         214 :     ret_all.pushKV("swtotal_weight", swtotal_weight);
                   +  - ]
    2062   [ +  -  +  -  :         214 :     ret_all.pushKV("swtxs", swtxs);
                   +  - ]
    2063   [ +  -  +  -  :         214 :     ret_all.pushKV("time", pindex.GetBlockTime());
                   +  - ]
    2064   [ +  -  +  -  :         214 :     ret_all.pushKV("total_out", total_out);
                   +  - ]
    2065   [ +  -  +  -  :         214 :     ret_all.pushKV("total_size", total_size);
                   +  - ]
    2066   [ +  -  +  -  :         214 :     ret_all.pushKV("total_weight", total_weight);
                   +  - ]
    2067   [ +  -  +  -  :         214 :     ret_all.pushKV("totalfee", totalfee);
                   +  - ]
    2068   [ +  -  +  -  :         214 :     ret_all.pushKV("txs", (int64_t)block.vtx.size());
                   +  - ]
    2069   [ +  -  +  -  :         214 :     ret_all.pushKV("utxo_increase", outputs - inputs);
                   +  - ]
    2070   [ +  -  +  -  :         214 :     ret_all.pushKV("utxo_size_inc", utxo_size_inc);
                   +  - ]
    2071   [ +  -  +  -  :         214 :     ret_all.pushKV("utxo_increase_actual", utxos - inputs);
                   +  - ]
    2072   [ +  -  +  -  :         214 :     ret_all.pushKV("utxo_size_inc_actual", utxo_size_inc_actual);
                   +  - ]
    2073                 :             : 
    2074         [ +  + ]:         107 :     if (do_all) {
    2075                 :           8 :         return ret_all;
    2076                 :             :     }
    2077                 :             : 
    2078                 :          99 :     UniValue ret(UniValue::VOBJ);
    2079         [ +  + ]:         194 :     for (const std::string& stat : stats) {
    2080         [ +  - ]:         100 :         const UniValue& value = ret_all[stat];
    2081         [ +  + ]:         100 :         if (value.isNull()) {
    2082   [ +  -  +  - ]:          10 :             throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic '%s'", stat));
    2083                 :             :         }
    2084   [ +  -  +  -  :         190 :         ret.pushKV(stat, value);
                   +  - ]
    2085                 :             :     }
    2086                 :          94 :     return ret;
    2087                 :         142 : },
    2088   [ +  -  +  -  :       43520 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
    2089   [ +  -  +  -  :       95744 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
                -  -  - ]
    2090                 :             : 
    2091                 :             : namespace {
    2092                 :             : //! Search for a given set of pubkey scripts
    2093                 :         976 : 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                 :         976 :     scan_progress = 0;
    2096                 :         976 :     count = 0;
    2097         [ +  + ]:      155518 :     while (cursor->Valid()) {
    2098                 :      154542 :         COutPoint key;
    2099                 :      154542 :         Coin coin;
    2100   [ +  -  +  -  :      154542 :         if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
             +  -  -  + ]
    2101         [ -  + ]:      154542 :         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         [ +  + ]:      154542 :         if (count % 256 == 0) {
    2109                 :             :             // update progress reference every 256 item
    2110                 :         159 :             uint32_t high = 0x100 * *UCharCast(key.hash.begin()) + *(UCharCast(key.hash.begin()) + 1);
    2111                 :         159 :             scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
    2112                 :             :         }
    2113         [ +  + ]:      154542 :         if (needles.count(coin.out.scriptPubKey)) {
    2114         [ +  - ]:      107773 :             out_results.emplace(key, coin);
    2115                 :             :         }
    2116         [ +  - ]:      154542 :         cursor->Next();
    2117                 :      154542 :     }
    2118                 :         976 :     scan_progress = 100;
    2119                 :         976 :     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                 :         984 :     bool reserve() {
    2135                 :         984 :         CHECK_NONFATAL(!m_could_reserve);
    2136         [ +  - ]:         984 :         if (g_scan_in_progress.exchange(true)) {
    2137                 :             :             return false;
    2138                 :             :         }
    2139                 :         984 :         CHECK_NONFATAL(g_scan_progress == 0);
    2140                 :         984 :         m_could_reserve = true;
    2141                 :         984 :         return true;
    2142                 :             :     }
    2143                 :             : 
    2144                 :         984 :     ~CoinsViewScanReserver() {
    2145         [ +  - ]:         984 :         if (m_could_reserve) {
    2146                 :         984 :             g_scan_in_progress = false;
    2147                 :         984 :             g_scan_progress = 0;
    2148                 :             :         }
    2149                 :         984 :     }
    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                 :        3048 : static RPCHelpMan scantxoutset()
    2187                 :             : {
    2188                 :             :     // raw() descriptor corresponding to mainnet address 12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S
    2189                 :        3048 :     const std::string EXAMPLE_DESCRIPTOR_RAW = "raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
    2190                 :             : 
    2191         [ +  - ]:        3048 :     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         [ +  - ]:        6096 :                         {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         [ +  - ]:        6096 :                 {RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of all found unspent outputs in " + CURRENCY_UNIT},
    2234   [ +  -  +  -  :       73152 :             }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  +  
          +  +  -  -  -  
                -  -  - ]
    2235                 :             :             scan_result_abort,
    2236                 :             :             scan_result_status_some,
    2237                 :             :             scan_result_status_none,
    2238                 :             :         },
    2239                 :        3048 :         RPCExamples{
    2240   [ +  -  +  -  :        9144 :             HelpExampleCli("scantxoutset", "start \'[\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]\'") +
                   +  - ]
    2241   [ +  -  +  -  :       12192 :             HelpExampleCli("scantxoutset", "status") +
             +  -  +  - ]
    2242   [ +  -  +  -  :       12192 :             HelpExampleCli("scantxoutset", "abort") +
             +  -  +  - ]
    2243   [ +  -  +  -  :       15240 :             HelpExampleRpc("scantxoutset", "\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]") +
             +  -  +  - ]
    2244   [ +  -  +  -  :       12192 :             HelpExampleRpc("scantxoutset", "\"status\"") +
             +  -  +  - ]
    2245   [ +  -  +  -  :        9144 :             HelpExampleRpc("scantxoutset", "\"abort\"")
             +  -  +  - ]
    2246         [ +  - ]:        3048 :         },
    2247                 :         985 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    2248                 :             : {
    2249                 :         985 :     UniValue result(UniValue::VOBJ);
    2250         [ +  - ]:         985 :     const auto action{self.Arg<std::string>("action")};
    2251         [ +  + ]:         985 :     if (action == "status") {
    2252                 :           1 :         CoinsViewScanReserver reserver;
    2253   [ +  -  +  - ]:           1 :         if (reserver.reserve()) {
    2254                 :             :             // no scan in progress
    2255                 :           1 :             return UniValue::VNULL;
    2256                 :             :         }
    2257   [ #  #  #  #  :           0 :         result.pushKV("progress", g_scan_progress.load());
                   #  # ]
    2258                 :           0 :         return result;
    2259         [ +  + ]:         985 :     } else if (action == "abort") {
    2260                 :           1 :         CoinsViewScanReserver reserver;
    2261   [ +  -  +  - ]:           1 :         if (reserver.reserve()) {
    2262                 :             :             // reserve was possible which means no scan was running
    2263         [ +  - ]:           1 :             return false;
    2264                 :             :         }
    2265                 :             :         // set the abort flag
    2266         [ #  # ]:           0 :         g_should_abort_scan = true;
    2267         [ #  # ]:           0 :         return true;
    2268         [ +  + ]:         984 :     } else if (action == "start") {
    2269                 :         982 :         CoinsViewScanReserver reserver;
    2270   [ +  -  -  + ]:         982 :         if (!reserver.reserve()) {
    2271   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
    2272                 :             :         }
    2273                 :             : 
    2274         [ +  + ]:         982 :         if (request.params.size() < 2) {
    2275   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_MISC_ERROR, "scanobjects argument is required for the start action");
    2276                 :             :         }
    2277                 :             : 
    2278         [ +  - ]:         981 :         std::set<CScript> needles;
    2279         [ +  - ]:         981 :         std::map<CScript, std::string> descriptors;
    2280                 :         981 :         CAmount total_in = 0;
    2281                 :             : 
    2282                 :             :         // loop through the scan objects
    2283   [ +  -  +  -  :        1968 :         for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
             +  -  +  + ]
    2284                 :         992 :             FlatSigningProvider provider;
    2285         [ +  + ]:         992 :             auto scripts = EvalDescriptorStringOrObject(scanobject, provider);
    2286         [ +  + ]:       74050 :             for (CScript& script : scripts) {
    2287   [ +  -  +  - ]:       73063 :                 std::string inferred = InferDescriptor(script, provider)->ToString();
    2288         [ +  - ]:       73063 :                 needles.emplace(script);
    2289         [ +  - ]:       73063 :                 descriptors.emplace(std::move(script), std::move(inferred));
    2290                 :       73063 :             }
    2291                 :         992 :         }
    2292                 :             : 
    2293                 :             :         // Scan the unspent transaction output set for inputs
    2294                 :         976 :         UniValue unspents(UniValue::VARR);
    2295                 :         976 :         std::vector<CTxOut> input_txos;
    2296         [ +  - ]:         976 :         std::map<COutPoint, Coin> coins;
    2297         [ +  - ]:         976 :         g_should_abort_scan = false;
    2298                 :         976 :         int64_t count = 0;
    2299                 :         976 :         std::unique_ptr<CCoinsViewCursor> pcursor;
    2300                 :         976 :         const CBlockIndex* tip;
    2301         [ +  - ]:         976 :         NodeContext& node = EnsureAnyNodeContext(request.context);
    2302                 :         976 :         {
    2303         [ +  - ]:         976 :             ChainstateManager& chainman = EnsureChainman(node);
    2304         [ +  - ]:         976 :             LOCK(cs_main);
    2305         [ +  - ]:         976 :             Chainstate& active_chainstate = chainman.ActiveChainstate();
    2306         [ +  - ]:         976 :             active_chainstate.ForceFlushStateToDisk();
    2307   [ +  -  +  -  :         976 :             pcursor = CHECK_NONFATAL(active_chainstate.CoinsDB().Cursor());
                   +  - ]
    2308   [ +  -  +  -  :        1952 :             tip = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
                   +  - ]
    2309                 :           0 :         }
    2310         [ +  - ]:         976 :         bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point);
    2311   [ +  -  +  -  :        1952 :         result.pushKV("success", res);
                   +  - ]
    2312   [ +  -  +  -  :        1952 :         result.pushKV("txouts", count);
                   +  - ]
    2313   [ +  -  +  -  :        1952 :         result.pushKV("height", tip->nHeight);
                   +  - ]
    2314   [ +  -  +  -  :        1952 :         result.pushKV("bestblock", tip->GetBlockHash().GetHex());
             +  -  +  - ]
    2315                 :             : 
    2316         [ +  + ]:      108749 :         for (const auto& it : coins) {
    2317                 :      107773 :             const COutPoint& outpoint = it.first;
    2318                 :      107773 :             const Coin& coin = it.second;
    2319                 :      107773 :             const CTxOut& txo = coin.out;
    2320   [ +  -  +  - ]:      107773 :             const CBlockIndex& coinb_block{*CHECK_NONFATAL(tip->GetAncestor(coin.nHeight))};
    2321         [ +  - ]:      107773 :             input_txos.push_back(txo);
    2322                 :      107773 :             total_in += txo.nValue;
    2323                 :             : 
    2324                 :      107773 :             UniValue unspent(UniValue::VOBJ);
    2325   [ +  -  +  -  :      215546 :             unspent.pushKV("txid", outpoint.hash.GetHex());
             +  -  +  - ]
    2326   [ +  -  +  -  :      215546 :             unspent.pushKV("vout", outpoint.n);
                   +  - ]
    2327   [ +  +  +  -  :      323319 :             unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey));
          +  -  +  -  +  
                      - ]
    2328   [ +  -  +  -  :      215546 :             unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
             +  -  +  - ]
    2329   [ +  -  +  -  :      215546 :             unspent.pushKV("amount", ValueFromAmount(txo.nValue));
                   +  - ]
    2330   [ +  -  +  -  :      215546 :             unspent.pushKV("coinbase", coin.IsCoinBase());
                   +  - ]
    2331   [ +  -  +  -  :      215546 :             unspent.pushKV("height", coin.nHeight);
                   +  - ]
    2332   [ +  -  +  -  :      215546 :             unspent.pushKV("blockhash", coinb_block.GetBlockHash().GetHex());
             +  -  +  - ]
    2333   [ +  -  +  -  :      215546 :             unspent.pushKV("confirmations", tip->nHeight - coin.nHeight + 1);
                   +  - ]
    2334                 :             : 
    2335         [ +  - ]:      107773 :             unspents.push_back(std::move(unspent));
    2336                 :      107773 :         }
    2337   [ +  -  +  - ]:        1952 :         result.pushKV("unspents", std::move(unspents));
    2338   [ +  -  +  -  :        1952 :         result.pushKV("total_amount", ValueFromAmount(total_in));
                   +  - ]
    2339                 :         987 :     } else {
    2340   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid action '%s'", action));
    2341                 :             :     }
    2342                 :         976 :     return result;
    2343                 :         985 : },
    2344   [ +  -  +  -  :       45720 :     };
          +  -  +  -  +  
          -  +  -  +  +  
          +  +  -  -  -  
                      - ]
    2345   [ +  -  +  -  :       60960 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  -  -  
             -  -  -  -  
                      - ]
    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                 :          21 :     bool reserve() {
    2360                 :          21 :         CHECK_NONFATAL(!m_could_reserve);
    2361         [ +  - ]:          21 :         if (g_scanfilter_in_progress.exchange(true)) {
    2362                 :             :             return false;
    2363                 :             :         }
    2364                 :          21 :         m_could_reserve = true;
    2365                 :          21 :         return true;
    2366                 :             :     }
    2367                 :             : 
    2368                 :          21 :     ~BlockFiltersScanReserver() {
    2369         [ +  - ]:          21 :         if (m_could_reserve) {
    2370                 :          21 :             g_scanfilter_in_progress = false;
    2371                 :             :         }
    2372                 :          21 :     }
    2373                 :             : };
    2374                 :             : 
    2375                 :           4 : static bool CheckBlockFilterMatches(BlockManager& blockman, const CBlockIndex& blockindex, const GCSFilter::ElementSet& needles)
    2376                 :             : {
    2377                 :           4 :     const CBlock block{GetBlockChecked(blockman, blockindex)};
    2378         [ +  - ]:           3 :     const CBlockUndo block_undo{GetUndoChecked(blockman, blockindex)};
    2379                 :             : 
    2380                 :             :     // Check if any of the outputs match the scriptPubKey
    2381         [ +  + ]:           6 :     for (const auto& tx : block.vtx) {
    2382   [ +  -  +  + ]:           5 :         if (std::any_of(tx->vout.cbegin(), tx->vout.cend(), [&](const auto& txout) {
    2383         [ +  + ]:          24 :                 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         [ -  + ]:           1 :     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                 :           3 : }
    2399                 :             : 
    2400                 :        2084 : static RPCHelpMan scanblocks()
    2401                 :             : {
    2402                 :        2084 :     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   [ +  -  +  -  :        6252 :             RPCArg{"start_height", RPCArg::Type::NUM, RPCArg::Default{0}, "Height to start to scan from"},
                   +  - ]
    2409   [ +  -  +  -  :        6252 :             RPCArg{"stop_height", RPCArg::Type::NUM, RPCArg::DefaultHint{"chain tip"}, "Height to stop to scan"},
                   +  - ]
    2410   [ +  -  +  -  :        6252 :             RPCArg{"filtertype", RPCArg::Type::STR, RPCArg::Default{BlockFilterTypeName(BlockFilterType::BASIC)}, "The type name of the filter"},
             +  -  +  - ]
    2411         [ +  - ]:        2084 :             RPCArg{"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
    2412                 :             :                 {
    2413         [ +  - ]:        4168 :                     {"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   [ +  -  +  -  :       14588 :                 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   [ +  -  +  -  :       16672 :             }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  -  -  
                   -  - ]
    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   [ +  -  +  -  :        8336 :             },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
    2432                 :             :             scan_result_abort,
    2433                 :             :         },
    2434                 :        2084 :         RPCExamples{
    2435   [ +  -  +  -  :        4168 :             HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 300000") +
                   +  - ]
    2436   [ +  -  +  -  :        8336 :             HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 100 150 basic") +
             +  -  +  - ]
    2437   [ +  -  +  -  :        8336 :             HelpExampleCli("scanblocks", "status") +
             +  -  +  - ]
    2438   [ +  -  +  -  :        8336 :             HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 300000") +
             +  -  +  - ]
    2439   [ +  -  +  -  :        8336 :             HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 100, 150, \"basic\"") +
             +  -  +  - ]
    2440   [ +  -  +  -  :        6252 :             HelpExampleRpc("scanblocks", "\"status\"")
             +  -  +  - ]
    2441         [ +  - ]:        2084 :         },
    2442                 :          22 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    2443                 :             : {
    2444                 :          22 :     UniValue ret(UniValue::VOBJ);
    2445   [ +  -  +  -  :          22 :     if (request.params[0].get_str() == "status") {
                   +  + ]
    2446                 :           1 :         BlockFiltersScanReserver reserver;
    2447   [ +  -  +  - ]:           1 :         if (reserver.reserve()) {
    2448                 :             :             // no scan in progress
    2449         [ +  - ]:           1 :             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   [ +  -  +  -  :          22 :     } else if (request.params[0].get_str() == "abort") {
                   +  + ]
    2455                 :           1 :         BlockFiltersScanReserver reserver;
    2456   [ +  -  +  - ]:           1 :         if (reserver.reserve()) {
    2457                 :             :             // reserve was possible which means no scan was running
    2458         [ +  - ]:           1 :             return false;
    2459                 :             :         }
    2460                 :             :         // set the abort flag
    2461         [ #  # ]:           0 :         g_scanfilter_should_abort_scan = true;
    2462         [ #  # ]:           0 :         return true;
    2463   [ +  -  +  -  :          21 :     } else if (request.params[0].get_str() == "start") {
                   +  + ]
    2464                 :          19 :         BlockFiltersScanReserver reserver;
    2465   [ +  -  -  + ]:          19 :         if (!reserver.reserve()) {
    2466   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
    2467                 :             :         }
    2468   [ +  -  +  +  :          19 :         const std::string filtertype_name{request.params[4].isNull() ? "basic" : request.params[4].get_str()};
          +  -  +  -  +  
                -  +  - ]
    2469                 :             : 
    2470                 :          19 :         BlockFilterType filtertype;
    2471   [ +  -  +  + ]:          19 :         if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
    2472   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
    2473                 :             :         }
    2474                 :             : 
    2475   [ +  -  +  +  :          18 :         UniValue options{request.params[5].isNull() ? UniValue::VOBJ : request.params[5]};
             +  -  +  - ]
    2476   [ +  -  +  +  :          36 :         bool filter_false_positives{options.exists("filter_false_positives") ? options["filter_false_positives"].get_bool() : false};
          +  -  +  -  +  
                      - ]
    2477                 :             : 
    2478         [ +  - ]:          18 :         BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
    2479         [ +  + ]:          18 :         if (!index) {
    2480   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_MISC_ERROR, "Index is not enabled for filtertype " + filtertype_name);
    2481                 :             :         }
    2482                 :             : 
    2483         [ +  - ]:          17 :         NodeContext& node = EnsureAnyNodeContext(request.context);
    2484         [ +  - ]:          17 :         ChainstateManager& chainman = EnsureChainman(node);
    2485                 :             : 
    2486                 :             :         // set the start-height
    2487                 :          17 :         const CBlockIndex* start_index = nullptr;
    2488                 :          17 :         const CBlockIndex* stop_block = nullptr;
    2489                 :          17 :         {
    2490         [ +  - ]:          17 :             LOCK(cs_main);
    2491         [ +  - ]:          17 :             CChain& active_chain = chainman.ActiveChain();
    2492         [ +  - ]:          17 :             start_index = active_chain.Genesis();
    2493         [ +  - ]:          17 :             stop_block = active_chain.Tip(); // If no stop block is provided, stop at the chain tip.
    2494   [ +  -  +  + ]:          17 :             if (!request.params[2].isNull()) {
    2495   [ +  -  +  -  :          16 :                 start_index = active_chain[request.params[2].getInt<int>()];
                   +  - ]
    2496         [ +  + ]:          16 :                 if (!start_index) {
    2497   [ +  -  +  - ]:           2 :                     throw JSONRPCError(RPC_MISC_ERROR, "Invalid start_height");
    2498                 :             :                 }
    2499                 :             :             }
    2500   [ +  -  +  + ]:          16 :             if (!request.params[3].isNull()) {
    2501   [ +  -  +  -  :          10 :                 stop_block = active_chain[request.params[3].getInt<int>()];
                   +  - ]
    2502   [ +  +  +  + ]:          10 :                 if (!stop_block || stop_block->nHeight < start_index->nHeight) {
    2503   [ +  -  +  - ]:           4 :                     throw JSONRPCError(RPC_MISC_ERROR, "Invalid stop_height");
    2504                 :             :                 }
    2505                 :             :             }
    2506                 :           3 :         }
    2507         [ +  - ]:          14 :         CHECK_NONFATAL(start_index);
    2508         [ +  - ]:          14 :         CHECK_NONFATAL(stop_block);
    2509                 :             : 
    2510                 :             :         // loop through the scan objects, add scripts to the needle_set
    2511         [ +  - ]:          14 :         GCSFilter::ElementSet needle_set;
    2512   [ +  -  +  -  :          28 :         for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
             +  -  +  + ]
    2513                 :          14 :             FlatSigningProvider provider;
    2514         [ +  - ]:          14 :             std::vector<CScript> scripts = EvalDescriptorStringOrObject(scanobject, provider);
    2515         [ +  + ]:         128 :             for (const CScript& script : scripts) {
    2516   [ +  +  +  - ]:         228 :                 needle_set.emplace(script.begin(), script.end());
    2517                 :             :             }
    2518                 :          14 :         }
    2519                 :          14 :         UniValue blocks(UniValue::VARR);
    2520                 :          14 :         const int amount_per_chunk = 10000;
    2521                 :          14 :         std::vector<BlockFilter> filters;
    2522                 :          14 :         int start_block_height = start_index->nHeight; // for progress reporting
    2523                 :          14 :         const int total_blocks_to_process = stop_block->nHeight - start_block_height;
    2524                 :             : 
    2525                 :          14 :         g_scanfilter_should_abort_scan = false;
    2526                 :          14 :         g_scanfilter_progress = 0;
    2527                 :          14 :         g_scanfilter_progress_height = start_block_height;
    2528                 :          14 :         bool completed = true;
    2529                 :             : 
    2530                 :          14 :         const CBlockIndex* end_range = nullptr;
    2531                 :          14 :         do {
    2532         [ +  - ]:          14 :             node.rpc_interruption_point(); // allow a clean shutdown
    2533         [ -  + ]:          14 :             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         [ +  - ]:          14 :             int start_block = !end_range ? start_index->nHeight : start_index->nHeight + 1; // to not include the previous round 'end_range' block
    2540         [ -  + ]:          14 :             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   [ +  -  +  - ]:          14 :             if (index->LookupFilterRange(start_block, end_range, filters)) {
    2545         [ +  + ]:         432 :                 for (const BlockFilter& filter : filters) {
    2546                 :             :                     // compare the elements-set with each filter
    2547   [ +  -  +  + ]:         419 :                     if (filter.GetFilter().MatchAny(needle_set)) {
    2548         [ +  + ]:          12 :                         if (filter_false_positives) {
    2549                 :             :                             // Double check the filter matches by scanning the block
    2550   [ +  -  +  -  :          12 :                             const CBlockIndex& blockindex = *CHECK_NONFATAL(WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(filter.GetBlockHash())));
             +  -  +  - ]
    2551                 :             : 
    2552   [ +  +  +  + ]:           4 :                             if (!CheckBlockFilterMatches(chainman.m_blockman, blockindex, needle_set)) {
    2553                 :           1 :                                 continue;
    2554                 :             :                             }
    2555                 :             :                         }
    2556                 :             : 
    2557   [ +  -  +  -  :          10 :                         blocks.push_back(filter.GetBlockHash().GetHex());
                   +  - ]
    2558                 :             :                     }
    2559                 :             :                 }
    2560                 :             :             }
    2561                 :          13 :             start_index = end_range;
    2562                 :             : 
    2563                 :             :             // update progress
    2564                 :          13 :             int blocks_processed = end_range->nHeight - start_block_height;
    2565         [ +  + ]:          13 :             if (total_blocks_to_process > 0) { // avoid division by zero
    2566                 :           6 :                 g_scanfilter_progress = (int)(100.0 / total_blocks_to_process * blocks_processed);
    2567                 :             :             } else {
    2568                 :           7 :                 g_scanfilter_progress = 100;
    2569                 :             :             }
    2570         [ -  + ]:          13 :             g_scanfilter_progress_height = end_range->nHeight;
    2571                 :             : 
    2572                 :             :         // Finish if we reached the stop block
    2573         [ -  + ]:          13 :         } while (start_index != stop_block);
    2574                 :             : 
    2575   [ +  -  +  -  :          26 :         ret.pushKV("from_height", start_block_height);
                   +  - ]
    2576   [ +  -  +  -  :          26 :         ret.pushKV("to_height", start_index->nHeight); // start_index is always the last scanned block here
                   +  - ]
    2577   [ +  -  +  - ]:          26 :         ret.pushKV("relevant_blocks", std::move(blocks));
    2578   [ +  -  +  -  :          26 :         ret.pushKV("completed", completed);
                   +  - ]
    2579                 :          26 :     }
    2580                 :             :     else {
    2581   [ +  -  +  -  :           2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid action '%s'", request.params[0].get_str()));
             +  -  +  - ]
    2582                 :             :     }
    2583                 :          13 :     return ret;
    2584                 :          22 : },
    2585   [ +  -  +  -  :       39596 :     };
          +  -  +  -  +  
          -  +  +  +  +  
             -  -  -  - ]
    2586   [ +  -  +  -  :       41680 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  -  -  
             -  -  -  - ]
    2587                 :             : 
    2588                 :        2085 : static RPCHelpMan getblockfilter()
    2589                 :             : {
    2590                 :        2085 :     return RPCHelpMan{"getblockfilter",
    2591                 :             :                 "\nRetrieve a BIP 157 content filter for a particular block.\n",
    2592                 :             :                 {
    2593         [ +  - ]:        2085 :                     {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the block"},
    2594   [ +  -  +  - ]:        4170 :                     {"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   [ +  -  +  -  :        8340 :                     }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
    2602                 :        2085 :                 RPCExamples{
    2603   [ +  -  +  -  :        4170 :                     HelpExampleCli("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
                   +  - ]
    2604   [ +  -  +  -  :        6255 :                     HelpExampleRpc("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
             +  -  +  - ]
    2605         [ +  - ]:        2085 :                 },
    2606                 :          23 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    2607                 :             : {
    2608                 :          23 :     uint256 block_hash = ParseHashV(request.params[0], "blockhash");
    2609                 :          23 :     std::string filtertype_name = BlockFilterTypeName(BlockFilterType::BASIC);
    2610   [ +  -  +  + ]:          23 :     if (!request.params[1].isNull()) {
    2611   [ +  -  +  -  :          14 :         filtertype_name = request.params[1].get_str();
                   +  - ]
    2612                 :             :     }
    2613                 :             : 
    2614                 :          23 :     BlockFilterType filtertype;
    2615   [ +  -  +  + ]:          23 :     if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
    2616   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
    2617                 :             :     }
    2618                 :             : 
    2619         [ +  - ]:          22 :     BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
    2620         [ +  + ]:          22 :     if (!index) {
    2621   [ +  -  +  - ]:           6 :         throw JSONRPCError(RPC_MISC_ERROR, "Index is not enabled for filtertype " + filtertype_name);
    2622                 :             :     }
    2623                 :             : 
    2624                 :          19 :     const CBlockIndex* block_index;
    2625                 :          19 :     bool block_was_connected;
    2626                 :          19 :     {
    2627         [ +  - ]:          19 :         ChainstateManager& chainman = EnsureAnyChainman(request.context);
    2628         [ +  - ]:          19 :         LOCK(cs_main);
    2629         [ +  - ]:          19 :         block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
    2630         [ +  + ]:          19 :         if (!block_index) {
    2631   [ +  -  +  - ]:           2 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
    2632                 :             :         }
    2633   [ +  -  +  - ]:          36 :         block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
    2634                 :           1 :     }
    2635                 :             : 
    2636         [ +  - ]:          18 :     bool index_ready = index->BlockUntilSyncedToCurrentChain();
    2637                 :             : 
    2638         [ +  - ]:          18 :     BlockFilter filter;
    2639                 :          18 :     uint256 filter_header;
    2640   [ +  -  +  -  :          36 :     if (!index->LookupFilter(block_index, filter) ||
                   -  + ]
    2641         [ +  - ]:          18 :         !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                 :          18 :     UniValue ret(UniValue::VOBJ);
    2660   [ +  -  +  -  :          36 :     ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
             +  -  +  - ]
    2661   [ +  -  +  -  :          36 :     ret.pushKV("header", filter_header.GetHex());
             +  -  +  - ]
    2662                 :          18 :     return ret;
    2663                 :          18 : },
    2664   [ +  -  +  -  :       29190 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
    2665   [ +  -  +  -  :       16680 : }
          +  -  +  -  +  
          -  +  -  -  -  
                   -  - ]
    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                 :           5 :     NetworkDisable(CConnman& connman) : m_connman(connman) {
    2676                 :           5 :         m_connman.SetNetworkActive(false);
    2677         [ -  + ]:           5 :         if (m_connman.GetNetworkActive()) {
    2678   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_MISC_ERROR, "Network activity could not be suspended.");
    2679                 :             :         }
    2680                 :           5 :     };
    2681                 :           5 :     ~NetworkDisable() {
    2682                 :           5 :         m_connman.SetNetworkActive(true);
    2683                 :           5 :     };
    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                 :           6 :     TemporaryRollback(ChainstateManager& chainman, const CBlockIndex& index) : m_chainman(chainman), m_invalidate_index(index) {
    2696                 :           6 :         InvalidateBlock(m_chainman, m_invalidate_index.GetBlockHash());
    2697                 :           6 :     };
    2698                 :           6 :     ~TemporaryRollback() {
    2699                 :           6 :         ReconsiderBlock(m_chainman, m_invalidate_index.GetBlockHash());
    2700                 :           6 :     };
    2701                 :             : };
    2702                 :             : 
    2703                 :             : /**
    2704                 :             :  * Serialize the UTXO set to a file for loading elsewhere.
    2705                 :             :  *
    2706                 :             :  * @see SnapshotMetadata
    2707                 :             :  */
    2708                 :        2074 : static RPCHelpMan dumptxoutset()
    2709                 :             : {
    2710                 :        2074 :     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         [ +  - ]:        2074 :             {"path", RPCArg::Type::STR, RPCArg::Optional::NO, "Path to the output file. If relative, will be prefixed by datadir."},
    2718         [ +  - ]:        4148 :             {"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         [ +  - ]:        2074 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
    2720                 :             :                 {
    2721         [ +  - ]:        2074 :                     {"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         [ +  - ]:        4148 :                     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   [ +  -  +  -  :       16592 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
    2738                 :        2074 :         RPCExamples{
    2739   [ +  -  +  -  :        4148 :             HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat latest") +
                   +  - ]
    2740   [ +  -  +  -  :        8296 :             HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat rollback") +
             +  -  +  - ]
    2741   [ +  -  +  -  :        6222 :             HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset", R"(utxo.dat rollback=853456)")
             +  -  +  - ]
    2742         [ +  - ]:        2074 :         },
    2743                 :          12 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    2744                 :             : {
    2745                 :          12 :     NodeContext& node = EnsureAnyNodeContext(request.context);
    2746   [ +  -  +  -  :          48 :     const CBlockIndex* tip{WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Tip())};
                   +  - ]
    2747                 :          12 :     const CBlockIndex* target_index{nullptr};
    2748                 :          12 :     const std::string snapshot_type{self.Arg<std::string>("type")};
    2749   [ +  -  +  +  :          12 :     const UniValue options{request.params[2].isNull() ? UniValue::VOBJ : request.params[2]};
             +  -  +  - ]
    2750   [ +  -  +  + ]:          24 :     if (options.exists("rollback")) {
    2751   [ -  +  -  - ]:           5 :         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   [ +  -  +  -  :           5 :         target_index = ParseHashOrHeight(options["rollback"], *node.chainman);
                   +  - ]
    2755         [ +  + ]:           7 :     } else if (snapshot_type == "rollback") {
    2756         [ +  - ]:           1 :         auto snapshot_heights = node.chainman->GetParams().GetAvailableSnapshotHeights();
    2757         [ +  - ]:           1 :         CHECK_NONFATAL(snapshot_heights.size() > 0);
    2758                 :           1 :         auto max_height = std::max_element(snapshot_heights.begin(), snapshot_heights.end());
    2759   [ +  -  +  - ]:           1 :         target_index = ParseHashOrHeight(*max_height, *node.chainman);
    2760         [ +  + ]:           7 :     } else if (snapshot_type == "latest") {
    2761                 :           5 :         target_index = tip;
    2762                 :             :     } else {
    2763   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid snapshot type \"%s\" specified. Please specify \"rollback\" or \"latest\"", snapshot_type));
    2764                 :             :     }
    2765                 :             : 
    2766         [ +  - ]:          11 :     const ArgsManager& args{EnsureAnyArgsman(request.context)};
    2767   [ +  -  +  -  :          33 :     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   [ +  -  +  -  :          44 :     const fs::path temppath = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(request.params[0].get_str() + ".incomplete"));
          +  -  +  -  +  
                      - ]
    2771                 :             : 
    2772   [ +  -  +  + ]:          11 :     if (fs::exists(path)) {
    2773                 :           1 :         throw JSONRPCError(
    2774                 :             :             RPC_INVALID_PARAMETER,
    2775         [ +  - ]:           2 :             path.utf8string() + " already exists. If you are sure this is what you want, "
    2776         [ +  - ]:           3 :             "move it out of the way first");
    2777                 :             :     }
    2778                 :             : 
    2779         [ +  - ]:          10 :     FILE* file{fsbridge::fopen(temppath, "wb")};
    2780         [ +  - ]:          10 :     AutoFile afile{file};
    2781         [ +  + ]:          10 :     if (afile.IsNull()) {
    2782                 :           1 :         throw JSONRPCError(
    2783                 :             :             RPC_INVALID_PARAMETER,
    2784   [ +  -  +  -  :           3 :             "Couldn't open file " + temppath.utf8string() + " for writing.");
                   +  - ]
    2785                 :             :     }
    2786                 :             : 
    2787         [ +  - ]:           9 :     CConnman& connman = EnsureConnman(node);
    2788                 :           9 :     const CBlockIndex* invalidate_index{nullptr};
    2789                 :           9 :     std::optional<NetworkDisable> disable_network;
    2790                 :           9 :     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         [ +  + ]:           9 :     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         [ -  + ]:           6 :         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         [ +  + ]:           6 :         if (connman.GetNetworkActive()) {
    2815         [ +  - ]:           5 :             disable_network.emplace(connman);
    2816                 :             :         }
    2817                 :             : 
    2818   [ +  -  +  -  :          18 :         invalidate_index = WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Next(target_index));
                   +  - ]
    2819         [ +  - ]:           6 :         temporary_rollback.emplace(*node.chainman, *invalidate_index);
    2820                 :             :     }
    2821                 :             : 
    2822                 :           9 :     Chainstate* chainstate;
    2823                 :           9 :     std::unique_ptr<CCoinsViewCursor> cursor;
    2824                 :           9 :     CCoinsStats stats;
    2825                 :           9 :     {
    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         [ +  - ]:           9 :         LOCK(node.chainman->GetMutex());
    2833         [ +  - ]:           9 :         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   [ +  -  +  + ]:          18 :         if (target_index != chainstate->m_chain.Tip()) {
    2841         [ +  - ]:           2 :             LogWarning("dumptxoutset failed to roll back to requested height, reverting to tip.\n");
    2842   [ +  -  +  - ]:           4 :             throw JSONRPCError(RPC_MISC_ERROR, "Could not roll back to requested height.");
    2843                 :             :         } else {
    2844   [ +  -  +  - ]:           7 :             std::tie(cursor, stats, tip) = PrepareUTXOSnapshot(*chainstate, node.rpc_interruption_point);
    2845                 :             :         }
    2846                 :           2 :     }
    2847                 :             : 
    2848         [ +  - ]:           7 :     UniValue result = WriteUTXOSnapshot(*chainstate, cursor.get(), &stats, tip, afile, path, temppath, node.rpc_interruption_point);
    2849         [ +  - ]:           7 :     fs::rename(temppath, path);
    2850                 :             : 
    2851   [ +  -  +  -  :          14 :     result.pushKV("path", path.utf8string());
             +  -  +  - ]
    2852                 :          14 :     return result;
    2853                 :          46 : },
    2854   [ +  -  +  -  :       41480 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
    2855   [ +  -  +  -  :       31110 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
    2856                 :             : 
    2857                 :             : std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex*>
    2858                 :          40 : PrepareUTXOSnapshot(
    2859                 :             :     Chainstate& chainstate,
    2860                 :             :     const std::function<void()>& interruption_point)
    2861                 :             : {
    2862                 :          40 :     std::unique_ptr<CCoinsViewCursor> pcursor;
    2863                 :          40 :     std::optional<CCoinsStats> maybe_stats;
    2864                 :          40 :     const CBlockIndex* tip;
    2865                 :             : 
    2866                 :          40 :     {
    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                 :          40 :         AssertLockHeld(::cs_main);
    2880                 :             : 
    2881         [ +  - ]:          40 :         chainstate.ForceFlushStateToDisk();
    2882                 :             : 
    2883   [ +  -  +  - ]:          40 :         maybe_stats = GetUTXOStats(&chainstate.CoinsDB(), chainstate.m_blockman, CoinStatsHashType::HASH_SERIALIZED, interruption_point);
    2884         [ -  + ]:          40 :         if (!maybe_stats) {
    2885   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
    2886                 :             :         }
    2887                 :             : 
    2888   [ +  -  +  - ]:          80 :         pcursor = chainstate.CoinsDB().Cursor();
    2889   [ +  -  +  - ]:          40 :         tip = CHECK_NONFATAL(chainstate.m_blockman.LookupBlockIndex(maybe_stats->hashBlock));
    2890                 :             :     }
    2891                 :             : 
    2892         [ +  - ]:          40 :     return {std::move(pcursor), *CHECK_NONFATAL(maybe_stats), tip};
    2893                 :          40 : }
    2894                 :             : 
    2895                 :          40 : 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   [ +  -  +  -  :         120 :     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         [ +  - ]:          40 :     SnapshotMetadata metadata{chainstate.m_chainman.GetParams().MessageStart(), tip->GetBlockHash(), maybe_stats->coins_count};
    2910                 :             : 
    2911         [ +  - ]:          40 :     afile << metadata;
    2912                 :             : 
    2913                 :          40 :     COutPoint key;
    2914                 :          40 :     Txid last_hash;
    2915                 :          40 :     Coin coin;
    2916                 :          40 :     unsigned int iter{0};
    2917                 :          40 :     size_t written_coins_count{0};
    2918                 :          40 :     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                 :        5922 :     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                 :        5882 :         afile << last_hash;
    2929                 :        5882 :         WriteCompactSize(afile, coins.size());
    2930         [ +  + ]:       11764 :         for (const auto& [n, coin] : coins) {
    2931                 :        5882 :             WriteCompactSize(afile, n);
    2932                 :        5882 :             afile << coin;
    2933                 :        5882 :             ++written_coins_count;
    2934                 :             :         }
    2935                 :        5882 :     };
    2936                 :             : 
    2937         [ +  - ]:          40 :     pcursor->GetKey(key);
    2938                 :          40 :     last_hash = key.hash;
    2939   [ +  -  +  + ]:        5922 :     while (pcursor->Valid()) {
    2940   [ +  +  +  - ]:        5882 :         if (iter % 5000 == 0) interruption_point();
    2941                 :        5882 :         ++iter;
    2942   [ +  -  +  -  :        5882 :         if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
             +  -  +  - ]
    2943         [ +  + ]:        5882 :             if (key.hash != last_hash) {
    2944         [ +  - ]:        5842 :                 write_coins_to_file(afile, last_hash, coins, written_coins_count);
    2945                 :        5842 :                 last_hash = key.hash;
    2946                 :        5842 :                 coins.clear();
    2947                 :             :             }
    2948         [ +  - ]:        5882 :             coins.emplace_back(key.n, coin);
    2949                 :             :         }
    2950         [ +  - ]:        5882 :         pcursor->Next();
    2951                 :             :     }
    2952                 :             : 
    2953         [ +  - ]:          40 :     if (!coins.empty()) {
    2954         [ +  - ]:          40 :         write_coins_to_file(afile, last_hash, coins, written_coins_count);
    2955                 :             :     }
    2956                 :             : 
    2957         [ +  - ]:          40 :     CHECK_NONFATAL(written_coins_count == maybe_stats->coins_count);
    2958                 :             : 
    2959         [ +  - ]:          40 :     afile.fclose();
    2960                 :             : 
    2961                 :          40 :     UniValue result(UniValue::VOBJ);
    2962   [ +  -  +  -  :          80 :     result.pushKV("coins_written", written_coins_count);
                   +  - ]
    2963   [ +  -  +  -  :          80 :     result.pushKV("base_hash", tip->GetBlockHash().ToString());
             +  -  +  - ]
    2964   [ +  -  +  -  :          80 :     result.pushKV("base_height", tip->nHeight);
                   +  - ]
    2965   [ +  -  +  -  :          80 :     result.pushKV("path", path.utf8string());
             +  -  +  - ]
    2966   [ +  -  +  -  :          80 :     result.pushKV("txoutset_hash", maybe_stats->hashSerialized.ToString());
             +  -  +  - ]
    2967   [ +  -  +  -  :          80 :     result.pushKV("nchaintx", tip->m_chain_tx_count);
                   +  - ]
    2968                 :          40 :     return result;
    2969                 :          40 : }
    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                 :        2101 : static RPCHelpMan loadtxoutset()
    2983                 :             : {
    2984                 :        2101 :     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         [ +  - ]:        2101 :                 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   [ +  -  +  -  :       12606 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    3015                 :        2101 :         RPCExamples{
    3016   [ +  -  +  -  :        4202 :             HelpExampleCli("-rpcclienttimeout=0 loadtxoutset", "utxo.dat")
                   +  - ]
    3017         [ +  - ]:        2101 :         },
    3018                 :          39 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    3019                 :             : {
    3020                 :          39 :     NodeContext& node = EnsureAnyNodeContext(request.context);
    3021                 :          39 :     ChainstateManager& chainman = EnsureChainman(node);
    3022   [ +  -  +  -  :          78 :     const fs::path path{AbsPathForConfigVal(EnsureArgsman(node), fs::u8path(self.Arg<std::string>("path")))};
                   +  - ]
    3023                 :             : 
    3024         [ +  - ]:          39 :     FILE* file{fsbridge::fopen(path, "rb")};
    3025         [ +  - ]:          39 :     AutoFile afile{file};
    3026         [ +  + ]:          39 :     if (afile.IsNull()) {
    3027                 :           1 :         throw JSONRPCError(
    3028                 :             :             RPC_INVALID_PARAMETER,
    3029   [ +  -  +  -  :           3 :             "Couldn't open file " + path.utf8string() + " for reading.");
                   +  - ]
    3030                 :             :     }
    3031                 :             : 
    3032         [ +  - ]:          38 :     SnapshotMetadata metadata{chainman.GetParams().MessageStart()};
    3033                 :          38 :     try {
    3034         [ +  + ]:          38 :         afile >> metadata;
    3035         [ -  + ]:           9 :     } catch (const std::ios_base::failure& e) {
    3036   [ +  -  +  - ]:          18 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Unable to parse metadata: %s", e.what()));
    3037                 :           9 :     }
    3038                 :             : 
    3039         [ +  - ]:          29 :     auto activation_result{chainman.ActivateSnapshot(afile, metadata, false)};
    3040         [ +  + ]:          29 :     if (!activation_result) {
    3041   [ +  -  +  -  :          66 :         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                 :           7 :     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                 :           7 :     node.connman->AddLocalServices(NODE_NETWORK_LIMITED);
    3050                 :             : 
    3051         [ +  - ]:           7 :     CBlockIndex& snapshot_index{*CHECK_NONFATAL(*activation_result)};
    3052                 :             : 
    3053                 :           7 :     UniValue result(UniValue::VOBJ);
    3054   [ +  -  +  -  :          14 :     result.pushKV("coins_loaded", metadata.m_coins_count);
                   +  - ]
    3055   [ +  -  +  -  :          14 :     result.pushKV("tip_hash", snapshot_index.GetBlockHash().ToString());
             +  -  +  - ]
    3056   [ +  -  +  -  :          14 :     result.pushKV("base_height", snapshot_index.nHeight);
                   +  - ]
    3057   [ +  -  +  -  :          21 :     result.pushKV("path", fs::PathToString(path));
             +  -  +  - ]
    3058                 :           7 :     return result;
    3059                 :         106 : },
    3060   [ +  -  +  -  :       18909 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
    3061   [ +  -  +  -  :       16808 : }
          +  -  +  -  +  
          -  +  -  +  -  
                   -  - ]
    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                 :        2332 : static RPCHelpMan getchainstates()
    3075                 :             : {
    3076                 :        2332 : 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   [ +  -  +  -  :       16324 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
    3086                 :        2332 :         RPCExamples{
    3087   [ +  -  +  -  :        4664 :             HelpExampleCli("getchainstates", "")
                   +  - ]
    3088   [ +  -  +  -  :        9328 :     + HelpExampleRpc("getchainstates", "")
             +  -  +  - ]
    3089         [ +  - ]:        2332 :         },
    3090                 :         270 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
    3091                 :             : {
    3092                 :         270 :     LOCK(cs_main);
    3093                 :         270 :     UniValue obj(UniValue::VOBJ);
    3094                 :             : 
    3095         [ +  - ]:         270 :     ChainstateManager& chainman = EnsureAnyChainman(request.context);
    3096                 :             : 
    3097                 :         800 :     auto make_chain_data = [&](const Chainstate& cs, bool validated) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
    3098                 :         530 :         AssertLockHeld(::cs_main);
    3099                 :         530 :         UniValue data(UniValue::VOBJ);
    3100   [ +  -  +  - ]:        1060 :         if (!cs.m_chain.Tip()) {
    3101                 :             :             return data;
    3102                 :             :         }
    3103                 :         530 :         const CChain& chain = cs.m_chain;
    3104         [ +  - ]:         530 :         const CBlockIndex* tip = chain.Tip();
    3105                 :             : 
    3106   [ +  -  +  -  :        1060 :         data.pushKV("blocks",                (int)chain.Height());
                   +  - ]
    3107   [ +  -  +  -  :        1060 :         data.pushKV("bestblockhash",         tip->GetBlockHash().GetHex());
             +  -  +  - ]
    3108   [ +  -  +  -  :        1060 :         data.pushKV("difficulty", GetDifficulty(*tip));
             +  -  +  - ]
    3109   [ +  -  +  -  :        1060 :         data.pushKV("verificationprogress",  GuessVerificationProgress(Params().TxData(), tip));
          +  -  +  -  +  
                      - ]
    3110   [ +  -  +  -  :        1060 :         data.pushKV("coins_db_cache_bytes",  cs.m_coinsdb_cache_size_bytes);
                   +  - ]
    3111   [ +  -  +  -  :        1060 :         data.pushKV("coins_tip_cache_bytes", cs.m_coinstip_cache_size_bytes);
                   +  - ]
    3112         [ +  + ]:         530 :         if (cs.m_from_snapshot_blockhash) {
    3113   [ +  -  +  -  :         528 :             data.pushKV("snapshot_blockhash", cs.m_from_snapshot_blockhash->ToString());
             +  -  +  - ]
    3114                 :             :         }
    3115   [ +  -  +  -  :         530 :         data.pushKV("validated", validated);
                   +  - ]
    3116                 :         530 :         return data;
    3117                 :           0 :     };
    3118                 :             : 
    3119   [ +  -  +  -  :         540 :     obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
             +  -  +  - ]
    3120                 :             : 
    3121         [ +  - ]:         270 :     const auto& chainstates = chainman.GetAll();
    3122                 :         270 :     UniValue obj_chainstates{UniValue::VARR};
    3123         [ +  + ]:         800 :     for (Chainstate* cs : chainstates) {
    3124   [ +  +  +  +  :         534 :       obj_chainstates.push_back(make_chain_data(*cs, !cs->m_from_snapshot_blockhash || chainstates.size() == 1));
             +  -  +  - ]
    3125                 :             :     }
    3126   [ +  -  +  - ]:         540 :     obj.pushKV("chainstates", std::move(obj_chainstates));
    3127                 :         540 :     return obj;
    3128         [ +  - ]:         540 : }
    3129   [ +  -  +  -  :       13992 :     };
             +  -  +  - ]
    3130   [ +  -  +  -  :        9328 : }
          +  -  +  -  -  
                      - ]
    3131                 :             : 
    3132                 :             : 
    3133                 :        1151 : void RegisterBlockchainRPCCommands(CRPCTable& t)
    3134                 :             : {
    3135                 :        1151 :     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   [ +  +  +  -  :        1151 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  -  - ]
    3166         [ +  + ]:       34530 :     for (const auto& c : commands) {
    3167                 :       33379 :         t.appendCommand(c.name, &c);
    3168                 :             :     }
    3169                 :        1151 : }
        

Generated by: LCOV version 2.0-1