rest.cpp raw

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