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