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