LCOV - code coverage report
Current view: top level - src/rpc - blockchain.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 60.0 % 1694 1017
Test Date: 2024-11-04 04:15:01 Functions: 80.0 % 130 104
Branches: 39.1 % 6643 2597

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

Generated by: LCOV version 2.0-1