Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
rest.cpp
Go to the documentation of this file.
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>
17#include <index/txindex.h>
18#include <node/blockstorage.h>
19#include <node/context.h>
20#include <node/transaction.h>
21#include <primitives/block.h>
23#include <rpc/blockchain.h>
24#include <rpc/mempool.h>
25#include <rpc/protocol.h>
26#include <rpc/request.h>
27#include <rpc/server.h>
28#include <rpc/util.h>
29#include <serialize.h>
30#include <streams.h>
31#include <sync.h>
32#include <tinyformat.h>
33#include <txmempool.h>
34#include <uint256.h>
35#include <undo.h>
36#include <univalue.h>
37#include <util/any.h>
38#include <util/check.h>
39#include <util/overflow.h>
40#include <util/strencodings.h>
41#include <util/string.h>
42#include <validation.h>
43
44#include <any>
45#include <cstdint>
46#include <cstring>
47#include <ios>
48#include <memory>
49#include <optional>
50#include <span>
51#include <stdexcept>
52#include <string_view>
53#include <utility>
54#include <vector>
55
59
60static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
61static constexpr unsigned int MAX_REST_HEADERS_RESULTS = 2000;
62
63// Cache-Control values for REST responses.
65static constexpr const char* REST_CACHE_IMMUTABLE = "public, immutable, max-age=86400";
67static constexpr const char* REST_CACHE_NO_STORE = "no-store";
68
69static const struct {
71 const char* name;
72} rf_names[] = {
77};
78
79struct CCoin {
82
83 CCoin() : nHeight(0) {}
84 explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
85
87 {
89 READWRITE(nTxVerDummy, obj.nHeight, obj.out);
90 }
91};
92
93static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
94{
95 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
96 req->WriteHeader("Content-Type", "text/plain");
97 req->WriteReply(status, message + "\r\n");
98 return false;
99}
100
108static NodeContext* GetNodeContext(const std::any& context, HTTPRequest* req)
109{
110 auto node_context = util::AnyPtr<NodeContext>(context);
111 if (!node_context) {
112 RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, STR_INTERNAL_BUG("Node context not found!"));
113 return nullptr;
114 }
115 return node_context;
116}
117
125static CTxMemPool* GetMemPool(const std::any& context, HTTPRequest* req)
126{
127 auto node_context = util::AnyPtr<NodeContext>(context);
128 if (!node_context || !node_context->mempool) {
129 RESTERR(req, HTTP_NOT_FOUND, "Mempool disabled or instance not found");
130 return nullptr;
131 }
132 return node_context->mempool.get();
133}
134
142static ChainstateManager* GetChainman(const std::any& context, HTTPRequest* req)
143{
144 auto node_context = util::AnyPtr<NodeContext>(context);
145 if (!node_context || !node_context->chainman) {
146 RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, STR_INTERNAL_BUG("Chainman disabled or instance not found!"));
147 return nullptr;
148 }
149 return node_context->chainman.get();
150}
151
152RESTResponseFormat ParseDataFormat(std::string& param, const std::string& strReq)
153{
154 // Remove query string (if any, separated with '?') as it should not interfere with
155 // parsing param and data format
156 param = strReq.substr(0, strReq.rfind('?'));
157 const std::string::size_type pos_format{param.rfind('.')};
158
159 // No format string is found
160 if (pos_format == std::string::npos) {
162 }
163
164 // Match format string to available formats
165 const std::string suffix(param, pos_format + 1);
166 for (const auto& rf_name : rf_names) {
167 if (suffix == rf_name.name) {
168 param.erase(pos_format);
169 return rf_name.rf;
170 }
171 }
172
173 // If no suffix is found, return RESTResponseFormat::UNDEF and original string without query string
175}
176
177static std::string AvailableDataFormatsString()
178{
179 std::string formats;
180 for (const auto& rf_name : rf_names) {
181 if (strlen(rf_name.name) > 0) {
182 formats.append(".");
183 formats.append(rf_name.name);
184 formats.append(", ");
185 }
186 }
187
188 if (formats.length() > 0)
189 return formats.substr(0, formats.length() - 2);
190
191 return formats;
192}
193
194static bool CheckWarmup(HTTPRequest* req)
195{
196 std::string statusmessage;
198 return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
199 return true;
200}
201
202static bool rest_headers(const std::any& context,
203 HTTPRequest* req,
204 const std::string& uri_part)
205{
206 if (!CheckWarmup(req))
207 return false;
208 std::string param;
210 std::vector<std::string> path = SplitString(param, '/');
211
212 std::string raw_count;
213 std::string hashStr;
214 if (path.size() == 2) {
215 // deprecated path: /rest/headers/<count>/<hash>
216 hashStr = path[1];
217 raw_count = path[0];
218 } else if (path.size() == 1) {
219 // new path with query parameter: /rest/headers/<hash>?count=<count>
220 hashStr = path[0];
221 try {
222 raw_count = req->GetQueryParameter("count").value_or("5");
223 } catch (const std::runtime_error& e) {
224 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
225 }
226 } else {
227 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/headers/<hash>.<ext>?count=<count>");
228 }
229
232 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));
233 }
234
235 auto hash{uint256::FromHex(hashStr)};
236 if (!hash) {
237 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
238 }
239
240 const CBlockIndex* tip = nullptr;
241 std::vector<const CBlockIndex*> headers;
242 headers.reserve(*parsed_count);
244 if (!maybe_chainman) return false;
246 {
247 LOCK(cs_main);
248 CChain& active_chain = chainman.ActiveChain();
249 tip = active_chain.Tip();
250 const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*hash)};
251 while (pindex != nullptr && active_chain.Contains(*pindex)) {
252 headers.push_back(pindex);
253 if (headers.size() == *parsed_count) {
254 break;
255 }
256 pindex = active_chain.Next(*pindex);
257 }
258 }
259
260 switch (rf) {
263 for (const CBlockIndex *pindex : headers) {
264 ssHeader << pindex->GetBlockHeader();
265 }
266
267 // Do not cache because chain extensions and reorgs can affect the response.
268 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
269 req->WriteHeader("Content-Type", "application/octet-stream");
271 return true;
272 }
273
276 for (const CBlockIndex *pindex : headers) {
277 ssHeader << pindex->GetBlockHeader();
278 }
279
280 std::string strHex = HexStr(ssHeader) + "\n";
281 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
282 req->WriteHeader("Content-Type", "text/plain");
284 return true;
285 }
288 for (const CBlockIndex *pindex : headers) {
289 jsonHeaders.push_back(blockheaderToJSON(*tip, *pindex, chainman.GetConsensus().powLimit));
290 }
291 std::string strJSON = jsonHeaders.write() + "\n";
292 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
293 req->WriteHeader("Content-Type", "application/json");
295 return true;
296 }
297 default: {
298 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
299 }
300 }
301}
302
307{
308 WriteCompactSize(stream, block_undo.vtxundo.size() + 1);
309 WriteCompactSize(stream, 0); // block_undo.vtxundo doesn't contain coinbase tx
310 for (const CTxUndo& tx_undo : block_undo.vtxundo) {
311 WriteCompactSize(stream, tx_undo.vprevout.size());
312 for (const Coin& coin : tx_undo.vprevout) {
313 coin.out.Serialize(stream);
314 }
315 }
316}
317
321static void BlockUndoToJSON(const CBlockUndo& block_undo, UniValue& result)
322{
323 result.push_back({UniValue::VARR}); // block_undo.vtxundo doesn't contain coinbase tx
324 for (const CTxUndo& tx_undo : block_undo.vtxundo) {
326 for (const Coin& coin : tx_undo.vprevout) {
327 UniValue prevout(UniValue::VOBJ);
328 prevout.pushKV("generated", coin.IsCoinBase());
329 prevout.pushKV("height", coin.nHeight);
330 prevout.pushKV("value", ValueFromAmount(coin.out.nValue));
331
333 ScriptToUniv(coin.out.scriptPubKey, /*out=*/script_pub_key, /*include_hex=*/true, /*include_address=*/true);
334 prevout.pushKV("scriptPubKey", std::move(script_pub_key));
335
336 tx_prevouts.push_back(std::move(prevout));
337 }
338 result.push_back(std::move(tx_prevouts));
339 }
340}
341
342static bool rest_spent_txouts(const std::any& context, HTTPRequest* req, const std::string& uri_part)
343{
344 if (!CheckWarmup(req)) {
345 return false;
346 }
347 std::string param;
349 std::vector<std::string> path = SplitString(param, '/');
350
351 std::string hashStr;
352 if (path.size() == 1) {
353 // path with query parameter: /rest/spenttxouts/<hash>
354 hashStr = path[0];
355 } else {
356 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/spenttxouts/<hash>.<ext>");
357 }
358
359 auto hash{uint256::FromHex(hashStr)};
360 if (!hash) {
361 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
362 }
363
364 ChainstateManager* chainman = GetChainman(context, req);
365 if (!chainman) {
366 return false;
367 }
368
369 const CBlockIndex* pblockindex = WITH_LOCK(cs_main, return chainman->m_blockman.LookupBlockIndex(*hash));
370 if (!pblockindex) {
371 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
372 }
373
375 if (pblockindex->nHeight > 0) {
376 // Blocks that were never connected or have been pruned have no undo data.
377 const bool have_undo{WITH_LOCK(cs_main, return (pblockindex->nStatus & BLOCK_HAVE_UNDO) != 0)};
379 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " undo not available");
380 }
381 }
382
383 switch (rf) {
387 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
388 req->WriteHeader("Content-Type", "application/octet-stream");
390 return true;
391 }
392
396 const std::string strHex{HexStr(ssSpentResponse) + "\n"};
397 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
398 req->WriteHeader("Content-Type", "text/plain");
400 return true;
401 }
402
404 UniValue result(UniValue::VARR);
406 std::string strJSON = result.write() + "\n";
407 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
408 req->WriteHeader("Content-Type", "application/json");
410 return true;
411 }
412
413 default: {
414 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
415 }
416 }
417}
418
425static bool rest_block(const std::any& context,
426 HTTPRequest* req,
427 const std::string& uri_part,
428 std::optional<TxVerbosity> tx_verbosity,
429 std::optional<std::pair<size_t, size_t>> block_part = std::nullopt)
430{
431 if (!CheckWarmup(req))
432 return false;
433 std::string hashStr;
435
436 auto hash{uint256::FromHex(hashStr)};
437 if (!hash) {
438 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
439 }
440
441 FlatFilePos pos{};
442 const CBlockIndex* pblockindex = nullptr;
443 const CBlockIndex* tip = nullptr;
445 if (!maybe_chainman) return false;
447 {
448 LOCK(cs_main);
449 tip = chainman.ActiveChain().Tip();
450 pblockindex = chainman.m_blockman.LookupBlockIndex(*hash);
451 if (!pblockindex) {
452 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
453 }
454 if (!(pblockindex->nStatus & BLOCK_HAVE_DATA)) {
455 if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
456 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
457 }
458 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (not fully downloaded)");
459 }
460 pos = pblockindex->GetBlockPos();
461 }
462
463 const auto block_data{chainman.m_blockman.ReadRawBlock(pos, block_part)};
464 if (!block_data) {
465 switch (block_data.error()) {
466 case node::ReadRawError::IO: return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "I/O error reading " + hashStr);
469 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Bad block part offset/size %d/%d for %s", block_part->first, block_part->second, hashStr));
470 } // no default case, so the compiler can warn about missing cases
471 assert(false);
472 }
473
474 switch (rf) {
476 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
477 req->WriteHeader("Content-Type", "application/octet-stream");
479 return true;
480 }
481
483 const std::string strHex{HexStr(*block_data) + "\n"};
484 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
485 req->WriteHeader("Content-Type", "text/plain");
487 return true;
488 }
489
491 if (tx_verbosity) {
492 CBlock block{};
495 std::string strJSON = objBlock.write() + "\n";
496 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
497 req->WriteHeader("Content-Type", "application/json");
499 return true;
500 }
501 return RESTERR(req, HTTP_BAD_REQUEST, "JSON output is not supported for this request type");
502 }
503
504 default: {
505 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
506 }
507 }
508}
509
510static bool rest_block_extended(const std::any& context, HTTPRequest* req, const std::string& uri_part)
511{
513}
514
515static bool rest_block_notxdetails(const std::any& context, HTTPRequest* req, const std::string& uri_part)
516{
518}
519
520static bool rest_block_part(const std::any& context, HTTPRequest* req, const std::string& uri_part)
521{
522 try {
523 if (const auto opt_offset{ToIntegral<size_t>(req->GetQueryParameter("offset").value_or(""))}) {
524 if (const auto opt_size{ToIntegral<size_t>(req->GetQueryParameter("size").value_or(""))}) {
525 return rest_block(context, req, uri_part,
526 /*tx_verbosity=*/std::nullopt,
527 /*block_part=*/{{*opt_offset, *opt_size}});
528 } else {
529 return RESTERR(req, HTTP_BAD_REQUEST, "Block part size missing or invalid");
530 }
531 } else {
532 return RESTERR(req, HTTP_BAD_REQUEST, "Block part offset missing or invalid");
533 }
534 } catch (const std::runtime_error& e) {
535 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
536 }
537}
538
539static bool rest_filter_header(const std::any& context, HTTPRequest* req, const std::string& uri_part)
540{
541 if (!CheckWarmup(req)) return false;
542
543 std::string param;
545
546 std::vector<std::string> uri_parts = SplitString(param, '/');
547 std::string raw_count;
548 std::string raw_blockhash;
549 if (uri_parts.size() == 3) {
550 // deprecated path: /rest/blockfilterheaders/<filtertype>/<count>/<blockhash>
552 raw_count = uri_parts[1];
553 } else if (uri_parts.size() == 2) {
554 // new path with query parameter: /rest/blockfilterheaders/<filtertype>/<blockhash>?count=<count>
556 try {
557 raw_count = req->GetQueryParameter("count").value_or("5");
558 } catch (const std::runtime_error& e) {
559 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
560 }
561 } else {
562 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilterheaders/<filtertype>/<blockhash>.<ext>?count=<count>");
563 }
564
567 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));
568 }
569
570 auto block_hash{uint256::FromHex(raw_blockhash)};
571 if (!block_hash) {
572 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + raw_blockhash);
573 }
574
577 return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
578 }
579
581 if (!index) {
582 return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
583 }
584
585 std::vector<const CBlockIndex*> headers;
586 headers.reserve(*parsed_count);
587 {
589 if (!maybe_chainman) return false;
591 LOCK(cs_main);
592 CChain& active_chain = chainman.ActiveChain();
593 const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*block_hash)};
594 while (pindex != nullptr && active_chain.Contains(*pindex)) {
595 headers.push_back(pindex);
596 if (headers.size() == *parsed_count)
597 break;
598 pindex = active_chain.Next(*pindex);
599 }
600 }
601
602 bool index_ready = index->BlockUntilSyncedToCurrentChain();
603
604 std::vector<uint256> filter_headers;
606 for (const CBlockIndex* pindex : headers) {
608 if (!index->LookupFilterHeader(pindex, filter_header)) {
609 std::string errmsg = "Filter not found.";
610
611 if (!index_ready) {
612 errmsg += " Block filters are still in the process of being indexed.";
613 } else {
614 errmsg += " This error is unexpected and indicates index corruption.";
615 }
616
617 return RESTERR(req, HTTP_NOT_FOUND, errmsg);
618 }
619 filter_headers.push_back(filter_header);
620 }
621
622 switch (rf) {
625 for (const uint256& header : filter_headers) {
626 ssHeader << header;
627 }
628
629 // Do not cache because chain extensions and reorgs can affect the response.
630 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
631 req->WriteHeader("Content-Type", "application/octet-stream");
633 return true;
634 }
637 for (const uint256& header : filter_headers) {
638 ssHeader << header;
639 }
640
641 std::string strHex = HexStr(ssHeader) + "\n";
642 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
643 req->WriteHeader("Content-Type", "text/plain");
645 return true;
646 }
649 for (const uint256& header : filter_headers) {
650 jsonHeaders.push_back(header.GetHex());
651 }
652
653 std::string strJSON = jsonHeaders.write() + "\n";
654 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
655 req->WriteHeader("Content-Type", "application/json");
657 return true;
658 }
659 default: {
660 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
661 }
662 }
663}
664
665static bool rest_block_filter(const std::any& context, HTTPRequest* req, const std::string& uri_part)
666{
667 if (!CheckWarmup(req)) return false;
668
669 std::string param;
671
672 // request is sent over URI scheme /rest/blockfilter/filtertype/blockhash
673 std::vector<std::string> uri_parts = SplitString(param, '/');
674 if (uri_parts.size() != 2) {
675 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilter/<filtertype>/<blockhash>");
676 }
677
678 auto block_hash{uint256::FromHex(uri_parts[1])};
679 if (!block_hash) {
680 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + uri_parts[1]);
681 }
682
685 return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
686 }
687
689 if (!index) {
690 return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
691 }
692
695 {
697 if (!maybe_chainman) return false;
699 LOCK(cs_main);
700 block_index = chainman.m_blockman.LookupBlockIndex(*block_hash);
701 if (!block_index) {
702 return RESTERR(req, HTTP_NOT_FOUND, uri_parts[1] + " not found");
703 }
705 }
706
707 bool index_ready = index->BlockUntilSyncedToCurrentChain();
708
709 BlockFilter filter;
710 if (!index->LookupFilter(block_index, filter)) {
711 std::string errmsg = "Filter not found.";
712
713 if (!block_was_connected) {
714 errmsg += " Block was not connected to active chain.";
715 } else if (!index_ready) {
716 errmsg += " Block filters are still in the process of being indexed.";
717 } else {
718 errmsg += " This error is unexpected and indicates index corruption.";
719 }
720
721 return RESTERR(req, HTTP_NOT_FOUND, errmsg);
722 }
723
724 switch (rf) {
727 ssResp << filter;
728
729 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
730 req->WriteHeader("Content-Type", "application/octet-stream");
732 return true;
733 }
736 ssResp << filter;
737
738 std::string strHex = HexStr(ssResp) + "\n";
739 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
740 req->WriteHeader("Content-Type", "text/plain");
742 return true;
743 }
746 ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
747 std::string strJSON = ret.write() + "\n";
748 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
749 req->WriteHeader("Content-Type", "application/json");
751 return true;
752 }
753 default: {
754 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
755 }
756 }
757}
758
759// A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
761
762static bool rest_chaininfo(const std::any& context, HTTPRequest* req, const std::string& uri_part)
763{
764 if (!CheckWarmup(req))
765 return false;
766 std::string param;
768
769 switch (rf) {
775 std::string strJSON = chainInfoObject.write() + "\n";
776 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
777 req->WriteHeader("Content-Type", "application/json");
779 return true;
780 }
781 default: {
782 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
783 }
784 }
785}
786
787
789
790static bool rest_deploymentinfo(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
791{
792 if (!CheckWarmup(req)) return false;
793
794 std::string hash_str;
796 const bool current_tip{hash_str.empty()};
797
798 switch (rf) {
803
804 if (!current_tip) {
805 auto hash{uint256::FromHex(hash_str)};
806 if (!hash) {
807 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hash_str);
808 }
809
810 const ChainstateManager* chainman = GetChainman(context, req);
811 if (!chainman) return false;
812 if (!WITH_LOCK(::cs_main, return chainman->m_blockman.LookupBlockIndex(*hash))) {
813 return RESTERR(req, HTTP_BAD_REQUEST, "Block not found");
814 }
815
816 jsonRequest.params.push_back(hash_str);
817 }
818
820 req->WriteHeader("Content-Type", "application/json");
822 return true;
823 }
824 default: {
825 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
826 }
827 }
828
829}
830
831static bool rest_mempool(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
832{
833 if (!CheckWarmup(req))
834 return false;
835
836 std::string param;
838 if (param != "contents" && param != "info") {
839 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/mempool/<info|contents>.json");
840 }
841
842 const CTxMemPool* mempool = GetMemPool(context, req);
843 if (!mempool) return false;
844
845 switch (rf) {
847 std::string str_json;
848 if (param == "contents") {
849 std::string raw_verbose;
850 try {
851 raw_verbose = req->GetQueryParameter("verbose").value_or("true");
852 } catch (const std::runtime_error& e) {
853 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
854 }
855 if (raw_verbose != "true" && raw_verbose != "false") {
856 return RESTERR(req, HTTP_BAD_REQUEST, "The \"verbose\" query parameter must be either \"true\" or \"false\".");
857 }
858 std::string raw_mempool_sequence;
859 try {
860 raw_mempool_sequence = req->GetQueryParameter("mempool_sequence").value_or("false");
861 } catch (const std::runtime_error& e) {
862 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
863 }
864 if (raw_mempool_sequence != "true" && raw_mempool_sequence != "false") {
865 return RESTERR(req, HTTP_BAD_REQUEST, "The \"mempool_sequence\" query parameter must be either \"true\" or \"false\".");
866 }
867 const bool verbose{raw_verbose == "true"};
868 const bool mempool_sequence{raw_mempool_sequence == "true"};
869 if (verbose && mempool_sequence) {
870 return RESTERR(req, HTTP_BAD_REQUEST, "Verbose results cannot contain mempool sequence values. (hint: set \"verbose=false\")");
871 }
872 str_json = MempoolToJSON(*mempool, verbose, mempool_sequence).write() + "\n";
873 } else {
874 str_json = MempoolInfoToJSON(*mempool).write() + "\n";
875 }
876
877 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
878 req->WriteHeader("Content-Type", "application/json");
880 return true;
881 }
882 default: {
883 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
884 }
885 }
886}
887
888static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string& uri_part)
889{
890 if (!CheckWarmup(req))
891 return false;
892 std::string hashStr;
894
895 auto hash{Txid::FromHex(hashStr)};
896 if (!hash) {
897 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
898 }
899
900 if (g_txindex) {
901 g_txindex->BlockUntilSyncedToCurrentChain();
902 }
903
904 const NodeContext* const node = GetNodeContext(context, req);
905 if (!node) return false;
906 uint256 hashBlock = uint256();
907 const CTransactionRef tx{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), *hash, node->chainman->m_blockman, hashBlock)};
908 if (!tx) {
909 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
910 }
911 switch (rf) {
914 ssTx << TX_WITH_WITNESS(tx);
915
916 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
917 req->WriteHeader("Content-Type", "application/octet-stream");
918 req->WriteReply(HTTP_OK, ssTx);
919 return true;
920 }
921
924 ssTx << TX_WITH_WITNESS(tx);
925
926 std::string strHex = HexStr(ssTx) + "\n";
927 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
928 req->WriteHeader("Content-Type", "text/plain");
930 return true;
931 }
932
935 TxToUniv(*tx, /*block_hash=*/hashBlock, /*entry=*/ objTx);
936 std::string strJSON = objTx.write() + "\n";
937 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
938 req->WriteHeader("Content-Type", "application/json");
940 return true;
941 }
942
943 default: {
944 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
945 }
946 }
947}
948
949static bool rest_getutxos(const std::any& context, HTTPRequest* req, const std::string& uri_part)
950{
951 if (!CheckWarmup(req))
952 return false;
953 std::string param;
955
956 std::vector<std::string> uriParts;
957 if (param.length() > 1)
958 {
959 std::string strUriParams = param.substr(1);
960 uriParts = SplitString(strUriParams, '/');
961 }
962
963 // throw exception in case of an empty request
964 std::string strRequestMutable = req->ReadBody();
965 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
966 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
967
968 bool fInputParsed = false;
969 bool fCheckMemPool = false;
970 std::vector<COutPoint> vOutPoints;
971
972 // parse/deserialize input
973 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
974
975 if (uriParts.size() > 0)
976 {
977 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
978 if (uriParts[0] == "checkmempool") fCheckMemPool = true;
979
980 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
981 {
982 const auto txid_out{util::Split<std::string_view>(uriParts[i], '-')};
983 if (txid_out.size() != 2) {
984 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
985 }
986 auto txid{Txid::FromHex(txid_out.at(0))};
987 auto output{ToIntegral<uint32_t>(txid_out.at(1))};
988
989 if (!txid || !output) {
990 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
991 }
992
993 vOutPoints.emplace_back(*txid, *output);
994 }
995
996 if (vOutPoints.size() > 0)
997 fInputParsed = true;
998 else
999 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
1000 }
1001
1002 switch (rf) {
1004 // convert hex to bin, continue then with bin part
1005 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
1006 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
1007 [[fallthrough]];
1008 }
1009
1011 try {
1012 //deserialize only if user sent a request
1013 if (strRequestMutable.size() > 0)
1014 {
1015 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
1016 return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
1017
1018 DataStream oss{};
1020 oss >> fCheckMemPool;
1021 oss >> vOutPoints;
1022 }
1023 } catch (const std::ios_base::failure&) {
1024 // abort in case of unreadable binary data
1025 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
1026 }
1027 break;
1028 }
1029
1031 if (!fInputParsed)
1032 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
1033 break;
1034 }
1035 default: {
1036 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1037 }
1038 }
1039
1040 // limit max outpoints
1042 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
1043
1044 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
1045 std::vector<unsigned char> bitmap;
1046 std::vector<CCoin> outs;
1047 std::string bitmapStringRepresentation;
1048 std::vector<bool> hits;
1049 bitmap.resize(CeilDiv(vOutPoints.size(), 8u));
1051 if (!maybe_chainman) return false;
1052 ChainstateManager& chainman = *maybe_chainman;
1053 decltype(chainman.ActiveHeight()) active_height;
1055 {
1056 auto process_utxos = [&vOutPoints, &outs, &hits, &active_height, &active_hash, &chainman](const CCoinsView& view, const CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(chainman.GetMutex()) {
1057 for (const COutPoint& vOutPoint : vOutPoints) {
1058 auto coin = !mempool || !mempool->isSpent(vOutPoint) ? view.GetCoin(vOutPoint) : std::nullopt;
1059 hits.push_back(coin.has_value());
1060 if (coin) outs.emplace_back(std::move(*coin));
1061 }
1062 active_height = chainman.ActiveHeight();
1063 active_hash = chainman.ActiveTip()->GetBlockHash();
1064 };
1065
1066 if (fCheckMemPool) {
1067 const CTxMemPool* mempool = GetMemPool(context, req);
1068 if (!mempool) return false;
1069 // use db+mempool as cache backend in case user likes to query mempool
1070 LOCK2(cs_main, mempool->cs);
1073 process_utxos(viewMempool, mempool);
1074 } else {
1075 LOCK(cs_main);
1076 process_utxos(chainman.ActiveChainstate().CoinsTip(), nullptr);
1077 }
1078
1079 for (size_t i = 0; i < hits.size(); ++i) {
1080 const bool hit = hits[i];
1081 bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
1082 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
1083 }
1084 }
1085
1086 switch (rf) {
1088 // serialize data
1089 // use exact same output as mentioned in Bip64
1092
1093 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1094 req->WriteHeader("Content-Type", "application/octet-stream");
1096 return true;
1097 }
1098
1102 std::string strHex = HexStr(ssGetUTXOResponse) + "\n";
1103
1104 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1105 req->WriteHeader("Content-Type", "text/plain");
1106 req->WriteReply(HTTP_OK, strHex);
1107 return true;
1108 }
1109
1112
1113 // pack in some essentials
1114 // use more or less the same output as mentioned in Bip64
1115 objGetUTXOResponse.pushKV("chainHeight", active_height);
1116 objGetUTXOResponse.pushKV("chaintipHash", active_hash.GetHex());
1118
1120 for (const CCoin& coin : outs) {
1122 utxo.pushKV("height", coin.nHeight);
1123 utxo.pushKV("value", ValueFromAmount(coin.out.nValue));
1124
1125 // include the script in a json output
1127 ScriptToUniv(coin.out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1128 utxo.pushKV("scriptPubKey", std::move(o));
1129 utxos.push_back(std::move(utxo));
1130 }
1131 objGetUTXOResponse.pushKV("utxos", std::move(utxos));
1132
1133 // return json string
1134 std::string strJSON = objGetUTXOResponse.write() + "\n";
1135 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1136 req->WriteHeader("Content-Type", "application/json");
1137 req->WriteReply(HTTP_OK, strJSON);
1138 return true;
1139 }
1140 default: {
1141 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1142 }
1143 }
1144}
1145
1146static bool rest_blockhash_by_height(const std::any& context, HTTPRequest* req,
1147 const std::string& str_uri_part)
1148{
1149 if (!CheckWarmup(req)) return false;
1150 std::string height_str;
1152
1154 if (!blockheight || *blockheight < 0) {
1155 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid height: " + SanitizeString(height_str, SAFE_CHARS_URI));
1156 }
1157
1158 CBlockIndex* pblockindex = nullptr;
1159 {
1161 if (!maybe_chainman) return false;
1162 ChainstateManager& chainman = *maybe_chainman;
1163 LOCK(cs_main);
1164 const CChain& active_chain = chainman.ActiveChain();
1165 if (*blockheight > active_chain.Height()) {
1166 return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range");
1167 }
1169 }
1170 switch (rf) {
1173 ss_blockhash << pblockindex->GetBlockHash();
1174 // Do not cache because reorgs can change the response.
1175 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1176 req->WriteHeader("Content-Type", "application/octet-stream");
1178 return true;
1179 }
1181 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1182 req->WriteHeader("Content-Type", "text/plain");
1183 req->WriteReply(HTTP_OK, pblockindex->GetBlockHash().GetHex() + "\n");
1184 return true;
1185 }
1187 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1188 req->WriteHeader("Content-Type", "application/json");
1190 resp.pushKV("blockhash", pblockindex->GetBlockHash().GetHex());
1191 req->WriteReply(HTTP_OK, resp.write() + "\n");
1192 return true;
1193 }
1194 default: {
1195 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1196 }
1197 }
1198}
1199
1200static const struct {
1201 const char* prefix;
1202 bool (*handler)(const std::any& context, HTTPRequest* req, const std::string& strReq);
1203} uri_prefixes[] = {
1204 {"/rest/tx/", rest_tx},
1205 {"/rest/block/notxdetails/", rest_block_notxdetails},
1206 {"/rest/block/", rest_block_extended},
1207 {"/rest/blockpart/", rest_block_part},
1208 {"/rest/blockfilter/", rest_block_filter},
1209 {"/rest/blockfilterheaders/", rest_filter_header},
1210 {"/rest/chaininfo", rest_chaininfo},
1211 {"/rest/mempool/", rest_mempool},
1212 {"/rest/headers/", rest_headers},
1213 {"/rest/getutxos", rest_getutxos},
1214 {"/rest/deploymentinfo/", rest_deploymentinfo},
1215 {"/rest/deploymentinfo", rest_deploymentinfo},
1216 {"/rest/blockhashbyheight/", rest_blockhash_by_height},
1217 {"/rest/spenttxouts/", rest_spent_txouts},
1219
1220void StartREST(const std::any& context)
1221{
1222 for (const auto& up : uri_prefixes) {
1223 auto handler = [context, up](HTTPRequest* req, const std::string& prefix) { return up.handler(context, req, prefix); };
1224 RegisterHTTPHandler(up.prefix, false, handler);
1225 }
1226}
1227
1229{
1230}
1231
1233{
1234 for (const auto& up : uri_prefixes) {
1235 UnregisterHTTPHandler(up.prefix, false);
1236 }
1237}
int ret
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity, const uint256 pow_limit)
Block description to JSON.
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex, const uint256 pow_limit)
Block header to JSON.
bool BlockFilterTypeByName(std::string_view name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterType
Definition blockfilter.h:94
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition chain.h:69
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition chain.h:76
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition chain.h:75
#define STR_INTERNAL_BUG(msg)
Definition check.h:100
Complete block filter struct as defined in BIP 157.
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
Definition block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition chain.h:94
uint256 GetBlockHash() const
Definition chain.h:198
Undo information for a CBlock.
Definition undo.h:64
An in-memory indexed chain of blocks.
Definition chain.h:380
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition chain.h:396
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:437
Pure abstract view on the open txout dataset.
Definition coins.h:356
CCoinsView that brings transactions from a mempool into view.
Definition txmempool.h:785
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:188
An output of a transaction.
Undo information for a CTransaction.
Definition undo.h:54
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:694
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition validation.h:950
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const Consensus::Params & GetConsensus() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
A UTXO entry.
Definition coins.h:46
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
void WriteHeader(std::string &&hdr, std::string &&value)
std::optional< std::string > GetQueryParameter(std::string_view key) const
std::string ReadBody() const
Definition httpserver.h:194
void WriteReply(HTTPStatusCode status, std::span< const std::byte > reply_body={})
std::any context
Definition request.h:64
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition util.cpp:645
Minimal stream for reading from an existing byte array by std::span.
Definition streams.h:83
void push_back(UniValue val)
Definition univalue.cpp:103
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:125
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
ReadRawBlockResult ReadRawBlock(const FlatFilePos &pos, std::optional< std::pair< size_t, size_t > > block_part=std::nullopt) const
static std::optional< transaction_identifier > FromHex(std::string_view hex)
256-bit opaque blob.
Definition uint256.h:196
static std::optional< uint256 > FromHex(std::string_view str)
Definition uint256.h:198
void ScriptToUniv(const CScript &script, UniValue &out, bool include_hex, bool include_address, const SigningProvider *provider)
Definition core_io.cpp:411
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex, const CTxUndo *txundo, TxVerbosity verbosity, std::function< bool(const CTxOut &)> is_change_func)
Definition core_io.cpp:432
UniValue ValueFromAmount(const CAmount amount)
Definition core_io.cpp:283
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:8
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
HTTPHeaders headers
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const Txid &hash, const BlockManager &blockman, uint256 &hashBlock)
Return transaction with a given hash.
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
Definition overflow.h:70
constexpr TransactionSerParams TX_WITH_WITNESS
std::shared_ptr< const CTransaction > CTransactionRef
static constexpr unsigned int MAX_REST_HEADERS_RESULTS
Definition rest.cpp:61
static bool rest_headers(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:202
static void SerializeBlockUndo(DataStream &stream, const CBlockUndo &block_undo)
Serialize spent outputs as a list of per-transaction CTxOut lists using binary format.
Definition rest.cpp:306
static bool rest_block_extended(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:510
static bool rest_blockhash_by_height(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition rest.cpp:1146
static bool rest_block_part(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:520
RESTResponseFormat rf
Definition rest.cpp:70
static constexpr const char * REST_CACHE_IMMUTABLE
Response bytes never change.
Definition rest.cpp:65
static bool rest_block_filter(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:665
const char * prefix
Definition rest.cpp:1201
static bool rest_block_notxdetails(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:515
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition rest.cpp:1220
static bool rest_filter_header(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:539
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition rest.cpp:1202
static bool rest_getutxos(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:949
static bool rest_tx(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:888
static bool rest_block(const std::any &context, HTTPRequest *req, const std::string &uri_part, std::optional< TxVerbosity > tx_verbosity, std::optional< std::pair< size_t, size_t > > block_part=std::nullopt)
This handler is used by multiple HTTP endpoints:
Definition rest.cpp:425
static const struct @10 uri_prefixes[]
void StopREST()
Stop HTTP REST subsystem.
Definition rest.cpp:1232
const char * name
Definition rest.cpp:71
void InterruptREST()
Interrupt RPC REST subsystem.
Definition rest.cpp:1228
static bool rest_deploymentinfo(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition rest.cpp:790
static bool RESTERR(HTTPRequest *req, enum HTTPStatusCode status, std::string message)
Definition rest.cpp:93
static bool rest_mempool(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition rest.cpp:831
static const struct @9 rf_names[]
static constexpr const char * REST_CACHE_NO_STORE
Mutable, node-local, or error response; must not be cached.
Definition rest.cpp:67
static bool CheckWarmup(HTTPRequest *req)
Definition rest.cpp:194
static ChainstateManager * GetChainman(const std::any &context, HTTPRequest *req)
Get the node context chainstatemanager.
Definition rest.cpp:142
RPCMethod getblockchaininfo()
static void BlockUndoToJSON(const CBlockUndo &block_undo, UniValue &result)
Serialize spent outputs as a list of per-transaction CTxOut lists using JSON format.
Definition rest.cpp:321
static bool rest_chaininfo(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:762
RPCMethod getdeploymentinfo()
static bool rest_spent_txouts(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:342
RESTResponseFormat ParseDataFormat(std::string &param, const std::string &strReq)
Parse a URI to get the data format and URI without data format and query string.
Definition rest.cpp:152
static CTxMemPool * GetMemPool(const std::any &context, HTTPRequest *req)
Get the node context mempool.
Definition rest.cpp:125
static const size_t MAX_GETUTXOS_OUTPOINTS
Definition rest.cpp:60
static std::string AvailableDataFormatsString()
Definition rest.cpp:177
static NodeContext * GetNodeContext(const std::any &context, HTTPRequest *req)
Get the node context.
Definition rest.cpp:108
RESTResponseFormat
Definition rest.h:10
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
Definition mempool.cpp:1097
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
Definition mempool.cpp:638
HTTPStatusCode
HTTP status codes.
Definition protocol.h:13
@ HTTP_BAD_REQUEST
Definition protocol.h:16
@ HTTP_OK
Definition protocol.h:14
@ HTTP_SERVICE_UNAVAILABLE
Definition protocol.h:23
@ HTTP_NOT_FOUND
Definition protocol.h:19
@ HTTP_INTERNAL_SERVER_ERROR
Definition protocol.h:22
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition serialize.h:1151
#define READWRITE(...)
Definition serialize.h:148
bool RPCIsInWarmup(std::string *outStatus)
Definition server.cpp:707
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition rest.cpp:79
CTxOut out
Definition rest.cpp:81
CCoin(Coin &&in)
Definition rest.cpp:84
uint32_t nHeight
Definition rest.cpp:80
CCoin()
Definition rest.cpp:83
SERIALIZE_METHODS(CCoin, obj)
Definition rest.cpp:86
uint256 powLimit
Proof of work parameters.
Definition params.h:116
NodeContext struct containing references to chain state and connection state.
Definition context.h:57
#define LOCK2(cs1, cs2)
Definition sync.h:269
#define LOCK(cs)
Definition sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:299
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition txindex.cpp:44
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())
WalletContext context