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