Bitcoin Core 32.1.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 {
80 uint32_t nHeight;
82
83 CCoin() : nHeight(0) {}
84 explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
85
87 {
88 uint32_t nTxVerDummy = 0;
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
195{
196 std::string statusmessage;
197 if (RPCIsInWarmup(&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,
204 const std::string& uri_part)
205{
206 if (!CheckWarmup(req))
207 return false;
208 std::string param;
209 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
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
230 const auto parsed_count{ToIntegral<size_t>(raw_count)};
231 if (!parsed_count.has_value() || *parsed_count < 1 || *parsed_count > MAX_REST_HEADERS_RESULTS) {
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);
243 ChainstateManager* maybe_chainman = GetChainman(context, req);
244 if (!maybe_chainman) return false;
245 ChainstateManager& chainman = *maybe_chainman;
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) {
262 DataStream ssHeader{};
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");
270 req->WriteReply(HTTP_OK, ssHeader);
271 return true;
272 }
273
275 DataStream ssHeader{};
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");
283 req->WriteReply(HTTP_OK, strHex);
284 return true;
285 }
287 UniValue jsonHeaders(UniValue::VARR);
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");
294 req->WriteReply(HTTP_OK, strJSON);
295 return true;
296 }
297 default: {
298 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
299 }
300 }
301}
302
306static void SerializeBlockUndo(DataStream& stream, const CBlockUndo& block_undo)
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) {
325 UniValue tx_prevouts(UniValue::VARR);
326 for (const Coin& coin : tx_undo.vprevout) {
327 UniValue prevout(UniValue::VOBJ);
328 prevout.pushKV("value", ValueFromAmount(coin.out.nValue));
329
330 UniValue script_pub_key(UniValue::VOBJ);
331 ScriptToUniv(coin.out.scriptPubKey, /*out=*/script_pub_key, /*include_hex=*/true, /*include_address=*/true);
332 prevout.pushKV("scriptPubKey", std::move(script_pub_key));
333
334 tx_prevouts.push_back(std::move(prevout));
335 }
336 result.push_back(std::move(tx_prevouts));
337 }
338}
339
340static bool rest_spent_txouts(const std::any& context, HTTPRequest* req, const std::string& uri_part)
341{
342 if (!CheckWarmup(req)) {
343 return false;
344 }
345 std::string param;
346 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
347 std::vector<std::string> path = SplitString(param, '/');
348
349 std::string hashStr;
350 if (path.size() == 1) {
351 // path with query parameter: /rest/spenttxouts/<hash>
352 hashStr = path[0];
353 } else {
354 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/spenttxouts/<hash>.<ext>");
355 }
356
357 auto hash{uint256::FromHex(hashStr)};
358 if (!hash) {
359 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
360 }
361
362 ChainstateManager* chainman = GetChainman(context, req);
363 if (!chainman) {
364 return false;
365 }
366
367 const CBlockIndex* pblockindex = WITH_LOCK(cs_main, return chainman->m_blockman.LookupBlockIndex(*hash));
368 if (!pblockindex) {
369 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
370 }
371
372 CBlockUndo block_undo;
373 if (pblockindex->nHeight > 0 && !chainman->m_blockman.ReadBlockUndo(block_undo, *pblockindex)) {
374 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " undo not available");
375 }
376
377 switch (rf) {
379 DataStream ssSpentResponse{};
380 SerializeBlockUndo(ssSpentResponse, block_undo);
381 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
382 req->WriteHeader("Content-Type", "application/octet-stream");
383 req->WriteReply(HTTP_OK, ssSpentResponse);
384 return true;
385 }
386
388 DataStream ssSpentResponse{};
389 SerializeBlockUndo(ssSpentResponse, block_undo);
390 const std::string strHex{HexStr(ssSpentResponse) + "\n"};
391 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
392 req->WriteHeader("Content-Type", "text/plain");
393 req->WriteReply(HTTP_OK, strHex);
394 return true;
395 }
396
398 UniValue result(UniValue::VARR);
399 BlockUndoToJSON(block_undo, result);
400 std::string strJSON = result.write() + "\n";
401 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
402 req->WriteHeader("Content-Type", "application/json");
403 req->WriteReply(HTTP_OK, strJSON);
404 return true;
405 }
406
407 default: {
408 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
409 }
410 }
411}
412
419static bool rest_block(const std::any& context,
421 const std::string& uri_part,
422 std::optional<TxVerbosity> tx_verbosity,
423 std::optional<std::pair<size_t, size_t>> block_part = std::nullopt)
424{
425 if (!CheckWarmup(req))
426 return false;
427 std::string hashStr;
428 const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part);
429
430 auto hash{uint256::FromHex(hashStr)};
431 if (!hash) {
432 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
433 }
434
435 FlatFilePos pos{};
436 const CBlockIndex* pblockindex = nullptr;
437 const CBlockIndex* tip = nullptr;
438 ChainstateManager* maybe_chainman = GetChainman(context, req);
439 if (!maybe_chainman) return false;
440 ChainstateManager& chainman = *maybe_chainman;
441 {
442 LOCK(cs_main);
443 tip = chainman.ActiveChain().Tip();
444 pblockindex = chainman.m_blockman.LookupBlockIndex(*hash);
445 if (!pblockindex) {
446 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
447 }
448 if (!(pblockindex->nStatus & BLOCK_HAVE_DATA)) {
449 if (chainman.m_blockman.IsBlockPruned(*pblockindex)) {
450 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
451 }
452 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (not fully downloaded)");
453 }
454 pos = pblockindex->GetBlockPos();
455 }
456
457 const auto block_data{chainman.m_blockman.ReadRawBlock(pos, block_part)};
458 if (!block_data) {
459 switch (block_data.error()) {
460 case node::ReadRawError::IO: return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "I/O error reading " + hashStr);
462 assert(block_part);
463 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Bad block part offset/size %d/%d for %s", block_part->first, block_part->second, hashStr));
464 } // no default case, so the compiler can warn about missing cases
465 assert(false);
466 }
467
468 switch (rf) {
470 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
471 req->WriteHeader("Content-Type", "application/octet-stream");
472 req->WriteReply(HTTP_OK, *block_data);
473 return true;
474 }
475
477 const std::string strHex{HexStr(*block_data) + "\n"};
478 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
479 req->WriteHeader("Content-Type", "text/plain");
480 req->WriteReply(HTTP_OK, strHex);
481 return true;
482 }
483
485 if (tx_verbosity) {
486 CBlock block{};
487 SpanReader{*block_data} >> TX_WITH_WITNESS(block);
488 UniValue objBlock = blockToJSON(chainman.m_blockman, block, *tip, *pblockindex, *tx_verbosity, chainman.GetConsensus().powLimit);
489 std::string strJSON = objBlock.write() + "\n";
490 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
491 req->WriteHeader("Content-Type", "application/json");
492 req->WriteReply(HTTP_OK, strJSON);
493 return true;
494 }
495 return RESTERR(req, HTTP_BAD_REQUEST, "JSON output is not supported for this request type");
496 }
497
498 default: {
499 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
500 }
501 }
502}
503
504static bool rest_block_extended(const std::any& context, HTTPRequest* req, const std::string& uri_part)
505{
506 return rest_block(context, req, uri_part, TxVerbosity::SHOW_DETAILS_AND_PREVOUT);
507}
508
509static bool rest_block_notxdetails(const std::any& context, HTTPRequest* req, const std::string& uri_part)
510{
511 return rest_block(context, req, uri_part, TxVerbosity::SHOW_TXID);
512}
513
514static bool rest_block_part(const std::any& context, HTTPRequest* req, const std::string& uri_part)
515{
516 try {
517 if (const auto opt_offset{ToIntegral<size_t>(req->GetQueryParameter("offset").value_or(""))}) {
518 if (const auto opt_size{ToIntegral<size_t>(req->GetQueryParameter("size").value_or(""))}) {
519 return rest_block(context, req, uri_part,
520 /*tx_verbosity=*/std::nullopt,
521 /*block_part=*/{{*opt_offset, *opt_size}});
522 } else {
523 return RESTERR(req, HTTP_BAD_REQUEST, "Block part size missing or invalid");
524 }
525 } else {
526 return RESTERR(req, HTTP_BAD_REQUEST, "Block part offset missing or invalid");
527 }
528 } catch (const std::runtime_error& e) {
529 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
530 }
531}
532
533static bool rest_filter_header(const std::any& context, HTTPRequest* req, const std::string& uri_part)
534{
535 if (!CheckWarmup(req)) return false;
536
537 std::string param;
538 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
539
540 std::vector<std::string> uri_parts = SplitString(param, '/');
541 std::string raw_count;
542 std::string raw_blockhash;
543 if (uri_parts.size() == 3) {
544 // deprecated path: /rest/blockfilterheaders/<filtertype>/<count>/<blockhash>
545 raw_blockhash = uri_parts[2];
546 raw_count = uri_parts[1];
547 } else if (uri_parts.size() == 2) {
548 // new path with query parameter: /rest/blockfilterheaders/<filtertype>/<blockhash>?count=<count>
549 raw_blockhash = uri_parts[1];
550 try {
551 raw_count = req->GetQueryParameter("count").value_or("5");
552 } catch (const std::runtime_error& e) {
553 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
554 }
555 } else {
556 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilterheaders/<filtertype>/<blockhash>.<ext>?count=<count>");
557 }
558
559 const auto parsed_count{ToIntegral<size_t>(raw_count)};
560 if (!parsed_count.has_value() || *parsed_count < 1 || *parsed_count > MAX_REST_HEADERS_RESULTS) {
561 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));
562 }
563
564 auto block_hash{uint256::FromHex(raw_blockhash)};
565 if (!block_hash) {
566 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + raw_blockhash);
567 }
568
569 BlockFilterType filtertype;
570 if (!BlockFilterTypeByName(uri_parts[0], filtertype)) {
571 return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
572 }
573
574 BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
575 if (!index) {
576 return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
577 }
578
579 std::vector<const CBlockIndex*> headers;
580 headers.reserve(*parsed_count);
581 {
582 ChainstateManager* maybe_chainman = GetChainman(context, req);
583 if (!maybe_chainman) return false;
584 ChainstateManager& chainman = *maybe_chainman;
585 LOCK(cs_main);
586 CChain& active_chain = chainman.ActiveChain();
587 const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*block_hash)};
588 while (pindex != nullptr && active_chain.Contains(*pindex)) {
589 headers.push_back(pindex);
590 if (headers.size() == *parsed_count)
591 break;
592 pindex = active_chain.Next(*pindex);
593 }
594 }
595
596 bool index_ready = index->BlockUntilSyncedToCurrentChain();
597
598 std::vector<uint256> filter_headers;
599 filter_headers.reserve(*parsed_count);
600 for (const CBlockIndex* pindex : headers) {
601 uint256 filter_header;
602 if (!index->LookupFilterHeader(pindex, filter_header)) {
603 std::string errmsg = "Filter not found.";
604
605 if (!index_ready) {
606 errmsg += " Block filters are still in the process of being indexed.";
607 } else {
608 errmsg += " This error is unexpected and indicates index corruption.";
609 }
610
611 return RESTERR(req, HTTP_NOT_FOUND, errmsg);
612 }
613 filter_headers.push_back(filter_header);
614 }
615
616 switch (rf) {
618 DataStream ssHeader{};
619 for (const uint256& header : filter_headers) {
620 ssHeader << header;
621 }
622
623 // Do not cache because chain extensions and reorgs can affect the response.
624 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
625 req->WriteHeader("Content-Type", "application/octet-stream");
626 req->WriteReply(HTTP_OK, ssHeader);
627 return true;
628 }
630 DataStream ssHeader{};
631 for (const uint256& header : filter_headers) {
632 ssHeader << header;
633 }
634
635 std::string strHex = HexStr(ssHeader) + "\n";
636 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
637 req->WriteHeader("Content-Type", "text/plain");
638 req->WriteReply(HTTP_OK, strHex);
639 return true;
640 }
642 UniValue jsonHeaders(UniValue::VARR);
643 for (const uint256& header : filter_headers) {
644 jsonHeaders.push_back(header.GetHex());
645 }
646
647 std::string strJSON = jsonHeaders.write() + "\n";
648 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
649 req->WriteHeader("Content-Type", "application/json");
650 req->WriteReply(HTTP_OK, strJSON);
651 return true;
652 }
653 default: {
654 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
655 }
656 }
657}
658
659static bool rest_block_filter(const std::any& context, HTTPRequest* req, const std::string& uri_part)
660{
661 if (!CheckWarmup(req)) return false;
662
663 std::string param;
664 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
665
666 // request is sent over URI scheme /rest/blockfilter/filtertype/blockhash
667 std::vector<std::string> uri_parts = SplitString(param, '/');
668 if (uri_parts.size() != 2) {
669 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilter/<filtertype>/<blockhash>");
670 }
671
672 auto block_hash{uint256::FromHex(uri_parts[1])};
673 if (!block_hash) {
674 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + uri_parts[1]);
675 }
676
677 BlockFilterType filtertype;
678 if (!BlockFilterTypeByName(uri_parts[0], filtertype)) {
679 return RESTERR(req, HTTP_BAD_REQUEST, "Unknown filtertype " + uri_parts[0]);
680 }
681
682 BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
683 if (!index) {
684 return RESTERR(req, HTTP_BAD_REQUEST, "Index is not enabled for filtertype " + uri_parts[0]);
685 }
686
687 const CBlockIndex* block_index;
688 bool block_was_connected;
689 {
690 ChainstateManager* maybe_chainman = GetChainman(context, req);
691 if (!maybe_chainman) return false;
692 ChainstateManager& chainman = *maybe_chainman;
693 LOCK(cs_main);
694 block_index = chainman.m_blockman.LookupBlockIndex(*block_hash);
695 if (!block_index) {
696 return RESTERR(req, HTTP_NOT_FOUND, uri_parts[1] + " not found");
697 }
698 block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
699 }
700
701 bool index_ready = index->BlockUntilSyncedToCurrentChain();
702
703 BlockFilter filter;
704 if (!index->LookupFilter(block_index, filter)) {
705 std::string errmsg = "Filter not found.";
706
707 if (!block_was_connected) {
708 errmsg += " Block was not connected to active chain.";
709 } else if (!index_ready) {
710 errmsg += " Block filters are still in the process of being indexed.";
711 } else {
712 errmsg += " This error is unexpected and indicates index corruption.";
713 }
714
715 return RESTERR(req, HTTP_NOT_FOUND, errmsg);
716 }
717
718 switch (rf) {
720 DataStream ssResp{};
721 ssResp << filter;
722
723 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
724 req->WriteHeader("Content-Type", "application/octet-stream");
725 req->WriteReply(HTTP_OK, ssResp);
726 return true;
727 }
729 DataStream ssResp{};
730 ssResp << filter;
731
732 std::string strHex = HexStr(ssResp) + "\n";
733 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
734 req->WriteHeader("Content-Type", "text/plain");
735 req->WriteReply(HTTP_OK, strHex);
736 return true;
737 }
740 ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
741 std::string strJSON = ret.write() + "\n";
742 req->WriteHeader("Cache-Control", REST_CACHE_IMMUTABLE);
743 req->WriteHeader("Content-Type", "application/json");
744 req->WriteReply(HTTP_OK, strJSON);
745 return true;
746 }
747 default: {
748 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
749 }
750 }
751}
752
753// A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
755
756static bool rest_chaininfo(const std::any& context, HTTPRequest* req, const std::string& uri_part)
757{
758 if (!CheckWarmup(req))
759 return false;
760 std::string param;
761 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
762
763 switch (rf) {
765 JSONRPCRequest jsonRequest;
766 jsonRequest.context = context;
767 jsonRequest.params = UniValue(UniValue::VARR);
768 UniValue chainInfoObject = getblockchaininfo().HandleRequest(jsonRequest);
769 std::string strJSON = chainInfoObject.write() + "\n";
770 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
771 req->WriteHeader("Content-Type", "application/json");
772 req->WriteReply(HTTP_OK, strJSON);
773 return true;
774 }
775 default: {
776 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
777 }
778 }
779}
780
781
783
784static bool rest_deploymentinfo(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
785{
786 if (!CheckWarmup(req)) return false;
787
788 std::string hash_str;
789 const RESTResponseFormat rf = ParseDataFormat(hash_str, str_uri_part);
790 const bool current_tip{hash_str.empty()};
791
792 switch (rf) {
794 JSONRPCRequest jsonRequest;
795 jsonRequest.context = context;
796 jsonRequest.params = UniValue(UniValue::VARR);
797
798 if (!current_tip) {
799 auto hash{uint256::FromHex(hash_str)};
800 if (!hash) {
801 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hash_str);
802 }
803
804 const ChainstateManager* chainman = GetChainman(context, req);
805 if (!chainman) return false;
806 if (!WITH_LOCK(::cs_main, return chainman->m_blockman.LookupBlockIndex(*hash))) {
807 return RESTERR(req, HTTP_BAD_REQUEST, "Block not found");
808 }
809
810 jsonRequest.params.push_back(hash_str);
811 }
812
813 req->WriteHeader("Cache-Control", current_tip ? REST_CACHE_NO_STORE : REST_CACHE_IMMUTABLE);
814 req->WriteHeader("Content-Type", "application/json");
815 req->WriteReply(HTTP_OK, getdeploymentinfo().HandleRequest(jsonRequest).write() + "\n");
816 return true;
817 }
818 default: {
819 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
820 }
821 }
822
823}
824
825static bool rest_mempool(const std::any& context, HTTPRequest* req, const std::string& str_uri_part)
826{
827 if (!CheckWarmup(req))
828 return false;
829
830 std::string param;
831 const RESTResponseFormat rf = ParseDataFormat(param, str_uri_part);
832 if (param != "contents" && param != "info") {
833 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/mempool/<info|contents>.json");
834 }
835
836 const CTxMemPool* mempool = GetMemPool(context, req);
837 if (!mempool) return false;
838
839 switch (rf) {
841 std::string str_json;
842 if (param == "contents") {
843 std::string raw_verbose;
844 try {
845 raw_verbose = req->GetQueryParameter("verbose").value_or("true");
846 } catch (const std::runtime_error& e) {
847 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
848 }
849 if (raw_verbose != "true" && raw_verbose != "false") {
850 return RESTERR(req, HTTP_BAD_REQUEST, "The \"verbose\" query parameter must be either \"true\" or \"false\".");
851 }
852 std::string raw_mempool_sequence;
853 try {
854 raw_mempool_sequence = req->GetQueryParameter("mempool_sequence").value_or("false");
855 } catch (const std::runtime_error& e) {
856 return RESTERR(req, HTTP_BAD_REQUEST, e.what());
857 }
858 if (raw_mempool_sequence != "true" && raw_mempool_sequence != "false") {
859 return RESTERR(req, HTTP_BAD_REQUEST, "The \"mempool_sequence\" query parameter must be either \"true\" or \"false\".");
860 }
861 const bool verbose{raw_verbose == "true"};
862 const bool mempool_sequence{raw_mempool_sequence == "true"};
863 if (verbose && mempool_sequence) {
864 return RESTERR(req, HTTP_BAD_REQUEST, "Verbose results cannot contain mempool sequence values. (hint: set \"verbose=false\")");
865 }
866 str_json = MempoolToJSON(*mempool, verbose, mempool_sequence).write() + "\n";
867 } else {
868 str_json = MempoolInfoToJSON(*mempool).write() + "\n";
869 }
870
871 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
872 req->WriteHeader("Content-Type", "application/json");
873 req->WriteReply(HTTP_OK, str_json);
874 return true;
875 }
876 default: {
877 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
878 }
879 }
880}
881
882static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string& uri_part)
883{
884 if (!CheckWarmup(req))
885 return false;
886 std::string hashStr;
887 const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part);
888
889 auto hash{Txid::FromHex(hashStr)};
890 if (!hash) {
891 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
892 }
893
894 if (g_txindex) {
895 g_txindex->BlockUntilSyncedToCurrentChain();
896 }
897
898 const NodeContext* const node = GetNodeContext(context, req);
899 if (!node) return false;
900 uint256 hashBlock = uint256();
901 const CTransactionRef tx{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), *hash, node->chainman->m_blockman, hashBlock)};
902 if (!tx) {
903 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
904 }
905 switch (rf) {
907 DataStream ssTx;
908 ssTx << TX_WITH_WITNESS(tx);
909
910 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
911 req->WriteHeader("Content-Type", "application/octet-stream");
912 req->WriteReply(HTTP_OK, ssTx);
913 return true;
914 }
915
917 DataStream ssTx;
918 ssTx << TX_WITH_WITNESS(tx);
919
920 std::string strHex = HexStr(ssTx) + "\n";
921 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
922 req->WriteHeader("Content-Type", "text/plain");
923 req->WriteReply(HTTP_OK, strHex);
924 return true;
925 }
926
929 TxToUniv(*tx, /*block_hash=*/hashBlock, /*entry=*/ objTx);
930 std::string strJSON = objTx.write() + "\n";
931 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
932 req->WriteHeader("Content-Type", "application/json");
933 req->WriteReply(HTTP_OK, strJSON);
934 return true;
935 }
936
937 default: {
938 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
939 }
940 }
941}
942
943static bool rest_getutxos(const std::any& context, HTTPRequest* req, const std::string& uri_part)
944{
945 if (!CheckWarmup(req))
946 return false;
947 std::string param;
948 const RESTResponseFormat rf = ParseDataFormat(param, uri_part);
949
950 std::vector<std::string> uriParts;
951 if (param.length() > 1)
952 {
953 std::string strUriParams = param.substr(1);
954 uriParts = SplitString(strUriParams, '/');
955 }
956
957 // throw exception in case of an empty request
958 std::string strRequestMutable = req->ReadBody();
959 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
960 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
961
962 bool fInputParsed = false;
963 bool fCheckMemPool = false;
964 std::vector<COutPoint> vOutPoints;
965
966 // parse/deserialize input
967 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
968
969 if (uriParts.size() > 0)
970 {
971 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
972 if (uriParts[0] == "checkmempool") fCheckMemPool = true;
973
974 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
975 {
976 const auto txid_out{util::Split<std::string_view>(uriParts[i], '-')};
977 if (txid_out.size() != 2) {
978 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
979 }
980 auto txid{Txid::FromHex(txid_out.at(0))};
981 auto output{ToIntegral<uint32_t>(txid_out.at(1))};
982
983 if (!txid || !output) {
984 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
985 }
986
987 vOutPoints.emplace_back(*txid, *output);
988 }
989
990 if (vOutPoints.size() > 0)
991 fInputParsed = true;
992 else
993 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
994 }
995
996 switch (rf) {
998 // convert hex to bin, continue then with bin part
999 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
1000 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
1001 [[fallthrough]];
1002 }
1003
1005 try {
1006 //deserialize only if user sent a request
1007 if (strRequestMutable.size() > 0)
1008 {
1009 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
1010 return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
1011
1012 DataStream oss{};
1013 oss << strRequestMutable;
1014 oss >> fCheckMemPool;
1015 oss >> vOutPoints;
1016 }
1017 } catch (const std::ios_base::failure&) {
1018 // abort in case of unreadable binary data
1019 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
1020 }
1021 break;
1022 }
1023
1025 if (!fInputParsed)
1026 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
1027 break;
1028 }
1029 default: {
1030 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1031 }
1032 }
1033
1034 // limit max outpoints
1035 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
1036 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
1037
1038 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
1039 std::vector<unsigned char> bitmap;
1040 std::vector<CCoin> outs;
1041 std::string bitmapStringRepresentation;
1042 std::vector<bool> hits;
1043 bitmap.resize(CeilDiv(vOutPoints.size(), 8u));
1044 ChainstateManager* maybe_chainman = GetChainman(context, req);
1045 if (!maybe_chainman) return false;
1046 ChainstateManager& chainman = *maybe_chainman;
1047 decltype(chainman.ActiveHeight()) active_height;
1048 uint256 active_hash;
1049 {
1050 auto process_utxos = [&vOutPoints, &outs, &hits, &active_height, &active_hash, &chainman](const CCoinsView& view, const CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(chainman.GetMutex()) {
1051 for (const COutPoint& vOutPoint : vOutPoints) {
1052 auto coin = !mempool || !mempool->isSpent(vOutPoint) ? view.GetCoin(vOutPoint) : std::nullopt;
1053 hits.push_back(coin.has_value());
1054 if (coin) outs.emplace_back(std::move(*coin));
1055 }
1056 active_height = chainman.ActiveHeight();
1057 active_hash = chainman.ActiveTip()->GetBlockHash();
1058 };
1059
1060 if (fCheckMemPool) {
1061 const CTxMemPool* mempool = GetMemPool(context, req);
1062 if (!mempool) return false;
1063 // use db+mempool as cache backend in case user likes to query mempool
1064 LOCK2(cs_main, mempool->cs);
1065 CCoinsViewCache& viewChain = chainman.ActiveChainstate().CoinsTip();
1066 CCoinsViewMemPool viewMempool(&viewChain, *mempool);
1067 process_utxos(viewMempool, mempool);
1068 } else {
1069 LOCK(cs_main);
1070 process_utxos(chainman.ActiveChainstate().CoinsTip(), nullptr);
1071 }
1072
1073 for (size_t i = 0; i < hits.size(); ++i) {
1074 const bool hit = hits[i];
1075 bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
1076 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
1077 }
1078 }
1079
1080 switch (rf) {
1082 // serialize data
1083 // use exact same output as mentioned in Bip64
1084 DataStream ssGetUTXOResponse{};
1085 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
1086
1087 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1088 req->WriteHeader("Content-Type", "application/octet-stream");
1089 req->WriteReply(HTTP_OK, ssGetUTXOResponse);
1090 return true;
1091 }
1092
1094 DataStream ssGetUTXOResponse{};
1095 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
1096 std::string strHex = HexStr(ssGetUTXOResponse) + "\n";
1097
1098 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1099 req->WriteHeader("Content-Type", "text/plain");
1100 req->WriteReply(HTTP_OK, strHex);
1101 return true;
1102 }
1103
1105 UniValue objGetUTXOResponse(UniValue::VOBJ);
1106
1107 // pack in some essentials
1108 // use more or less the same output as mentioned in Bip64
1109 objGetUTXOResponse.pushKV("chainHeight", active_height);
1110 objGetUTXOResponse.pushKV("chaintipHash", active_hash.GetHex());
1111 objGetUTXOResponse.pushKV("bitmap", bitmapStringRepresentation);
1112
1113 UniValue utxos(UniValue::VARR);
1114 for (const CCoin& coin : outs) {
1116 utxo.pushKV("height", coin.nHeight);
1117 utxo.pushKV("value", ValueFromAmount(coin.out.nValue));
1118
1119 // include the script in a json output
1121 ScriptToUniv(coin.out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1122 utxo.pushKV("scriptPubKey", std::move(o));
1123 utxos.push_back(std::move(utxo));
1124 }
1125 objGetUTXOResponse.pushKV("utxos", std::move(utxos));
1126
1127 // return json string
1128 std::string strJSON = objGetUTXOResponse.write() + "\n";
1129 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1130 req->WriteHeader("Content-Type", "application/json");
1131 req->WriteReply(HTTP_OK, strJSON);
1132 return true;
1133 }
1134 default: {
1135 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1136 }
1137 }
1138}
1139
1140static bool rest_blockhash_by_height(const std::any& context, HTTPRequest* req,
1141 const std::string& str_uri_part)
1142{
1143 if (!CheckWarmup(req)) return false;
1144 std::string height_str;
1145 const RESTResponseFormat rf = ParseDataFormat(height_str, str_uri_part);
1146
1147 const auto blockheight{ToIntegral<int32_t>(height_str)};
1148 if (!blockheight || *blockheight < 0) {
1149 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid height: " + SanitizeString(height_str, SAFE_CHARS_URI));
1150 }
1151
1152 CBlockIndex* pblockindex = nullptr;
1153 {
1154 ChainstateManager* maybe_chainman = GetChainman(context, req);
1155 if (!maybe_chainman) return false;
1156 ChainstateManager& chainman = *maybe_chainman;
1157 LOCK(cs_main);
1158 const CChain& active_chain = chainman.ActiveChain();
1159 if (*blockheight > active_chain.Height()) {
1160 return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range");
1161 }
1162 pblockindex = active_chain[*blockheight];
1163 }
1164 switch (rf) {
1166 DataStream ss_blockhash{};
1167 ss_blockhash << pblockindex->GetBlockHash();
1168 // Do not cache because reorgs can change the response.
1169 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1170 req->WriteHeader("Content-Type", "application/octet-stream");
1171 req->WriteReply(HTTP_OK, ss_blockhash);
1172 return true;
1173 }
1175 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1176 req->WriteHeader("Content-Type", "text/plain");
1177 req->WriteReply(HTTP_OK, pblockindex->GetBlockHash().GetHex() + "\n");
1178 return true;
1179 }
1181 req->WriteHeader("Cache-Control", REST_CACHE_NO_STORE);
1182 req->WriteHeader("Content-Type", "application/json");
1184 resp.pushKV("blockhash", pblockindex->GetBlockHash().GetHex());
1185 req->WriteReply(HTTP_OK, resp.write() + "\n");
1186 return true;
1187 }
1188 default: {
1189 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
1190 }
1191 }
1192}
1193
1194static const struct {
1195 const char* prefix;
1196 bool (*handler)(const std::any& context, HTTPRequest* req, const std::string& strReq);
1197} uri_prefixes[] = {
1198 {"/rest/tx/", rest_tx},
1199 {"/rest/block/notxdetails/", rest_block_notxdetails},
1200 {"/rest/block/", rest_block_extended},
1201 {"/rest/blockpart/", rest_block_part},
1202 {"/rest/blockfilter/", rest_block_filter},
1203 {"/rest/blockfilterheaders/", rest_filter_header},
1204 {"/rest/chaininfo", rest_chaininfo},
1205 {"/rest/mempool/", rest_mempool},
1206 {"/rest/headers/", rest_headers},
1207 {"/rest/getutxos", rest_getutxos},
1208 {"/rest/deploymentinfo/", rest_deploymentinfo},
1209 {"/rest/deploymentinfo", rest_deploymentinfo},
1210 {"/rest/blockhashbyheight/", rest_blockhash_by_height},
1211 {"/rest/spenttxouts/", rest_spent_txouts},
1213
1214void StartREST(const std::any& context)
1215{
1216 for (const auto& up : uri_prefixes) {
1217 auto handler = [context, up](HTTPRequest* req, const std::string& prefix) { return up.handler(context, req, prefix); };
1218 RegisterHTTPHandler(up.prefix, false, handler);
1219 }
1220}
1221
1223{
1224}
1225
1227{
1228 for (const auto& up : uri_prefixes) {
1229 UnregisterHTTPHandler(up.prefix, false);
1230 }
1231}
int ret
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
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
Definition chain.h:69
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition chain.h:75
#define STR_INTERNAL_BUG(msg)
Definition check.h:99
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
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition chain.h:250
uint256 GetBlockHash() const
Definition chain.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition chain.h:106
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition chain.h:163
Undo information for a CBlock.
Definition undo.h:64
std::vector< CTxUndo > vtxundo
Definition undo.h:66
An in-memory indexed chain of blocks.
Definition chain.h:380
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
Definition chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition chain.h:396
CBlockIndex * Next(const CBlockIndex &index) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition chain.h:416
int Height() const
Return the maximal height in the chain.
Definition chain.h:425
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:777
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:187
An output of a transaction.
CScript scriptPubKey
CAmount nValue
Undo information for a CTransaction.
Definition undo.h:54
std::vector< Coin > vprevout
Definition undo.h:57
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
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const Consensus::Params & GetConsensus() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A UTXO entry.
Definition coins.h:46
CTxOut out
unspent transaction output
Definition coins.h:49
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:191
void WriteReply(HTTPStatusCode status, std::span< const std::byte > reply_body={})
UniValue params
Definition request.h:59
std::any context
Definition request.h:64
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition util.cpp:644
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
UniValue()
Definition univalue.h:31
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:125
std::string GetHex() const
Definition uint256.cpp:11
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
constexpr uint256()=default
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.
Definition core_io.h:32
@ SHOW_TXID
Only TXID for each block's transaction.
Definition core_io.h:30
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 StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition rest.cpp:1214
void StopREST()
Stop HTTP REST subsystem.
Definition rest.cpp:1226
void InterruptREST()
Interrupt RPC REST subsystem.
Definition rest.cpp:1222
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.
HTTPRequest req
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
std::vector< T > Split(std::span< const char > sp LIFETIMEBOUND, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
Definition string.h:120
T * AnyPtr(const std::any &any) noexcept
Helper function to access the contained object of a std::any instance.
Definition any.h:18
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:504
CTransactionRef GetTransaction(const CBlockIndex *block_index, const CTxMemPool *mempool, const Txid &hash, const BlockManager &blockman, uint256 &hashBlock)
Return transaction with a given hash.
static bool rest_blockhash_by_height(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition rest.cpp:1140
static bool rest_block_part(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:514
static const struct @241067227063174173171120277006046215202134064040 uri_prefixes[]
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:659
static bool rest_block_notxdetails(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:509
static bool rest_filter_header(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:533
static bool rest_getutxos(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:943
static bool rest_tx(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:882
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:419
static const struct @100340210357045130265072364121206334104121063345 rf_names[]
static bool rest_deploymentinfo(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition rest.cpp:784
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:825
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:756
RPCMethod getdeploymentinfo()
static bool rest_spent_txouts(const std::any &context, HTTPRequest *req, const std::string &uri_part)
Definition rest.cpp:340
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:1108
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
Definition mempool.cpp:639
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:708
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
std::optional< T > ToIntegral(std::string_view str, size_t base=10)
Convert string to integral type T.
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986).
RESTResponseFormat rf
const char * name
bool(*) handler(const std::any &context, HTTPRequest *req, const std::string &strReq)
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
#define LOCK2(cs1, cs2)
Definition sync.h:269
#define LOCK(cs)
Definition sync.h:268
#define WITH_LOCK(cs, code)
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:41
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
assert(!tx.IsCoinBase())