Coverage Report

Created: 2026-07-23 20:35

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