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