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