LCOV - code coverage report
Current view: top level - src - rest.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 0.0 % 760 0
Test Date: 2026-11-27 05:37:43 Functions: 0.0 % 30 0
Branches: 0.0 % 1699 0

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <rest.h>
       7                 :             : 
       8                 :             : #include <blockfilter.h>
       9                 :             : #include <chain.h>
      10                 :             : #include <coins.h>
      11                 :             : #include <consensus/params.h>
      12                 :             : #include <core_io.h>
      13                 :             : #include <crypto/hex_base.h>
      14                 :             : #include <flatfile.h>
      15                 :             : #include <httpserver.h>
      16                 :             : #include <index/blockfilterindex.h>
      17                 :             : #include <index/txindex.h>
      18                 :             : #include <node/blockstorage.h>
      19                 :             : #include <node/context.h>
      20                 :             : #include <node/indexes.h>
      21                 :             : #include <node/transaction.h>
      22                 :             : #include <primitives/block.h>
      23                 :             : #include <primitives/transaction.h>
      24                 :             : #include <rpc/blockchain.h>
      25                 :             : #include <rpc/mempool.h>
      26                 :             : #include <rpc/protocol.h>
      27                 :             : #include <rpc/request.h>
      28                 :             : #include <rpc/server.h>
      29                 :             : #include <rpc/util.h>
      30                 :             : #include <serialize.h>
      31                 :             : #include <streams.h>
      32                 :             : #include <sync.h>
      33                 :             : #include <tinyformat.h>
      34                 :             : #include <txmempool.h>
      35                 :             : #include <uint256.h>
      36                 :             : #include <undo.h>
      37                 :             : #include <univalue.h>
      38                 :             : #include <util/any.h>
      39                 :             : #include <util/check.h>
      40                 :             : #include <util/overflow.h>
      41                 :             : #include <util/strencodings.h>
      42                 :             : #include <util/string.h>
      43                 :             : #include <validation.h>
      44                 :             : 
      45                 :             : #include <any>
      46                 :             : #include <cstdint>
      47                 :             : #include <cstring>
      48                 :             : #include <ios>
      49                 :             : #include <memory>
      50                 :             : #include <optional>
      51                 :             : #include <span>
      52                 :             : #include <stdexcept>
      53                 :             : #include <string_view>
      54                 :             : #include <utility>
      55                 :             : #include <vector>
      56                 :             : 
      57                 :             : using node::GetBlockFilterIndex;
      58                 :             : using node::GetTransaction;
      59                 :             : using node::NodeContext;
      60                 :             : using util::SplitString;
      61                 :             : 
      62                 :             : static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
      63                 :             : static constexpr unsigned int MAX_REST_HEADERS_RESULTS = 2000;
      64                 :             : 
      65                 :             : // Cache-Control values for REST responses.
      66                 :             : /** Response bytes never change. One-day TTL limits staleness across software upgrades. */
      67                 :             : static constexpr const char* REST_CACHE_IMMUTABLE = "public, immutable, max-age=86400";
      68                 :             : /** Mutable, node-local, or error response; must not be cached. */
      69                 :             : static constexpr const char* REST_CACHE_NO_STORE = "no-store";
      70                 :             : 
      71                 :             : static const struct {
      72                 :             :     RESTResponseFormat rf;
      73                 :             :     const char* name;
      74                 :             : } rf_names[] = {
      75                 :             :       {RESTResponseFormat::UNDEF, ""},
      76                 :             :       {RESTResponseFormat::BINARY, "bin"},
      77                 :             :       {RESTResponseFormat::HEX, "hex"},
      78                 :             :       {RESTResponseFormat::JSON, "json"},
      79                 :             : };
      80                 :             : 
      81                 :           0 : struct CCoin {
      82                 :             :     uint32_t nHeight;
      83                 :             :     CTxOut out;
      84                 :             : 
      85                 :             :     CCoin() : nHeight(0) {}
      86                 :           0 :     explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
      87                 :             : 
      88                 :           0 :     SERIALIZE_METHODS(CCoin, obj)
      89                 :             :     {
      90                 :           0 :         uint32_t nTxVerDummy = 0;
      91                 :           0 :         READWRITE(nTxVerDummy, obj.nHeight, obj.out);
      92                 :             :     }
      93                 :             : };
      94                 :             : 
      95                 :           0 : static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
      96                 :             : {
      97   [ #  #  #  # ]:           0 :     req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
      98   [ #  #  #  # ]:           0 :     req->WriteHeader("Content-Type", "text/plain");
      99   [ #  #  #  # ]:           0 :     req->WriteReply(status, message + "\r\n");
     100                 :           0 :     return false;
     101                 :             : }
     102                 :             : 
     103                 :             : /**
     104                 :             :  * Get the node context.
     105                 :             :  *
     106                 :             :  * @param[in]  req  The HTTP request, whose status code will be set if node
     107                 :             :  *                  context is not found.
     108                 :             :  * @returns         Pointer to the node context or nullptr if not found.
     109                 :             :  */
     110                 :           0 : static NodeContext* GetNodeContext(const std::any& context, HTTPRequest* req)
     111                 :             : {
     112                 :           0 :     auto node_context = util::AnyPtr<NodeContext>(context);
     113         [ #  # ]:           0 :     if (!node_context) {
     114         [ #  # ]:           0 :         RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, STR_INTERNAL_BUG("Node context not found!"));
     115                 :           0 :         return nullptr;
     116                 :             :     }
     117                 :             :     return node_context;
     118                 :             : }
     119                 :             : 
     120                 :             : /**
     121                 :             :  * Get the node context mempool.
     122                 :             :  *
     123                 :             :  * @param[in]  req The HTTP request, whose status code will be set if node
     124                 :             :  *                 context mempool is not found.
     125                 :             :  * @returns        Pointer to the mempool or nullptr if no mempool found.
     126                 :             :  */
     127                 :           0 : static CTxMemPool* GetMemPool(const std::any& context, HTTPRequest* req)
     128                 :             : {
     129                 :           0 :     auto node_context = util::AnyPtr<NodeContext>(context);
     130   [ #  #  #  # ]:           0 :     if (!node_context || !node_context->mempool) {
     131         [ #  # ]:           0 :         RESTERR(req, HTTP_NOT_FOUND, "Mempool disabled or instance not found");
     132                 :           0 :         return nullptr;
     133                 :             :     }
     134                 :             :     return node_context->mempool.get();
     135                 :             : }
     136                 :             : 
     137                 :             : /**
     138                 :             :  * Get the node context chainstatemanager.
     139                 :             :  *
     140                 :             :  * @param[in]  req The HTTP request, whose status code will be set if node
     141                 :             :  *                 context chainstatemanager is not found.
     142                 :             :  * @returns        Pointer to the chainstatemanager or nullptr if none found.
     143                 :             :  */
     144                 :           0 : static ChainstateManager* GetChainman(const std::any& context, HTTPRequest* req)
     145                 :             : {
     146                 :           0 :     auto node_context = util::AnyPtr<NodeContext>(context);
     147   [ #  #  #  # ]:           0 :     if (!node_context || !node_context->chainman) {
     148         [ #  # ]:           0 :         RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, STR_INTERNAL_BUG("Chainman disabled or instance not found!"));
     149                 :           0 :         return nullptr;
     150                 :             :     }
     151                 :             :     return node_context->chainman.get();
     152                 :             : }
     153                 :             : 
     154                 :           0 : RESTResponseFormat ParseDataFormat(std::string& param, const std::string& strReq)
     155                 :             : {
     156                 :             :     // Remove query string (if any, separated with '?') as it should not interfere with
     157                 :             :     // parsing param and data format
     158                 :           0 :     param = strReq.substr(0, strReq.rfind('?'));
     159                 :           0 :     const std::string::size_type pos_format{param.rfind('.')};
     160                 :             : 
     161                 :             :     // No format string is found
     162         [ #  # ]:           0 :     if (pos_format == std::string::npos) {
     163                 :             :         return RESTResponseFormat::UNDEF;
     164                 :             :     }
     165                 :             : 
     166                 :             :     // Match format string to available formats
     167                 :           0 :     const std::string suffix(param, pos_format + 1);
     168         [ #  # ]:           0 :     for (const auto& rf_name : rf_names) {
     169         [ #  # ]:           0 :         if (suffix == rf_name.name) {
     170         [ #  # ]:           0 :             param.erase(pos_format);
     171                 :           0 :             return rf_name.rf;
     172                 :             :         }
     173                 :             :     }
     174                 :             : 
     175                 :             :     // If no suffix is found, return RESTResponseFormat::UNDEF and original string without query string
     176                 :             :     return RESTResponseFormat::UNDEF;
     177                 :           0 : }
     178                 :             : 
     179                 :           0 : static std::string AvailableDataFormatsString()
     180                 :             : {
     181                 :           0 :     std::string formats;
     182         [ #  # ]:           0 :     for (const auto& rf_name : rf_names) {
     183         [ #  # ]:           0 :         if (strlen(rf_name.name) > 0) {
     184         [ #  # ]:           0 :             formats.append(".");
     185         [ #  # ]:           0 :             formats.append(rf_name.name);
     186         [ #  # ]:           0 :             formats.append(", ");
     187                 :             :         }
     188                 :             :     }
     189                 :             : 
     190   [ #  #  #  # ]:           0 :     if (formats.length() > 0)
     191         [ #  # ]:           0 :         return formats.substr(0, formats.length() - 2);
     192                 :             : 
     193                 :           0 :     return formats;
     194                 :           0 : }
     195                 :             : 
     196                 :           0 : static bool CheckWarmup(HTTPRequest* req)
     197                 :             : {
     198         [ #  # ]:           0 :     std::string statusmessage;
     199   [ #  #  #  # ]:           0 :     if (RPCIsInWarmup(&statusmessage))
     200   [ #  #  #  # ]:           0 :          return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
     201                 :             :     return true;
     202                 :           0 : }
     203                 :             : 
     204                 :           0 : static bool rest_headers(const std::any& context,
     205                 :             :                          HTTPRequest* req,
     206                 :             :                          const std::string& uri_part)
     207                 :             : {
     208         [ #  # ]:           0 :     if (!CheckWarmup(req))
     209                 :             :         return false;
     210         [ #  # ]:           0 :     std::string param;
     211         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     212   [ #  #  #  # ]:           0 :     std::vector<std::string> path = SplitString(param, '/');
     213                 :             : 
     214         [ #  # ]:           0 :     std::string raw_count;
     215                 :           0 :     std::string hashStr;
     216   [ #  #  #  # ]:           0 :     if (path.size() == 2) {
     217                 :             :         // deprecated path: /rest/headers/<count>/<hash>
     218         [ #  # ]:           0 :         hashStr = path[1];
     219         [ #  # ]:           0 :         raw_count = path[0];
     220         [ #  # ]:           0 :     } else if (path.size() == 1) {
     221                 :             :         // new path with query parameter: /rest/headers/<hash>?count=<count>
     222         [ #  # ]:           0 :         hashStr = path[0];
     223                 :           0 :         try {
     224   [ #  #  #  # ]:           0 :             raw_count = req->GetQueryParameter("count").value_or("5");
     225         [ -  - ]:           0 :         } catch (const std::runtime_error& e) {
     226   [ -  -  -  - ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, e.what());
     227                 :           0 :         }
     228                 :             :     } else {
     229   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/headers/<hash>.<ext>?count=<count>");
     230                 :             :     }
     231                 :             : 
     232         [ #  # ]:           0 :     const auto parsed_count{ToIntegral<size_t>(raw_count)};
     233   [ #  #  #  #  :           0 :     if (!parsed_count.has_value() || *parsed_count < 1 || *parsed_count > MAX_REST_HEADERS_RESULTS) {
                   #  # ]
     234   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count));
     235                 :             :     }
     236                 :             : 
     237   [ #  #  #  # ]:           0 :     auto hash{uint256::FromHex(hashStr)};
     238         [ #  # ]:           0 :     if (!hash) {
     239   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
     240                 :             :     }
     241                 :             : 
     242                 :           0 :     const CBlockIndex* tip = nullptr;
     243                 :           0 :     std::vector<const CBlockIndex*> headers;
     244         [ #  # ]:           0 :     headers.reserve(*parsed_count);
     245         [ #  # ]:           0 :     ChainstateManager* maybe_chainman = GetChainman(context, req);
     246         [ #  # ]:           0 :     if (!maybe_chainman) return false;
     247                 :           0 :     ChainstateManager& chainman = *maybe_chainman;
     248                 :           0 :     {
     249         [ #  # ]:           0 :         LOCK(cs_main);
     250         [ #  # ]:           0 :         CChain& active_chain = chainman.ActiveChain();
     251         [ #  # ]:           0 :         tip = active_chain.Tip();
     252         [ #  # ]:           0 :         const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*hash)};
     253   [ #  #  #  # ]:           0 :         while (pindex != nullptr && active_chain.Contains(*pindex)) {
     254         [ #  # ]:           0 :             headers.push_back(pindex);
     255   [ #  #  #  # ]:           0 :             if (headers.size() == *parsed_count) {
     256                 :             :                 break;
     257                 :             :             }
     258                 :           0 :             pindex = active_chain.Next(*pindex);
     259                 :             :         }
     260                 :           0 :     }
     261                 :             : 
     262   [ #  #  #  # ]:           0 :     switch (rf) {
     263                 :           0 :     case RESTResponseFormat::BINARY: {
     264                 :           0 :         DataStream ssHeader{};
     265         [ #  # ]:           0 :         for (const CBlockIndex *pindex : headers) {
     266         [ #  # ]:           0 :             ssHeader << pindex->GetBlockHeader();
     267                 :             :         }
     268                 :             : 
     269                 :             :         // Do not cache because chain extensions and reorgs can affect the response.
     270   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     271   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     272   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssHeader);
     273                 :           0 :         return true;
     274                 :           0 :     }
     275                 :             : 
     276                 :           0 :     case RESTResponseFormat::HEX: {
     277                 :           0 :         DataStream ssHeader{};
     278         [ #  # ]:           0 :         for (const CBlockIndex *pindex : headers) {
     279         [ #  # ]:           0 :             ssHeader << pindex->GetBlockHeader();
     280                 :             :         }
     281                 :             : 
     282   [ #  #  #  # ]:           0 :         std::string strHex = HexStr(ssHeader) + "\n";
     283   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     284   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     285   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     286                 :           0 :         return true;
     287                 :           0 :     }
     288                 :           0 :     case RESTResponseFormat::JSON: {
     289                 :           0 :         UniValue jsonHeaders(UniValue::VARR);
     290         [ #  # ]:           0 :         for (const CBlockIndex *pindex : headers) {
     291   [ #  #  #  # ]:           0 :             jsonHeaders.push_back(blockheaderToJSON(*tip, *pindex, chainman.GetConsensus().powLimit));
     292                 :             :         }
     293         [ #  # ]:           0 :         std::string strJSON = jsonHeaders.write() + "\n";
     294   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     295   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     296   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     297                 :           0 :         return true;
     298                 :           0 :     }
     299                 :           0 :     default: {
     300   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     301                 :             :     }
     302                 :             :     }
     303                 :           0 : }
     304                 :             : 
     305                 :             : /**
     306                 :             :  * Serialize spent outputs as a list of per-transaction CTxOut lists using binary format.
     307                 :             :  */
     308                 :           0 : static void SerializeBlockUndo(DataStream& stream, const CBlockUndo& block_undo)
     309                 :             : {
     310         [ #  # ]:           0 :     WriteCompactSize(stream, block_undo.vtxundo.size() + 1);
     311                 :           0 :     WriteCompactSize(stream, 0); // block_undo.vtxundo doesn't contain coinbase tx
     312         [ #  # ]:           0 :     for (const CTxUndo& tx_undo : block_undo.vtxundo) {
     313         [ #  # ]:           0 :         WriteCompactSize(stream, tx_undo.vprevout.size());
     314         [ #  # ]:           0 :         for (const Coin& coin : tx_undo.vprevout) {
     315                 :           0 :             coin.out.Serialize(stream);
     316                 :             :         }
     317                 :             :     }
     318                 :           0 : }
     319                 :             : 
     320                 :             : /**
     321                 :             :  * Serialize spent outputs as a list of per-transaction CTxOut lists using JSON format.
     322                 :             :  */
     323                 :           0 : static void BlockUndoToJSON(const CBlockUndo& block_undo, UniValue& result)
     324                 :             : {
     325         [ #  # ]:           0 :     result.push_back({UniValue::VARR}); // block_undo.vtxundo doesn't contain coinbase tx
     326         [ #  # ]:           0 :     for (const CTxUndo& tx_undo : block_undo.vtxundo) {
     327                 :           0 :         UniValue tx_prevouts(UniValue::VARR);
     328         [ #  # ]:           0 :         for (const Coin& coin : tx_undo.vprevout) {
     329                 :           0 :             UniValue prevout(UniValue::VOBJ);
     330   [ #  #  #  #  :           0 :             prevout.pushKV("generated", coin.IsCoinBase());
                   #  # ]
     331   [ #  #  #  #  :           0 :             prevout.pushKV("height", coin.nHeight);
                   #  # ]
     332   [ #  #  #  #  :           0 :             prevout.pushKV("value", ValueFromAmount(coin.out.nValue));
                   #  # ]
     333                 :             : 
     334                 :           0 :             UniValue script_pub_key(UniValue::VOBJ);
     335         [ #  # ]:           0 :             ScriptToUniv(coin.out.scriptPubKey, /*out=*/script_pub_key, /*include_hex=*/true, /*include_address=*/true);
     336   [ #  #  #  # ]:           0 :             prevout.pushKV("scriptPubKey", std::move(script_pub_key));
     337                 :             : 
     338         [ #  # ]:           0 :             tx_prevouts.push_back(std::move(prevout));
     339                 :           0 :         }
     340         [ #  # ]:           0 :         result.push_back(std::move(tx_prevouts));
     341                 :           0 :     }
     342                 :           0 : }
     343                 :             : 
     344                 :           0 : static bool rest_spent_txouts(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     345                 :             : {
     346         [ #  # ]:           0 :     if (!CheckWarmup(req)) {
     347                 :             :         return false;
     348                 :             :     }
     349         [ #  # ]:           0 :     std::string param;
     350         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     351   [ #  #  #  # ]:           0 :     std::vector<std::string> path = SplitString(param, '/');
     352                 :             : 
     353         [ #  # ]:           0 :     std::string hashStr;
     354   [ #  #  #  # ]:           0 :     if (path.size() == 1) {
     355                 :             :         // path with query parameter: /rest/spenttxouts/<hash>
     356         [ #  # ]:           0 :         hashStr = path[0];
     357                 :             :     } else {
     358   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/spenttxouts/<hash>.<ext>");
     359                 :             :     }
     360                 :             : 
     361   [ #  #  #  # ]:           0 :     auto hash{uint256::FromHex(hashStr)};
     362         [ #  # ]:           0 :     if (!hash) {
     363   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
     364                 :             :     }
     365                 :             : 
     366         [ #  # ]:           0 :     ChainstateManager* chainman = GetChainman(context, req);
     367         [ #  # ]:           0 :     if (!chainman) {
     368                 :             :         return false;
     369                 :             :     }
     370                 :             : 
     371   [ #  #  #  #  :           0 :     const CBlockIndex* pblockindex = WITH_LOCK(cs_main, return chainman->m_blockman.LookupBlockIndex(*hash));
                   #  # ]
     372         [ #  # ]:           0 :     if (!pblockindex) {
     373   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
     374                 :             :     }
     375                 :             : 
     376                 :           0 :     CBlockUndo block_undo;
     377         [ #  # ]:           0 :     if (pblockindex->nHeight > 0) {
     378                 :             :         // Blocks that were never connected or have been pruned have no undo data.
     379   [ #  #  #  # ]:           0 :         const bool have_undo{WITH_LOCK(cs_main, return (pblockindex->nStatus & BLOCK_HAVE_UNDO) != 0)};
     380   [ #  #  #  #  :           0 :         if (!have_undo || !chainman->m_blockman.ReadBlockUndo(block_undo, *pblockindex)) {
                   #  # ]
     381   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " undo not available");
     382                 :             :         }
     383                 :             :     }
     384                 :             : 
     385   [ #  #  #  # ]:           0 :     switch (rf) {
     386                 :           0 :     case RESTResponseFormat::BINARY: {
     387                 :           0 :         DataStream ssSpentResponse{};
     388         [ #  # ]:           0 :         SerializeBlockUndo(ssSpentResponse, block_undo);
     389   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     390   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     391   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssSpentResponse);
     392                 :           0 :         return true;
     393                 :           0 :     }
     394                 :             : 
     395                 :           0 :     case RESTResponseFormat::HEX: {
     396                 :           0 :         DataStream ssSpentResponse{};
     397         [ #  # ]:           0 :         SerializeBlockUndo(ssSpentResponse, block_undo);
     398   [ #  #  #  # ]:           0 :         const std::string strHex{HexStr(ssSpentResponse) + "\n"};
     399   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     400   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     401   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     402                 :           0 :         return true;
     403                 :           0 :     }
     404                 :             : 
     405                 :           0 :     case RESTResponseFormat::JSON: {
     406                 :           0 :         UniValue result(UniValue::VARR);
     407         [ #  # ]:           0 :         BlockUndoToJSON(block_undo, result);
     408         [ #  # ]:           0 :         std::string strJSON = result.write() + "\n";
     409   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     410   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     411   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     412                 :           0 :         return true;
     413                 :           0 :     }
     414                 :             : 
     415                 :           0 :     default: {
     416   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     417                 :             :     }
     418                 :             :     }
     419                 :           0 : }
     420                 :             : 
     421                 :             : /**
     422                 :             :  * This handler is used by multiple HTTP endpoints:
     423                 :             :  * - `/block/` via `rest_block_extended()`
     424                 :             :  * - `/block/notxdetails/` via `rest_block_notxdetails()`
     425                 :             :  * - `/blockpart/` via `rest_block_part()` (doesn't support JSON response, so `tx_verbosity` is unset)
     426                 :             :  */
     427                 :           0 : static bool rest_block(const std::any& context,
     428                 :             :                        HTTPRequest* req,
     429                 :             :                        const std::string& uri_part,
     430                 :             :                        std::optional<TxVerbosity> tx_verbosity,
     431                 :             :                        std::optional<std::pair<size_t, size_t>> block_part = std::nullopt)
     432                 :             : {
     433         [ #  # ]:           0 :     if (!CheckWarmup(req))
     434                 :             :         return false;
     435         [ #  # ]:           0 :     std::string hashStr;
     436         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part);
     437                 :             : 
     438   [ #  #  #  # ]:           0 :     auto hash{uint256::FromHex(hashStr)};
     439         [ #  # ]:           0 :     if (!hash) {
     440   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
     441                 :             :     }
     442                 :             : 
     443                 :           0 :     FlatFilePos pos{};
     444                 :           0 :     const CBlockIndex* pblockindex = nullptr;
     445                 :           0 :     const CBlockIndex* tip = nullptr;
     446         [ #  # ]:           0 :     ChainstateManager* maybe_chainman = GetChainman(context, req);
     447         [ #  # ]:           0 :     if (!maybe_chainman) return false;
     448                 :           0 :     ChainstateManager& chainman = *maybe_chainman;
     449                 :           0 :     {
     450         [ #  # ]:           0 :         LOCK(cs_main);
     451   [ #  #  #  # ]:           0 :         tip = chainman.ActiveChain().Tip();
     452         [ #  # ]:           0 :         pblockindex = chainman.m_blockman.LookupBlockIndex(*hash);
     453         [ #  # ]:           0 :         if (!pblockindex) {
     454   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
     455                 :             :         }
     456         [ #  # ]:           0 :         if (!(pblockindex->nStatus & BLOCK_HAVE_DATA)) {
     457   [ #  #  #  # ]:           0 :             if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
     458   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
     459                 :             :             }
     460   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (not fully downloaded)");
     461                 :             :         }
     462         [ #  # ]:           0 :         pos = pblockindex->GetBlockPos();
     463                 :           0 :     }
     464                 :             : 
     465         [ #  # ]:           0 :     const auto block_data{chainman.m_blockman.ReadRawBlock(pos, block_part)};
     466         [ #  # ]:           0 :     if (!block_data) {
     467      [ #  #  # ]:           0 :         switch (block_data.error()) {
     468   [ #  #  #  # ]:           0 :         case node::ReadRawError::IO: return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "I/O error reading " + hashStr);
     469                 :           0 :         case node::ReadRawError::BadPartRange:
     470         [ #  # ]:           0 :             assert(block_part);
     471   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Bad block part offset/size %d/%d for %s", block_part->first, block_part->second, hashStr));
     472                 :             :         } // no default case, so the compiler can warn about missing cases
     473                 :           0 :         AssertUnreachable();
     474                 :             :     }
     475                 :             : 
     476   [ #  #  #  # ]:           0 :     switch (rf) {
     477                 :           0 :     case RESTResponseFormat::BINARY: {
     478   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     479   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     480   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, *block_data);
     481                 :             :         return true;
     482                 :             :     }
     483                 :             : 
     484                 :           0 :     case RESTResponseFormat::HEX: {
     485   [ #  #  #  # ]:           0 :         const std::string strHex{HexStr(*block_data) + "\n"};
     486   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     487   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     488   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     489                 :           0 :         return true;
     490                 :           0 :     }
     491                 :             : 
     492                 :           0 :     case RESTResponseFormat::JSON: {
     493         [ #  # ]:           0 :         if (tx_verbosity) {
     494                 :           0 :             CBlock block{};
     495   [ #  #  #  # ]:           0 :             SpanReader{*block_data} >> TX_WITH_WITNESS(block);
     496         [ #  # ]:           0 :             UniValue objBlock = blockToJSON(chainman.m_blockman, block, *tip, *pblockindex, *tx_verbosity, chainman.GetConsensus().powLimit);
     497         [ #  # ]:           0 :             std::string strJSON = objBlock.write() + "\n";
     498   [ #  #  #  #  :           0 :             req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     499   [ #  #  #  #  :           0 :             req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     500   [ #  #  #  # ]:           0 :             req->WriteReply(HTTP_OK, strJSON);
     501                 :           0 :             return true;
     502                 :           0 :         }
     503   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "JSON output is not supported for this request type");
     504                 :             :     }
     505                 :             : 
     506                 :           0 :     default: {
     507   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     508                 :             :     }
     509                 :             :     }
     510                 :           0 : }
     511                 :             : 
     512                 :           0 : static bool rest_block_extended(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     513                 :             : {
     514                 :           0 :     return rest_block(context, req, uri_part, TxVerbosity::SHOW_DETAILS_AND_PREVOUT);
     515                 :             : }
     516                 :             : 
     517                 :           0 : static bool rest_block_notxdetails(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     518                 :             : {
     519                 :           0 :     return rest_block(context, req, uri_part, TxVerbosity::SHOW_TXID);
     520                 :             : }
     521                 :             : 
     522                 :           0 : static bool rest_block_part(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     523                 :             : {
     524                 :           0 :     try {
     525   [ #  #  #  #  :           0 :         if (const auto opt_offset{ToIntegral<size_t>(req->GetQueryParameter("offset").value_or(""))}) {
                   #  # ]
     526   [ #  #  #  #  :           0 :             if (const auto opt_size{ToIntegral<size_t>(req->GetQueryParameter("size").value_or(""))}) {
                   #  # ]
     527         [ #  # ]:           0 :                 return rest_block(context, req, uri_part,
     528                 :             :                                   /*tx_verbosity=*/std::nullopt,
     529         [ #  # ]:           0 :                                   /*block_part=*/{{*opt_offset, *opt_size}});
     530                 :             :             } else {
     531   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Block part size missing or invalid");
     532                 :             :             }
     533                 :             :         } else {
     534   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, "Block part offset missing or invalid");
     535                 :             :         }
     536         [ -  - ]:           0 :     } catch (const std::runtime_error& e) {
     537   [ -  -  -  - ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, e.what());
     538                 :           0 :     }
     539                 :             : }
     540                 :             : 
     541                 :           0 : static bool rest_filter_header(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     542                 :             : {
     543         [ #  # ]:           0 :     if (!CheckWarmup(req)) return false;
     544                 :             : 
     545         [ #  # ]:           0 :     std::string param;
     546         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     547                 :             : 
     548   [ #  #  #  # ]:           0 :     std::vector<std::string> uri_parts = SplitString(param, '/');
     549         [ #  # ]:           0 :     std::string raw_count;
     550                 :           0 :     std::string raw_blockhash;
     551   [ #  #  #  # ]:           0 :     if (uri_parts.size() == 3) {
     552                 :             :         // deprecated path: /rest/blockfilterheaders/<filtertype>/<count>/<blockhash>
     553         [ #  # ]:           0 :         raw_blockhash = uri_parts[2];
     554         [ #  # ]:           0 :         raw_count = uri_parts[1];
     555         [ #  # ]:           0 :     } else if (uri_parts.size() == 2) {
     556                 :             :         // new path with query parameter: /rest/blockfilterheaders/<filtertype>/<blockhash>?count=<count>
     557         [ #  # ]:           0 :         raw_blockhash = uri_parts[1];
     558                 :           0 :         try {
     559   [ #  #  #  # ]:           0 :             raw_count = req->GetQueryParameter("count").value_or("5");
     560         [ -  - ]:           0 :         } catch (const std::runtime_error& e) {
     561   [ -  -  -  - ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, e.what());
     562                 :           0 :         }
     563                 :             :     } else {
     564   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilterheaders/<filtertype>/<blockhash>.<ext>?count=<count>");
     565                 :             :     }
     566                 :             : 
     567         [ #  # ]:           0 :     const auto parsed_count{ToIntegral<size_t>(raw_count)};
     568   [ #  #  #  #  :           0 :     if (!parsed_count.has_value() || *parsed_count < 1 || *parsed_count > MAX_REST_HEADERS_RESULTS) {
                   #  # ]
     569   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count));
     570                 :             :     }
     571                 :             : 
     572   [ #  #  #  # ]:           0 :     auto block_hash{uint256::FromHex(raw_blockhash)};
     573         [ #  # ]:           0 :     if (!block_hash) {
     574   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + raw_blockhash);
     575                 :             :     }
     576                 :             : 
     577                 :           0 :     BlockFilterType filtertype;
     578   [ #  #  #  #  :           0 :     if (!BlockFilterTypeByName(uri_parts[0], filtertype)) {
                   #  # ]
     579   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
     580                 :             :     }
     581                 :             : 
     582         [ #  # ]:           0 :     NodeContext* node = GetNodeContext(context, req);
     583         [ #  # ]:           0 :     if (!node) return false;
     584         [ #  # ]:           0 :     BlockFilterIndex* index = GetBlockFilterIndex(*node, filtertype);
     585         [ #  # ]:           0 :     if (!index) {
     586   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
     587                 :             :     }
     588                 :             : 
     589                 :           0 :     std::vector<const CBlockIndex*> headers;
     590         [ #  # ]:           0 :     headers.reserve(*parsed_count);
     591                 :           0 :     {
     592         [ #  # ]:           0 :         ChainstateManager* maybe_chainman = GetChainman(context, req);
     593         [ #  # ]:           0 :         if (!maybe_chainman) return false;
     594                 :           0 :         ChainstateManager& chainman = *maybe_chainman;
     595         [ #  # ]:           0 :         LOCK(cs_main);
     596         [ #  # ]:           0 :         CChain& active_chain = chainman.ActiveChain();
     597         [ #  # ]:           0 :         const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*block_hash)};
     598   [ #  #  #  # ]:           0 :         while (pindex != nullptr && active_chain.Contains(*pindex)) {
     599         [ #  # ]:           0 :             headers.push_back(pindex);
     600   [ #  #  #  # ]:           0 :             if (headers.size() == *parsed_count)
     601                 :             :                 break;
     602                 :           0 :             pindex = active_chain.Next(*pindex);
     603                 :             :         }
     604                 :           0 :     }
     605                 :             : 
     606         [ #  # ]:           0 :     bool index_ready = index->BlockUntilSyncedToCurrentChain();
     607                 :             : 
     608                 :           0 :     std::vector<uint256> filter_headers;
     609         [ #  # ]:           0 :     filter_headers.reserve(*parsed_count);
     610         [ #  # ]:           0 :     for (const CBlockIndex* pindex : headers) {
     611                 :           0 :         uint256 filter_header;
     612   [ #  #  #  # ]:           0 :         if (!index->LookupFilterHeader(pindex, filter_header)) {
     613         [ #  # ]:           0 :             std::string errmsg = "Filter not found.";
     614                 :             : 
     615         [ #  # ]:           0 :             if (!index_ready) {
     616         [ #  # ]:           0 :                 errmsg += " Block filters are still in the process of being indexed.";
     617                 :             :             } else {
     618         [ #  # ]:           0 :                 errmsg += " This error is unexpected and indicates index corruption.";
     619                 :             :             }
     620                 :             : 
     621   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_NOT_FOUND, errmsg);
     622                 :           0 :         }
     623         [ #  # ]:           0 :         filter_headers.push_back(filter_header);
     624                 :             :     }
     625                 :             : 
     626   [ #  #  #  # ]:           0 :     switch (rf) {
     627                 :           0 :     case RESTResponseFormat::BINARY: {
     628                 :           0 :         DataStream ssHeader{};
     629         [ #  # ]:           0 :         for (const uint256& header : filter_headers) {
     630         [ #  # ]:           0 :             ssHeader << header;
     631                 :             :         }
     632                 :             : 
     633                 :             :         // Do not cache because chain extensions and reorgs can affect the response.
     634   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     635   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     636   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssHeader);
     637                 :           0 :         return true;
     638                 :           0 :     }
     639                 :           0 :     case RESTResponseFormat::HEX: {
     640                 :           0 :         DataStream ssHeader{};
     641         [ #  # ]:           0 :         for (const uint256& header : filter_headers) {
     642         [ #  # ]:           0 :             ssHeader << header;
     643                 :             :         }
     644                 :             : 
     645   [ #  #  #  # ]:           0 :         std::string strHex = HexStr(ssHeader) + "\n";
     646   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     647   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     648   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     649                 :           0 :         return true;
     650                 :           0 :     }
     651                 :           0 :     case RESTResponseFormat::JSON: {
     652                 :           0 :         UniValue jsonHeaders(UniValue::VARR);
     653         [ #  # ]:           0 :         for (const uint256& header : filter_headers) {
     654   [ #  #  #  #  :           0 :             jsonHeaders.push_back(header.GetHex());
                   #  # ]
     655                 :             :         }
     656                 :             : 
     657         [ #  # ]:           0 :         std::string strJSON = jsonHeaders.write() + "\n";
     658   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     659   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     660   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     661                 :           0 :         return true;
     662                 :           0 :     }
     663                 :           0 :     default: {
     664   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     665                 :             :     }
     666                 :             :     }
     667                 :           0 : }
     668                 :             : 
     669                 :           0 : static bool rest_block_filter(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     670                 :             : {
     671         [ #  # ]:           0 :     if (!CheckWarmup(req)) return false;
     672                 :             : 
     673         [ #  # ]:           0 :     std::string param;
     674         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     675                 :             : 
     676                 :             :     // request is sent over URI scheme /rest/blockfilter/filtertype/blockhash
     677   [ #  #  #  # ]:           0 :     std::vector<std::string> uri_parts = SplitString(param, '/');
     678   [ #  #  #  # ]:           0 :     if (uri_parts.size() != 2) {
     679   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilter/<filtertype>/<blockhash>");
     680                 :             :     }
     681                 :             : 
     682   [ #  #  #  # ]:           0 :     auto block_hash{uint256::FromHex(uri_parts[1])};
     683         [ #  # ]:           0 :     if (!block_hash) {
     684   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + uri_parts[1]);
     685                 :             :     }
     686                 :             : 
     687                 :           0 :     BlockFilterType filtertype;
     688   [ #  #  #  #  :           0 :     if (!BlockFilterTypeByName(uri_parts[0], filtertype)) {
                   #  # ]
     689   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
     690                 :             :     }
     691                 :             : 
     692         [ #  # ]:           0 :     NodeContext* node = GetNodeContext(context, req);
     693         [ #  # ]:           0 :     if (!node) return false;
     694         [ #  # ]:           0 :     BlockFilterIndex* index = GetBlockFilterIndex(*node, filtertype);
     695         [ #  # ]:           0 :     if (!index) {
     696   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
     697                 :             :     }
     698                 :             : 
     699                 :           0 :     const CBlockIndex* block_index;
     700                 :           0 :     bool block_was_connected;
     701                 :           0 :     {
     702         [ #  # ]:           0 :         ChainstateManager* maybe_chainman = GetChainman(context, req);
     703         [ #  # ]:           0 :         if (!maybe_chainman) return false;
     704                 :           0 :         ChainstateManager& chainman = *maybe_chainman;
     705         [ #  # ]:           0 :         LOCK(cs_main);
     706         [ #  # ]:           0 :         block_index = chainman.m_blockman.LookupBlockIndex(*block_hash);
     707         [ #  # ]:           0 :         if (!block_index) {
     708   [ #  #  #  #  :           0 :             return RESTERR(req, HTTP_NOT_FOUND, uri_parts[1] + " not found");
                   #  # ]
     709                 :             :         }
     710   [ #  #  #  # ]:           0 :         block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
     711                 :           0 :     }
     712                 :             : 
     713         [ #  # ]:           0 :     bool index_ready = index->BlockUntilSyncedToCurrentChain();
     714                 :             : 
     715         [ #  # ]:           0 :     BlockFilter filter;
     716   [ #  #  #  # ]:           0 :     if (!index->LookupFilter(block_index, filter)) {
     717         [ #  # ]:           0 :         std::string errmsg = "Filter not found.";
     718                 :             : 
     719         [ #  # ]:           0 :         if (!block_was_connected) {
     720         [ #  # ]:           0 :             errmsg += " Block was not connected to active chain.";
     721         [ #  # ]:           0 :         } else if (!index_ready) {
     722         [ #  # ]:           0 :             errmsg += " Block filters are still in the process of being indexed.";
     723                 :             :         } else {
     724         [ #  # ]:           0 :             errmsg += " This error is unexpected and indicates index corruption.";
     725                 :             :         }
     726                 :             : 
     727   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, errmsg);
     728                 :           0 :     }
     729                 :             : 
     730   [ #  #  #  # ]:           0 :     switch (rf) {
     731                 :           0 :     case RESTResponseFormat::BINARY: {
     732                 :           0 :         DataStream ssResp{};
     733         [ #  # ]:           0 :         ssResp << filter;
     734                 :             : 
     735   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     736   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     737   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssResp);
     738                 :           0 :         return true;
     739                 :           0 :     }
     740                 :           0 :     case RESTResponseFormat::HEX: {
     741                 :           0 :         DataStream ssResp{};
     742         [ #  # ]:           0 :         ssResp << filter;
     743                 :             : 
     744   [ #  #  #  # ]:           0 :         std::string strHex = HexStr(ssResp) + "\n";
     745   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     746   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     747   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     748                 :           0 :         return true;
     749                 :           0 :     }
     750                 :           0 :     case RESTResponseFormat::JSON: {
     751                 :           0 :         UniValue ret(UniValue::VOBJ);
     752   [ #  #  #  #  :           0 :         ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
          #  #  #  #  #  
                      # ]
     753         [ #  # ]:           0 :         std::string strJSON = ret.write() + "\n";
     754   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
                   #  # ]
     755   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     756   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     757                 :           0 :         return true;
     758                 :           0 :     }
     759                 :           0 :     default: {
     760   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     761                 :             :     }
     762                 :             :     }
     763                 :           0 : }
     764                 :             : 
     765                 :             : // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
     766                 :             : RPCMethod getblockchaininfo();
     767                 :             : 
     768                 :           0 : static bool rest_chaininfo(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     769                 :             : {
     770         [ #  # ]:           0 :     if (!CheckWarmup(req))
     771                 :             :         return false;
     772         [ #  # ]:           0 :     std::string param;
     773         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     774                 :             : 
     775         [ #  # ]:           0 :     switch (rf) {
     776                 :           0 :     case RESTResponseFormat::JSON: {
     777                 :           0 :         JSONRPCRequest jsonRequest;
     778         [ #  # ]:           0 :         jsonRequest.context = context;
     779                 :           0 :         jsonRequest.params = UniValue(UniValue::VARR);
     780   [ #  #  #  # ]:           0 :         UniValue chainInfoObject = getblockchaininfo().HandleRequest(jsonRequest);
     781         [ #  # ]:           0 :         std::string strJSON = chainInfoObject.write() + "\n";
     782   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     783   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     784   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     785                 :           0 :         return true;
     786                 :           0 :     }
     787                 :           0 :     default: {
     788   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
     789                 :             :     }
     790                 :             :     }
     791                 :           0 : }
     792                 :             : 
     793                 :             : 
     794                 :             : RPCMethod getdeploymentinfo();
     795                 :             : 
     796                 :           0 : static bool rest_deploymentinfo(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
     797                 :             : {
     798         [ #  # ]:           0 :     if (!CheckWarmup(req)) return false;
     799                 :             : 
     800         [ #  # ]:           0 :     std::string hash_str;
     801         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(hash_str, str_uri_part);
     802         [ #  # ]:           0 :     const bool current_tip{hash_str.empty()};
     803                 :             : 
     804         [ #  # ]:           0 :     switch (rf) {
     805                 :           0 :     case RESTResponseFormat::JSON: {
     806                 :           0 :         JSONRPCRequest jsonRequest;
     807         [ #  # ]:           0 :         jsonRequest.context = context;
     808                 :           0 :         jsonRequest.params = UniValue(UniValue::VARR);
     809                 :             : 
     810         [ #  # ]:           0 :         if (!current_tip) {
     811   [ #  #  #  # ]:           0 :             auto hash{uint256::FromHex(hash_str)};
     812         [ #  # ]:           0 :             if (!hash) {
     813   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hash_str);
     814                 :             :             }
     815                 :             : 
     816         [ #  # ]:           0 :             const ChainstateManager* chainman = GetChainman(context, req);
     817         [ #  # ]:           0 :             if (!chainman) return false;
     818   [ #  #  #  #  :           0 :             if (!WITH_LOCK(::cs_main, return chainman->m_blockman.LookupBlockIndex(*hash))) {
             #  #  #  # ]
     819   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Block not found");
     820                 :             :             }
     821                 :             : 
     822   [ #  #  #  # ]:           0 :             jsonRequest.params.push_back(hash_str);
     823                 :             :         }
     824                 :             : 
     825   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", current_tip ? REST_CACHE_NO_STORE : REST_CACHE_IMMUTABLE);
                   #  # ]
     826   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     827   [ #  #  #  #  :           0 :         req->WriteReply(HTTP_OK, getdeploymentinfo().HandleRequest(jsonRequest).write() + "\n");
          #  #  #  #  #  
                      # ]
     828                 :           0 :         return true;
     829                 :           0 :     }
     830                 :           0 :     default: {
     831   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
     832                 :             :     }
     833                 :             :     }
     834                 :             : 
     835                 :           0 : }
     836                 :             : 
     837                 :           0 : static bool rest_mempool(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
     838                 :             : {
     839         [ #  # ]:           0 :     if (!CheckWarmup(req))
     840                 :             :         return false;
     841                 :             : 
     842         [ #  # ]:           0 :     std::string param;
     843         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, str_uri_part);
     844   [ #  #  #  # ]:           0 :     if (param != "contents" && param != "info") {
     845   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/mempool/<info|contents>.json");
     846                 :             :     }
     847                 :             : 
     848         [ #  # ]:           0 :     const CTxMemPool* mempool = GetMemPool(context, req);
     849         [ #  # ]:           0 :     if (!mempool) return false;
     850                 :             : 
     851         [ #  # ]:           0 :     switch (rf) {
     852                 :           0 :     case RESTResponseFormat::JSON: {
     853         [ #  # ]:           0 :         std::string str_json;
     854         [ #  # ]:           0 :         if (param == "contents") {
     855         [ #  # ]:           0 :             std::string raw_verbose;
     856                 :           0 :             try {
     857   [ #  #  #  # ]:           0 :                 raw_verbose = req->GetQueryParameter("verbose").value_or("true");
     858         [ -  - ]:           0 :             } catch (const std::runtime_error& e) {
     859   [ -  -  -  - ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
     860                 :           0 :             }
     861   [ #  #  #  # ]:           0 :             if (raw_verbose != "true" && raw_verbose != "false") {
     862   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "The \"verbose\" query parameter must be either \"true\" or \"false\".");
     863                 :             :             }
     864         [ #  # ]:           0 :             std::string raw_mempool_sequence;
     865                 :           0 :             try {
     866   [ #  #  #  # ]:           0 :                 raw_mempool_sequence = req->GetQueryParameter("mempool_sequence").value_or("false");
     867         [ -  - ]:           0 :             } catch (const std::runtime_error& e) {
     868   [ -  -  -  - ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
     869                 :           0 :             }
     870   [ #  #  #  # ]:           0 :             if (raw_mempool_sequence != "true" && raw_mempool_sequence != "false") {
     871   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "The \"mempool_sequence\" query parameter must be either \"true\" or \"false\".");
     872                 :             :             }
     873                 :           0 :             const bool verbose{raw_verbose == "true"};
     874                 :           0 :             const bool mempool_sequence{raw_mempool_sequence == "true"};
     875         [ #  # ]:           0 :             if (verbose && mempool_sequence) {
     876   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Verbose results cannot contain mempool sequence values. (hint: set \"verbose=false\")");
     877                 :             :             }
     878   [ #  #  #  # ]:           0 :             str_json = MempoolToJSON(*mempool, verbose, mempool_sequence).write() + "\n";
     879                 :           0 :         } else {
     880   [ #  #  #  # ]:           0 :             str_json = MempoolInfoToJSON(*mempool).write() + "\n";
     881                 :             :         }
     882                 :             : 
     883   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     884   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     885   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, str_json);
     886                 :             :         return true;
     887                 :           0 :     }
     888                 :           0 :     default: {
     889   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
     890                 :             :     }
     891                 :             :     }
     892                 :           0 : }
     893                 :             : 
     894                 :           0 : static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     895                 :             : {
     896         [ #  # ]:           0 :     if (!CheckWarmup(req))
     897                 :             :         return false;
     898         [ #  # ]:           0 :     std::string hashStr;
     899         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part);
     900                 :             : 
     901   [ #  #  #  # ]:           0 :     auto hash{Txid::FromHex(hashStr)};
     902         [ #  # ]:           0 :     if (!hash) {
     903   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
     904                 :             :     }
     905                 :             : 
     906         [ #  # ]:           0 :     const NodeContext* const node = GetNodeContext(context, req);
     907         [ #  # ]:           0 :     if (!node) return false;
     908         [ #  # ]:           0 :     if (node->txindex) {
     909         [ #  # ]:           0 :         node->txindex->BlockUntilSyncedToCurrentChain();
     910                 :             :     }
     911                 :           0 :     uint256 hashBlock = uint256();
     912         [ #  # ]:           0 :     const CTransactionRef tx{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), node->txindex.get(), *hash,  node->chainman->m_blockman, hashBlock)};
     913         [ #  # ]:           0 :     if (!tx) {
     914   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
     915                 :             :     }
     916   [ #  #  #  # ]:           0 :     switch (rf) {
     917                 :           0 :     case RESTResponseFormat::BINARY: {
     918                 :           0 :         DataStream ssTx;
     919         [ #  # ]:           0 :         ssTx << TX_WITH_WITNESS(tx);
     920                 :             : 
     921   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     922   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
     923   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssTx);
     924                 :           0 :         return true;
     925                 :           0 :     }
     926                 :             : 
     927                 :           0 :     case RESTResponseFormat::HEX: {
     928                 :           0 :         DataStream ssTx;
     929         [ #  # ]:           0 :         ssTx << TX_WITH_WITNESS(tx);
     930                 :             : 
     931   [ #  #  #  # ]:           0 :         std::string strHex = HexStr(ssTx) + "\n";
     932   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     933   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
     934   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
     935                 :           0 :         return true;
     936                 :           0 :     }
     937                 :             : 
     938                 :           0 :     case RESTResponseFormat::JSON: {
     939                 :           0 :         UniValue objTx(UniValue::VOBJ);
     940         [ #  # ]:           0 :         TxToUniv(*tx, /*block_hash=*/hashBlock, /*entry=*/ objTx);
     941         [ #  # ]:           0 :         std::string strJSON = objTx.write() + "\n";
     942   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
     943   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
     944   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
     945                 :           0 :         return true;
     946                 :           0 :     }
     947                 :             : 
     948                 :           0 :     default: {
     949   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
     950                 :             :     }
     951                 :             :     }
     952                 :           0 : }
     953                 :             : 
     954                 :           0 : static bool rest_getutxos(const std::any& context, HTTPRequest* req, const std::string& uri_part)
     955                 :             : {
     956         [ #  # ]:           0 :     if (!CheckWarmup(req))
     957                 :             :         return false;
     958         [ #  # ]:           0 :     std::string param;
     959         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
     960                 :             : 
     961                 :           0 :     std::vector<std::string> uriParts;
     962   [ #  #  #  # ]:           0 :     if (param.length() > 1)
     963                 :             :     {
     964         [ #  # ]:           0 :         std::string strUriParams = param.substr(1);
     965   [ #  #  #  # ]:           0 :         uriParts = SplitString(strUriParams, '/');
     966                 :           0 :     }
     967                 :             : 
     968                 :             :     // throw exception in case of an empty request
     969         [ #  # ]:           0 :     std::string strRequestMutable = req->ReadBody();
     970   [ #  #  #  #  :           0 :     if (strRequestMutable.length() == 0 && uriParts.size() == 0)
                   #  # ]
     971   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
     972                 :             : 
     973                 :           0 :     bool fInputParsed = false;
     974                 :           0 :     bool fCheckMemPool = false;
     975                 :           0 :     std::vector<COutPoint> vOutPoints;
     976                 :             : 
     977                 :             :     // parse/deserialize input
     978                 :             :     // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
     979                 :             : 
     980   [ #  #  #  # ]:           0 :     if (uriParts.size() > 0)
     981                 :             :     {
     982                 :             :         //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
     983         [ #  # ]:           0 :         if (uriParts[0] == "checkmempool") fCheckMemPool = true;
     984                 :             : 
     985   [ #  #  #  #  :           0 :         for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
                   #  # ]
     986                 :             :         {
     987   [ #  #  #  # ]:           0 :             const auto txid_out{util::Split<std::string_view>(uriParts[i], '-')};
     988   [ #  #  #  # ]:           0 :             if (txid_out.size() != 2) {
     989   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
     990                 :             :             }
     991   [ #  #  #  # ]:           0 :             auto txid{Txid::FromHex(txid_out.at(0))};
     992         [ #  # ]:           0 :             auto output{ToIntegral<uint32_t>(txid_out.at(1))};
     993                 :             : 
     994   [ #  #  #  # ]:           0 :             if (!txid || !output) {
     995   [ #  #  #  # ]:           0 :                 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
     996                 :             :             }
     997                 :             : 
     998         [ #  # ]:           0 :             vOutPoints.emplace_back(*txid, *output);
     999                 :           0 :         }
    1000                 :             : 
    1001   [ #  #  #  # ]:           0 :         if (vOutPoints.size() > 0)
    1002                 :             :             fInputParsed = true;
    1003                 :             :         else
    1004   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
    1005                 :             :     }
    1006                 :             : 
    1007   [ #  #  #  # ]:           0 :     switch (rf) {
    1008                 :           0 :     case RESTResponseFormat::HEX: {
    1009                 :             :         // convert hex to bin, continue then with bin part
    1010   [ #  #  #  # ]:           0 :         std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
    1011         [ #  # ]:           0 :         strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
    1012                 :           0 :         [[fallthrough]];
    1013                 :           0 :     }
    1014                 :             : 
    1015                 :           0 :     case RESTResponseFormat::BINARY: {
    1016                 :           0 :         try {
    1017                 :             :             //deserialize only if user sent a request
    1018   [ #  #  #  # ]:           0 :             if (strRequestMutable.size() > 0)
    1019                 :             :             {
    1020         [ #  # ]:           0 :                 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
    1021   [ #  #  #  # ]:           0 :                     return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
    1022                 :             : 
    1023                 :           0 :                 DataStream oss{};
    1024         [ #  # ]:           0 :                 oss << strRequestMutable;
    1025         [ #  # ]:           0 :                 oss >> fCheckMemPool;
    1026         [ #  # ]:           0 :                 oss >> vOutPoints;
    1027                 :           0 :             }
    1028         [ -  - ]:           0 :         } catch (const std::ios_base::failure&) {
    1029                 :             :             // abort in case of unreadable binary data
    1030   [ -  -  -  - ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
    1031                 :           0 :         }
    1032                 :             :         break;
    1033                 :             :     }
    1034                 :             : 
    1035                 :           0 :     case RESTResponseFormat::JSON: {
    1036         [ #  # ]:           0 :         if (!fInputParsed)
    1037   [ #  #  #  # ]:           0 :             return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
    1038                 :             :         break;
    1039                 :             :     }
    1040                 :           0 :     default: {
    1041   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
    1042                 :             :     }
    1043                 :             :     }
    1044                 :             : 
    1045                 :             :     // limit max outpoints
    1046   [ #  #  #  # ]:           0 :     if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
    1047   [ #  #  #  # ]:           0 :         return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
    1048                 :             : 
    1049                 :             :     // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
    1050                 :           0 :     std::vector<unsigned char> bitmap;
    1051                 :           0 :     std::vector<CCoin> outs;
    1052         [ #  # ]:           0 :     std::string bitmapStringRepresentation;
    1053                 :           0 :     std::vector<bool> hits;
    1054         [ #  # ]:           0 :     bitmap.resize(CeilDiv(vOutPoints.size(), 8u));
    1055         [ #  # ]:           0 :     ChainstateManager* maybe_chainman = GetChainman(context, req);
    1056         [ #  # ]:           0 :     if (!maybe_chainman) return false;
    1057                 :           0 :     ChainstateManager& chainman = *maybe_chainman;
    1058                 :           0 :     decltype(chainman.ActiveHeight()) active_height;
    1059                 :           0 :     uint256 active_hash;
    1060                 :           0 :     {
    1061                 :           0 :         auto process_utxos = [&vOutPoints, &outs, &hits, &active_height, &active_hash, &chainman](const CCoinsView& view, const CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(chainman.GetMutex()) {
    1062         [ #  # ]:           0 :             for (const COutPoint& vOutPoint : vOutPoints) {
    1063   [ #  #  #  # ]:           0 :                 auto coin = !mempool || !mempool->isSpent(vOutPoint) ? view.GetCoin(vOutPoint) : std::nullopt;
    1064         [ #  # ]:           0 :                 hits.push_back(coin.has_value());
    1065   [ #  #  #  # ]:           0 :                 if (coin) outs.emplace_back(std::move(*coin));
    1066                 :           0 :             }
    1067                 :           0 :             active_height = chainman.ActiveHeight();
    1068                 :           0 :             active_hash = chainman.ActiveTip()->GetBlockHash();
    1069                 :           0 :         };
    1070                 :             : 
    1071         [ #  # ]:           0 :         if (fCheckMemPool) {
    1072         [ #  # ]:           0 :             const CTxMemPool* mempool = GetMemPool(context, req);
    1073         [ #  # ]:           0 :             if (!mempool) return false;
    1074                 :             :             // use db+mempool as cache backend in case user likes to query mempool
    1075   [ #  #  #  # ]:           0 :             LOCK2(cs_main, mempool->cs);
    1076   [ #  #  #  # ]:           0 :             CCoinsViewCache& viewChain = chainman.ActiveChainstate().CoinsTip();
    1077         [ #  # ]:           0 :             CCoinsViewMemPool viewMempool(&viewChain, *mempool);
    1078         [ #  # ]:           0 :             process_utxos(viewMempool, mempool);
    1079   [ #  #  #  # ]:           0 :         } else {
    1080         [ #  # ]:           0 :             LOCK(cs_main);
    1081   [ #  #  #  #  :           0 :             process_utxos(chainman.ActiveChainstate().CoinsTip(), nullptr);
                   #  # ]
    1082                 :           0 :         }
    1083                 :             : 
    1084         [ #  # ]:           0 :         for (size_t i = 0; i < hits.size(); ++i) {
    1085         [ #  # ]:           0 :             const bool hit = hits[i];
    1086   [ #  #  #  # ]:           0 :             bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
    1087                 :           0 :             bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
    1088                 :             :         }
    1089                 :             :     }
    1090                 :             : 
    1091   [ #  #  #  # ]:           0 :     switch (rf) {
    1092                 :           0 :     case RESTResponseFormat::BINARY: {
    1093                 :             :         // serialize data
    1094                 :             :         // use exact same output as mentioned in Bip64
    1095                 :           0 :         DataStream ssGetUTXOResponse{};
    1096   [ #  #  #  #  :           0 :         ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
             #  #  #  # ]
    1097                 :             : 
    1098   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1099   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
    1100   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ssGetUTXOResponse);
    1101                 :           0 :         return true;
    1102                 :           0 :     }
    1103                 :             : 
    1104                 :           0 :     case RESTResponseFormat::HEX: {
    1105                 :           0 :         DataStream ssGetUTXOResponse{};
    1106   [ #  #  #  #  :           0 :         ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
             #  #  #  # ]
    1107   [ #  #  #  # ]:           0 :         std::string strHex = HexStr(ssGetUTXOResponse) + "\n";
    1108                 :             : 
    1109   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1110   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
    1111   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strHex);
    1112                 :           0 :         return true;
    1113                 :           0 :     }
    1114                 :             : 
    1115                 :           0 :     case RESTResponseFormat::JSON: {
    1116                 :           0 :         UniValue objGetUTXOResponse(UniValue::VOBJ);
    1117                 :             : 
    1118                 :             :         // pack in some essentials
    1119                 :             :         // use more or less the same output as mentioned in Bip64
    1120   [ #  #  #  #  :           0 :         objGetUTXOResponse.pushKV("chainHeight", active_height);
                   #  # ]
    1121   [ #  #  #  #  :           0 :         objGetUTXOResponse.pushKV("chaintipHash", active_hash.GetHex());
             #  #  #  # ]
    1122   [ #  #  #  #  :           0 :         objGetUTXOResponse.pushKV("bitmap", bitmapStringRepresentation);
                   #  # ]
    1123                 :             : 
    1124                 :           0 :         UniValue utxos(UniValue::VARR);
    1125         [ #  # ]:           0 :         for (const CCoin& coin : outs) {
    1126                 :           0 :             UniValue utxo(UniValue::VOBJ);
    1127   [ #  #  #  #  :           0 :             utxo.pushKV("height", coin.nHeight);
                   #  # ]
    1128   [ #  #  #  #  :           0 :             utxo.pushKV("value", ValueFromAmount(coin.out.nValue));
                   #  # ]
    1129                 :             : 
    1130                 :             :             // include the script in a json output
    1131                 :           0 :             UniValue o(UniValue::VOBJ);
    1132         [ #  # ]:           0 :             ScriptToUniv(coin.out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
    1133   [ #  #  #  # ]:           0 :             utxo.pushKV("scriptPubKey", std::move(o));
    1134         [ #  # ]:           0 :             utxos.push_back(std::move(utxo));
    1135                 :           0 :         }
    1136   [ #  #  #  # ]:           0 :         objGetUTXOResponse.pushKV("utxos", std::move(utxos));
    1137                 :             : 
    1138                 :             :         // return json string
    1139         [ #  # ]:           0 :         std::string strJSON = objGetUTXOResponse.write() + "\n";
    1140   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1141   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
    1142   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, strJSON);
    1143                 :           0 :         return true;
    1144                 :           0 :     }
    1145                 :           0 :     default: {
    1146   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
    1147                 :             :     }
    1148                 :             :     }
    1149                 :           0 : }
    1150                 :             : 
    1151                 :           0 : static bool rest_blockhash_by_height(const std::any& context, HTTPRequest* req,
    1152                 :             :                        const std::string& str_uri_part)
    1153                 :             : {
    1154         [ #  # ]:           0 :     if (!CheckWarmup(req)) return false;
    1155         [ #  # ]:           0 :     std::string height_str;
    1156         [ #  # ]:           0 :     const RESTResponseFormat rf = ParseDataFormat(height_str, str_uri_part);
    1157                 :             : 
    1158         [ #  # ]:           0 :     const auto blockheight{ToIntegral<int32_t>(height_str)};
    1159   [ #  #  #  # ]:           0 :     if (!blockheight || *blockheight < 0) {
    1160   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid height: " + SanitizeString(height_str, SAFE_CHARS_URI));
             #  #  #  # ]
    1161                 :             :     }
    1162                 :             : 
    1163                 :           0 :     CBlockIndex* pblockindex = nullptr;
    1164                 :           0 :     {
    1165         [ #  # ]:           0 :         ChainstateManager* maybe_chainman = GetChainman(context, req);
    1166         [ #  # ]:           0 :         if (!maybe_chainman) return false;
    1167                 :           0 :         ChainstateManager& chainman = *maybe_chainman;
    1168         [ #  # ]:           0 :         LOCK(cs_main);
    1169         [ #  # ]:           0 :         const CChain& active_chain = chainman.ActiveChain();
    1170   [ #  #  #  # ]:           0 :         if (*blockheight > active_chain.Height()) {
    1171   [ #  #  #  #  :           0 :             return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range");
                   #  # ]
    1172                 :             :         }
    1173         [ #  # ]:           0 :         pblockindex = active_chain[*blockheight];
    1174                 :           0 :     }
    1175   [ #  #  #  # ]:           0 :     switch (rf) {
    1176                 :           0 :     case RESTResponseFormat::BINARY: {
    1177                 :           0 :         DataStream ss_blockhash{};
    1178         [ #  # ]:           0 :         ss_blockhash << pblockindex->GetBlockHash();
    1179                 :             :         // Do not cache because reorgs can change the response.
    1180   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1181   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/octet-stream");
                   #  # ]
    1182   [ #  #  #  # ]:           0 :         req->WriteReply(HTTP_OK, ss_blockhash);
    1183                 :           0 :         return true;
    1184                 :           0 :     }
    1185                 :           0 :     case RESTResponseFormat::HEX: {
    1186   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1187   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "text/plain");
                   #  # ]
    1188   [ #  #  #  #  :           0 :         req->WriteReply(HTTP_OK, pblockindex->GetBlockHash().GetHex() + "\n");
                   #  # ]
    1189                 :           0 :         return true;
    1190                 :             :     }
    1191                 :           0 :     case RESTResponseFormat::JSON: {
    1192   [ #  #  #  #  :           0 :         req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
                   #  # ]
    1193   [ #  #  #  #  :           0 :         req->WriteHeader("Content-Type", "application/json");
                   #  # ]
    1194                 :           0 :         UniValue resp = UniValue(UniValue::VOBJ);
    1195   [ #  #  #  #  :           0 :         resp.pushKV("blockhash", pblockindex->GetBlockHash().GetHex());
             #  #  #  # ]
    1196   [ #  #  #  #  :           0 :         req->WriteReply(HTTP_OK, resp.write() + "\n");
                   #  # ]
    1197                 :           0 :         return true;
    1198                 :           0 :     }
    1199                 :           0 :     default: {
    1200   [ #  #  #  #  :           0 :         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
                   #  # ]
    1201                 :             :     }
    1202                 :             :     }
    1203                 :           0 : }
    1204                 :             : 
    1205                 :             : static const struct {
    1206                 :             :     const char* prefix;
    1207                 :             :     bool (*handler)(const std::any& context, HTTPRequest* req, const std::string& strReq);
    1208                 :             : } uri_prefixes[] = {
    1209                 :             :     {"/rest/tx/", rest_tx},
    1210                 :             :     {"/rest/block/notxdetails/", rest_block_notxdetails},
    1211                 :             :     {"/rest/block/", rest_block_extended},
    1212                 :             :     {"/rest/blockpart/", rest_block_part},
    1213                 :             :     {"/rest/blockfilter/", rest_block_filter},
    1214                 :             :     {"/rest/blockfilterheaders/", rest_filter_header},
    1215                 :             :     {"/rest/chaininfo", rest_chaininfo},
    1216                 :             :     {"/rest/mempool/", rest_mempool},
    1217                 :             :     {"/rest/headers/", rest_headers},
    1218                 :             :     {"/rest/getutxos", rest_getutxos},
    1219                 :             :     {"/rest/deploymentinfo/", rest_deploymentinfo},
    1220                 :             :     {"/rest/deploymentinfo", rest_deploymentinfo},
    1221                 :             :     {"/rest/blockhashbyheight/", rest_blockhash_by_height},
    1222                 :             :     {"/rest/spenttxouts/", rest_spent_txouts},
    1223                 :             : };
    1224                 :             : 
    1225                 :           0 : void StartREST(const std::any& context)
    1226                 :             : {
    1227         [ #  # ]:           0 :     for (const auto& up : uri_prefixes) {
    1228   [ #  #  #  # ]:           0 :         auto handler = [context, up](HTTPRequest* req, const std::string& prefix) { return up.handler(context, req, prefix); };
    1229   [ #  #  #  #  :           0 :         RegisterHTTPHandler(up.prefix, false, handler);
                   #  # ]
    1230                 :           0 :     }
    1231                 :           0 : }
    1232                 :             : 
    1233                 :           0 : void InterruptREST()
    1234                 :             : {
    1235                 :           0 : }
    1236                 :             : 
    1237                 :           0 : void StopREST()
    1238                 :             : {
    1239         [ #  # ]:           0 :     for (const auto& up : uri_prefixes) {
    1240         [ #  # ]:           0 :         UnregisterHTTPHandler(up.prefix, false);
    1241                 :             :     }
    1242                 :           0 : }
        

Generated by: LCOV version 2.5.0-full