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