Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-05-28 15:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/rpc/blockchain.cpp
Line
Count
Source
1
// Copyright (c) 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 <rpc/blockchain.h>
7
8
#include <blockfilter.h>
9
#include <chain.h>
10
#include <chainparams.h>
11
#include <chainparamsbase.h>
12
#include <clientversion.h>
13
#include <coins.h>
14
#include <common/args.h>
15
#include <consensus/amount.h>
16
#include <consensus/params.h>
17
#include <consensus/validation.h>
18
#include <core_io.h>
19
#include <deploymentinfo.h>
20
#include <deploymentstatus.h>
21
#include <flatfile.h>
22
#include <hash.h>
23
#include <index/blockfilterindex.h>
24
#include <index/coinstatsindex.h>
25
#include <interfaces/mining.h>
26
#include <kernel/coinstats.h>
27
#include <logging/timer.h>
28
#include <net.h>
29
#include <net_processing.h>
30
#include <node/blockstorage.h>
31
#include <node/context.h>
32
#include <node/transaction.h>
33
#include <node/utxo_snapshot.h>
34
#include <node/warnings.h>
35
#include <primitives/transaction.h>
36
#include <rpc/server.h>
37
#include <rpc/server_util.h>
38
#include <rpc/util.h>
39
#include <script/descriptor.h>
40
#include <serialize.h>
41
#include <streams.h>
42
#include <sync.h>
43
#include <tinyformat.h>
44
#include <txdb.h>
45
#include <txmempool.h>
46
#include <undo.h>
47
#include <univalue.h>
48
#include <util/check.h>
49
#include <util/fs.h>
50
#include <util/strencodings.h>
51
#include <util/syserror.h>
52
#include <util/translation.h>
53
#include <validation.h>
54
#include <validationinterface.h>
55
#include <versionbits.h>
56
57
#include <cstdint>
58
59
#include <condition_variable>
60
#include <iterator>
61
#include <memory>
62
#include <mutex>
63
#include <optional>
64
#include <string>
65
#include <string_view>
66
#include <vector>
67
68
using kernel::CCoinsStats;
69
using kernel::CoinStatsHashType;
70
71
using interfaces::BlockRef;
72
using interfaces::Mining;
73
using node::BlockManager;
74
using node::NodeContext;
75
using node::SnapshotMetadata;
76
using util::MakeUnorderedList;
77
78
std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex*>
79
PrepareUTXOSnapshot(
80
    Chainstate& chainstate,
81
    const std::function<void()>& interruption_point = {})
82
    EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
83
84
UniValue WriteUTXOSnapshot(
85
    Chainstate& chainstate,
86
    CCoinsViewCursor* pcursor,
87
    CCoinsStats* maybe_stats,
88
    const CBlockIndex* tip,
89
    AutoFile&& afile,
90
    const fs::path& path,
91
    const fs::path& temppath,
92
    const std::function<void()>& interruption_point = {});
93
94
/* Calculate the difficulty for a given block index.
95
 */
96
double GetDifficulty(const CBlockIndex& blockindex)
97
0
{
98
0
    int nShift = (blockindex.nBits >> 24) & 0xff;
99
0
    double dDiff =
100
0
        (double)0x0000ffff / (double)(blockindex.nBits & 0x00ffffff);
101
102
0
    while (nShift < 29)
103
0
    {
104
0
        dDiff *= 256.0;
105
0
        nShift++;
106
0
    }
107
0
    while (nShift > 29)
108
0
    {
109
0
        dDiff /= 256.0;
110
0
        nShift--;
111
0
    }
112
113
0
    return dDiff;
114
0
}
115
116
static int ComputeNextBlockAndDepth(const CBlockIndex& tip, const CBlockIndex& blockindex, const CBlockIndex*& next)
117
0
{
118
0
    next = tip.GetAncestor(blockindex.nHeight + 1);
119
0
    if (next && next->pprev == &blockindex) {
120
0
        return tip.nHeight - blockindex.nHeight + 1;
121
0
    }
122
0
    next = nullptr;
123
0
    return &blockindex == &tip ? 1 : -1;
124
0
}
125
126
static const CBlockIndex* ParseHashOrHeight(const UniValue& param, ChainstateManager& chainman)
127
0
{
128
0
    LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
129
0
    CChain& active_chain = chainman.ActiveChain();
130
131
0
    if (param.isNum()) {
132
0
        const int height{param.getInt<int>()};
133
0
        if (height < 0) {
134
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
Line
Count
Source
1172
0
#define strprintf tfm::format
135
0
        }
136
0
        const int current_tip{active_chain.Height()};
137
0
        if (height > current_tip) {
138
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
Line
Count
Source
1172
0
#define strprintf tfm::format
139
0
        }
140
141
0
        return active_chain[height];
142
0
    } else {
143
0
        const uint256 hash{ParseHashV(param, "hash_or_height")};
144
0
        const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
145
146
0
        if (!pindex) {
147
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
148
0
        }
149
150
0
        return pindex;
151
0
    }
152
0
}
153
154
UniValue blockheaderToJSON(const CBlockIndex& tip, const CBlockIndex& blockindex, const uint256 pow_limit)
155
0
{
156
    // Serialize passed information without accessing chain state of the active chain!
157
0
    AssertLockNotHeld(cs_main); // For performance reasons
Line
Count
Source
149
0
#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
158
159
0
    UniValue result(UniValue::VOBJ);
160
0
    result.pushKV("hash", blockindex.GetBlockHash().GetHex());
161
0
    const CBlockIndex* pnext;
162
0
    int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
163
0
    result.pushKV("confirmations", confirmations);
164
0
    result.pushKV("height", blockindex.nHeight);
165
0
    result.pushKV("version", blockindex.nVersion);
166
0
    result.pushKV("versionHex", strprintf("%08x", blockindex.nVersion));
Line
Count
Source
1172
0
#define strprintf tfm::format
167
0
    result.pushKV("merkleroot", blockindex.hashMerkleRoot.GetHex());
168
0
    result.pushKV("time", blockindex.nTime);
169
0
    result.pushKV("mediantime", blockindex.GetMedianTimePast());
170
0
    result.pushKV("nonce", blockindex.nNonce);
171
0
    result.pushKV("bits", strprintf("%08x", blockindex.nBits));
Line
Count
Source
1172
0
#define strprintf tfm::format
172
0
    result.pushKV("target", GetTarget(blockindex, pow_limit).GetHex());
173
0
    result.pushKV("difficulty", GetDifficulty(blockindex));
174
0
    result.pushKV("chainwork", blockindex.nChainWork.GetHex());
175
0
    result.pushKV("nTx", blockindex.nTx);
176
177
0
    if (blockindex.pprev)
178
0
        result.pushKV("previousblockhash", blockindex.pprev->GetBlockHash().GetHex());
179
0
    if (pnext)
180
0
        result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
181
0
    return result;
182
0
}
183
184
/** Serialize coinbase transaction metadata */
185
UniValue coinbaseTxToJSON(const CTransaction& coinbase_tx)
186
0
{
187
0
    CHECK_NONFATAL(!coinbase_tx.vin.empty());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
188
0
    const CTxIn& vin_0{coinbase_tx.vin[0]};
189
0
    UniValue coinbase_tx_obj(UniValue::VOBJ);
190
0
    coinbase_tx_obj.pushKV("version", coinbase_tx.version);
191
0
    coinbase_tx_obj.pushKV("locktime", coinbase_tx.nLockTime);
192
0
    coinbase_tx_obj.pushKV("sequence", vin_0.nSequence);
193
0
    coinbase_tx_obj.pushKV("coinbase", HexStr(vin_0.scriptSig));
194
0
    const auto& witness_stack{vin_0.scriptWitness.stack};
195
0
    if (!witness_stack.empty()) {
196
0
        CHECK_NONFATAL(witness_stack.size() == 1);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
197
0
        coinbase_tx_obj.pushKV("witness", HexStr(witness_stack[0]));
198
0
    }
199
0
    return coinbase_tx_obj;
200
0
}
201
202
UniValue blockToJSON(BlockManager& blockman, const CBlock& block, const CBlockIndex& tip, const CBlockIndex& blockindex, TxVerbosity verbosity, const uint256 pow_limit)
203
0
{
204
0
    UniValue result = blockheaderToJSON(tip, blockindex, pow_limit);
205
206
0
    result.pushKV("strippedsize", ::GetSerializeSize(TX_NO_WITNESS(block)));
207
0
    result.pushKV("size", ::GetSerializeSize(TX_WITH_WITNESS(block)));
208
0
    result.pushKV("weight", ::GetBlockWeight(block));
209
210
0
    CHECK_NONFATAL(!block.vtx.empty());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
211
0
    result.pushKV("coinbase_tx", coinbaseTxToJSON(*block.vtx[0]));
212
213
0
    UniValue txs(UniValue::VARR);
214
0
    txs.reserve(block.vtx.size());
215
216
0
    switch (verbosity) {
217
0
        case TxVerbosity::SHOW_TXID:
218
0
            for (const CTransactionRef& tx : block.vtx) {
219
0
                txs.push_back(tx->GetHash().GetHex());
220
0
            }
221
0
            break;
222
223
0
        case TxVerbosity::SHOW_DETAILS:
224
0
        case TxVerbosity::SHOW_DETAILS_AND_PREVOUT:
225
0
            CBlockUndo blockUndo;
226
0
            const bool is_not_pruned{WITH_LOCK(::cs_main, return !blockman.IsBlockPruned(blockindex))};
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
227
0
            bool have_undo{is_not_pruned && WITH_LOCK(::cs_main, return blockindex.nStatus & BLOCK_HAVE_UNDO)};
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
228
0
            if (have_undo && !blockman.ReadBlockUndo(blockUndo, blockindex)) {
229
0
                throw JSONRPCError(RPC_INTERNAL_ERROR, "Undo data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
230
0
            }
231
0
            for (size_t i = 0; i < block.vtx.size(); ++i) {
232
0
                const CTransactionRef& tx = block.vtx.at(i);
233
                // coinbase transaction (i.e. i == 0) doesn't have undo data
234
0
                const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.vtxundo.at(i - 1) : nullptr;
235
0
                UniValue objTx(UniValue::VOBJ);
236
0
                TxToUniv(*tx, /*block_hash=*/uint256(), /*entry=*/objTx, /*include_hex=*/true, txundo, verbosity);
237
0
                txs.push_back(std::move(objTx));
238
0
            }
239
0
            break;
240
0
    }
241
242
0
    result.pushKV("tx", std::move(txs));
243
244
0
    return result;
245
0
}
246
247
static RPCMethod getblockcount()
248
0
{
249
0
    return RPCMethod{
250
0
        "getblockcount",
251
0
        "Returns the height of the most-work fully-validated chain.\n"
252
0
                "The genesis block has height 0.\n",
253
0
                {},
254
0
                RPCResult{
255
0
                    RPCResult::Type::NUM, "", "The current block count"},
256
0
                RPCExamples{
257
0
                    HelpExampleCli("getblockcount", "")
258
0
            + HelpExampleRpc("getblockcount", "")
259
0
                },
260
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
261
0
{
262
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
263
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
264
0
    return chainman.ActiveChain().Height();
265
0
},
266
0
    };
267
0
}
268
269
static RPCMethod getbestblockhash()
270
0
{
271
0
    return RPCMethod{
272
0
        "getbestblockhash",
273
0
        "Returns the hash of the best (tip) block in the most-work fully-validated chain.\n",
274
0
                {},
275
0
                RPCResult{
276
0
                    RPCResult::Type::STR_HEX, "", "the block hash, hex-encoded"},
277
0
                RPCExamples{
278
0
                    HelpExampleCli("getbestblockhash", "")
279
0
            + HelpExampleRpc("getbestblockhash", "")
280
0
                },
281
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
282
0
{
283
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
284
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
285
0
    return chainman.ActiveChain().Tip()->GetBlockHash().GetHex();
286
0
},
287
0
    };
288
0
}
289
290
static RPCMethod waitfornewblock()
291
0
{
292
0
    return RPCMethod{
293
0
        "waitfornewblock",
294
0
        "Waits for any new block and returns useful info about it.\n"
295
0
                "\nReturns the current block on timeout or exit.\n"
296
0
                "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
297
0
                {
298
0
                    {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
299
0
                    {"current_tip", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "Method waits for the chain tip to differ from this."},
300
0
                },
301
0
                RPCResult{
302
0
                    RPCResult::Type::OBJ, "", "",
303
0
                    {
304
0
                        {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
305
0
                        {RPCResult::Type::NUM, "height", "Block height"},
306
0
                    }},
307
0
                RPCExamples{
308
0
                    HelpExampleCli("waitfornewblock", "1000")
309
0
            + HelpExampleRpc("waitfornewblock", "1000")
310
0
                },
311
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
312
0
{
313
0
    int timeout = 0;
314
0
    if (!request.params[0].isNull())
315
0
        timeout = request.params[0].getInt<int>();
316
0
    if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
317
318
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
319
0
    Mining& miner = EnsureMining(node);
320
321
    // If the caller provided a current_tip value, pass it to waitTipChanged().
322
    //
323
    // If the caller did not provide a current tip hash, call getTip() to get
324
    // one and wait for the tip to be different from this value. This mode is
325
    // less reliable because if the tip changed between waitfornewblock calls,
326
    // it will need to change a second time before this call returns.
327
0
    BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
328
329
0
    uint256 tip_hash{request.params[1].isNull()
330
0
        ? current_block.hash
331
0
        : ParseHashV(request.params[1], "current_tip")};
332
333
    // If the user provided an invalid current_tip then this call immediately
334
    // returns the current tip.
335
0
    std::optional<BlockRef> block = timeout ? miner.waitTipChanged(tip_hash, std::chrono::milliseconds(timeout)) :
336
0
                                              miner.waitTipChanged(tip_hash);
337
338
    // Return current block upon shutdown
339
0
    if (block) current_block = *block;
340
341
0
    UniValue ret(UniValue::VOBJ);
342
0
    ret.pushKV("hash", current_block.hash.GetHex());
343
0
    ret.pushKV("height", current_block.height);
344
0
    return ret;
345
0
},
346
0
    };
347
0
}
348
349
static RPCMethod waitforblock()
350
0
{
351
0
    return RPCMethod{
352
0
        "waitforblock",
353
0
        "Waits for a specific new block and returns useful info about it.\n"
354
0
                "\nReturns the current block on timeout or exit.\n"
355
0
                "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
356
0
                {
357
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Block hash to wait for."},
358
0
                    {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
359
0
                },
360
0
                RPCResult{
361
0
                    RPCResult::Type::OBJ, "", "",
362
0
                    {
363
0
                        {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
364
0
                        {RPCResult::Type::NUM, "height", "Block height"},
365
0
                    }},
366
0
                RPCExamples{
367
0
                    HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
368
0
            + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
369
0
                },
370
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
371
0
{
372
0
    int timeout = 0;
373
374
0
    uint256 hash(ParseHashV(request.params[0], "blockhash"));
375
376
0
    if (!request.params[1].isNull())
377
0
        timeout = request.params[1].getInt<int>();
378
0
    if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
379
380
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
381
0
    Mining& miner = EnsureMining(node);
382
383
    // Abort if RPC came out of warmup too early
384
0
    BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
385
386
0
    const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
387
0
    while (current_block.hash != hash) {
388
0
        std::optional<BlockRef> block;
389
0
        if (timeout) {
390
0
            auto now{std::chrono::steady_clock::now()};
391
0
            if (now >= deadline) break;
392
0
            const MillisecondsDouble remaining{deadline - now};
393
0
            block = miner.waitTipChanged(current_block.hash, remaining);
394
0
        } else {
395
0
            block = miner.waitTipChanged(current_block.hash);
396
0
        }
397
        // Return current block upon shutdown
398
0
        if (!block) break;
399
0
        current_block = *block;
400
0
    }
401
402
0
    UniValue ret(UniValue::VOBJ);
403
0
    ret.pushKV("hash", current_block.hash.GetHex());
404
0
    ret.pushKV("height", current_block.height);
405
0
    return ret;
406
0
},
407
0
    };
408
0
}
409
410
static RPCMethod waitforblockheight()
411
0
{
412
0
    return RPCMethod{
413
0
        "waitforblockheight",
414
0
        "Waits for (at least) block height and returns the height and hash\n"
415
0
                "of the current tip.\n"
416
0
                "\nReturns the current block on timeout or exit.\n"
417
0
                "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
418
0
                {
419
0
                    {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Block height to wait for."},
420
0
                    {"timeout", RPCArg::Type::NUM, RPCArg::Default{0}, "Time in milliseconds to wait for a response. 0 indicates no timeout."},
421
0
                },
422
0
                RPCResult{
423
0
                    RPCResult::Type::OBJ, "", "",
424
0
                    {
425
0
                        {RPCResult::Type::STR_HEX, "hash", "The blockhash"},
426
0
                        {RPCResult::Type::NUM, "height", "Block height"},
427
0
                    }},
428
0
                RPCExamples{
429
0
                    HelpExampleCli("waitforblockheight", "100 1000")
430
0
            + HelpExampleRpc("waitforblockheight", "100, 1000")
431
0
                },
432
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
433
0
{
434
0
    int timeout = 0;
435
436
0
    int height = request.params[0].getInt<int>();
437
438
0
    if (!request.params[1].isNull())
439
0
        timeout = request.params[1].getInt<int>();
440
0
    if (timeout < 0) throw JSONRPCError(RPC_MISC_ERROR, "Negative timeout");
441
442
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
443
0
    Mining& miner = EnsureMining(node);
444
445
    // Abort if RPC came out of warmup too early
446
0
    BlockRef current_block{CHECK_NONFATAL(miner.getTip()).value()};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
447
448
0
    const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
449
450
0
    while (current_block.height < height) {
451
0
        std::optional<BlockRef> block;
452
0
        if (timeout) {
453
0
            auto now{std::chrono::steady_clock::now()};
454
0
            if (now >= deadline) break;
455
0
            const MillisecondsDouble remaining{deadline - now};
456
0
            block = miner.waitTipChanged(current_block.hash, remaining);
457
0
        } else {
458
0
            block = miner.waitTipChanged(current_block.hash);
459
0
        }
460
        // Return current block on shutdown
461
0
        if (!block) break;
462
0
        current_block = *block;
463
0
    }
464
465
0
    UniValue ret(UniValue::VOBJ);
466
0
    ret.pushKV("hash", current_block.hash.GetHex());
467
0
    ret.pushKV("height", current_block.height);
468
0
    return ret;
469
0
},
470
0
    };
471
0
}
472
473
static RPCMethod syncwithvalidationinterfacequeue()
474
0
{
475
0
    return RPCMethod{
476
0
        "syncwithvalidationinterfacequeue",
477
0
        "Waits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
478
0
                {},
479
0
                RPCResult{RPCResult::Type::NONE, "", ""},
480
0
                RPCExamples{
481
0
                    HelpExampleCli("syncwithvalidationinterfacequeue","")
482
0
            + HelpExampleRpc("syncwithvalidationinterfacequeue","")
483
0
                },
484
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
485
0
{
486
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
487
0
    CHECK_NONFATAL(node.validation_signals)->SyncWithValidationInterfaceQueue();
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
488
0
    return UniValue::VNULL;
489
0
},
490
0
    };
491
0
}
492
493
static RPCMethod getdifficulty()
494
0
{
495
0
    return RPCMethod{
496
0
        "getdifficulty",
497
0
        "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
498
0
                {},
499
0
                RPCResult{
500
0
                    RPCResult::Type::NUM, "", "the proof-of-work difficulty as a multiple of the minimum difficulty."},
501
0
                RPCExamples{
502
0
                    HelpExampleCli("getdifficulty", "")
503
0
            + HelpExampleRpc("getdifficulty", "")
504
0
                },
505
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
506
0
{
507
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
508
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
509
0
    return GetDifficulty(*CHECK_NONFATAL(chainman.ActiveChain().Tip()));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
510
0
},
511
0
    };
512
0
}
513
514
static RPCMethod getblockfrompeer()
515
0
{
516
0
    return RPCMethod{
517
0
        "getblockfrompeer",
518
0
        "Attempt to fetch block from a given peer.\n\n"
519
0
        "We must have the header for this block, e.g. using submitheader.\n"
520
0
        "The block will not have any undo data which can limit the usage of the block data in a context where the undo data is needed.\n"
521
0
        "Subsequent calls for the same block may cause the response from the previous peer to be ignored.\n"
522
0
        "Peers generally ignore requests for a stale block that they never fully verified, or one that is more than a month old.\n"
523
0
        "When a peer does not respond with a block, we will disconnect.\n"
524
0
        "Note: The block could be re-pruned as soon as it is received.\n\n"
525
0
        "Returns an empty JSON object if the request was successfully scheduled.",
526
0
        {
527
0
            {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash to try to fetch"},
528
0
            {"peer_id", RPCArg::Type::NUM, RPCArg::Optional::NO, "The peer to fetch it from (see getpeerinfo for peer IDs)"},
529
0
        },
530
0
        RPCResult{RPCResult::Type::OBJ, "", /*optional=*/false, "", {}},
531
0
        RPCExamples{
532
0
            HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
533
0
            + HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
534
0
        },
535
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
536
0
{
537
0
    const NodeContext& node = EnsureAnyNodeContext(request.context);
538
0
    ChainstateManager& chainman = EnsureChainman(node);
539
0
    PeerManager& peerman = EnsurePeerman(node);
540
541
0
    const uint256& block_hash{ParseHashV(request.params[0], "blockhash")};
542
0
    const NodeId peer_id{request.params[1].getInt<int64_t>()};
543
544
0
    const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(block_hash););
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
545
546
0
    if (!index) {
547
0
        throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
548
0
    }
549
550
    // Fetching blocks before the node has syncing past their height can prevent block files from
551
    // being pruned, so we avoid it if the node is in prune mode.
552
0
    if (chainman.m_blockman.IsPruneMode() && index->nHeight > WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()->nHeight)) {
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
553
0
        throw JSONRPCError(RPC_MISC_ERROR, "In prune mode, only blocks that the node has already synced previously can be fetched from a peer");
554
0
    }
555
556
0
    const bool block_has_data = WITH_LOCK(::cs_main, return index->nStatus & BLOCK_HAVE_DATA);
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
557
0
    if (block_has_data) {
558
0
        throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
559
0
    }
560
561
0
    if (const auto res{peerman.FetchBlock(peer_id, *index)}; !res) {
562
0
        throw JSONRPCError(RPC_MISC_ERROR, res.error());
563
0
    }
564
0
    return UniValue::VOBJ;
565
0
},
566
0
    };
567
0
}
568
569
static RPCMethod getblockhash()
570
0
{
571
0
    return RPCMethod{
572
0
        "getblockhash",
573
0
        "Returns hash of block in best-block-chain at height provided.\n",
574
0
                {
575
0
                    {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The height index"},
576
0
                },
577
0
                RPCResult{
578
0
                    RPCResult::Type::STR_HEX, "", "The block hash"},
579
0
                RPCExamples{
580
0
                    HelpExampleCli("getblockhash", "1000")
581
0
            + HelpExampleRpc("getblockhash", "1000")
582
0
                },
583
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
584
0
{
585
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
586
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
587
0
    const CChain& active_chain = chainman.ActiveChain();
588
589
0
    int nHeight = request.params[0].getInt<int>();
590
0
    if (nHeight < 0 || nHeight > active_chain.Height())
591
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
592
593
0
    const CBlockIndex* pblockindex = active_chain[nHeight];
594
0
    return pblockindex->GetBlockHash().GetHex();
595
0
},
596
0
    };
597
0
}
598
599
static RPCMethod getblockheader()
600
0
{
601
0
    return RPCMethod{
602
0
        "getblockheader",
603
0
        "If verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
604
0
                "If verbose is true, returns an Object with information about blockheader <hash>.\n",
605
0
                {
606
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
607
0
                    {"verbose", RPCArg::Type::BOOL, RPCArg::Default{true}, "true for a json object, false for the hex-encoded data"},
608
0
                },
609
0
                {
610
0
                    RPCResult{"for verbose = true",
611
0
                        RPCResult::Type::OBJ, "", "",
612
0
                        {
613
0
                            {RPCResult::Type::STR_HEX, "hash", "the block hash (same as provided)"},
614
0
                            {RPCResult::Type::NUM, "confirmations", "The number of confirmations, or -1 if the block is not on the main chain"},
615
0
                            {RPCResult::Type::NUM, "height", "The block height or index"},
616
0
                            {RPCResult::Type::NUM, "version", "The block version"},
617
0
                            {RPCResult::Type::STR_HEX, "versionHex", "The block version formatted in hexadecimal"},
618
0
                            {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
619
0
                            {RPCResult::Type::NUM_TIME, "time", "The block time expressed in " + UNIX_EPOCH_TIME},
620
0
                            {RPCResult::Type::NUM_TIME, "mediantime", "The median block time expressed in " + UNIX_EPOCH_TIME},
621
0
                            {RPCResult::Type::NUM, "nonce", "The nonce"},
622
0
                            {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
623
0
                            {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
624
0
                            {RPCResult::Type::NUM, "difficulty", "The difficulty"},
625
0
                            {RPCResult::Type::STR_HEX, "chainwork", "Expected number of hashes required to produce the current chain"},
626
0
                            {RPCResult::Type::NUM, "nTx", "The number of transactions in the block"},
627
0
                            {RPCResult::Type::STR_HEX, "previousblockhash", /*optional=*/true, "The hash of the previous block (if available)"},
628
0
                            {RPCResult::Type::STR_HEX, "nextblockhash", /*optional=*/true, "The hash of the next block (if available)"},
629
0
                        }},
630
0
                    RPCResult{"for verbose=false",
631
0
                        RPCResult::Type::STR_HEX, "", "A string that is serialized, hex-encoded data for block 'hash'"},
632
0
                },
633
0
                RPCExamples{
634
0
                    HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
635
0
            + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
636
0
                },
637
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
638
0
{
639
0
    uint256 hash(ParseHashV(request.params[0], "hash"));
640
641
0
    bool fVerbose = true;
642
0
    if (!request.params[1].isNull())
643
0
        fVerbose = request.params[1].get_bool();
644
645
0
    const CBlockIndex* pblockindex;
646
0
    const CBlockIndex* tip;
647
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
648
0
    {
649
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
650
0
        pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
651
0
        tip = chainman.ActiveChain().Tip();
652
0
    }
653
654
0
    if (!pblockindex) {
655
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
656
0
    }
657
658
0
    if (!fVerbose)
659
0
    {
660
0
        DataStream ssBlock{};
661
0
        ssBlock << pblockindex->GetBlockHeader();
662
0
        std::string strHex = HexStr(ssBlock);
663
0
        return strHex;
664
0
    }
665
666
0
    return blockheaderToJSON(*tip, *pblockindex, chainman.GetConsensus().powLimit);
667
0
},
668
0
    };
669
0
}
670
671
void CheckBlockDataAvailability(BlockManager& blockman, const CBlockIndex& blockindex, bool check_for_undo)
672
0
{
673
0
    AssertLockHeld(cs_main);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
674
0
    uint32_t flag = check_for_undo ? BLOCK_HAVE_UNDO : BLOCK_HAVE_DATA;
675
0
    if (!(blockindex.nStatus & flag)) {
676
0
        if (blockman.IsBlockPruned(blockindex)) {
677
0
            throw JSONRPCError(RPC_MISC_ERROR, strprintf("%s not available (pruned data)", check_for_undo ? "Undo data" : "Block"));
Line
Count
Source
1172
0
#define strprintf tfm::format
678
0
        }
679
0
        if (check_for_undo) {
680
0
            throw JSONRPCError(RPC_MISC_ERROR, "Undo data not available");
681
0
        }
682
0
        throw JSONRPCError(RPC_MISC_ERROR, "Block not available (not fully downloaded)");
683
0
    }
684
0
}
685
686
static CBlock GetBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
687
0
{
688
0
    CBlock block;
689
0
    {
690
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
691
0
        CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
692
0
    }
693
694
0
    if (!blockman.ReadBlock(block, blockindex)) {
695
        // Block not found on disk. This shouldn't normally happen unless the block was
696
        // pruned right after we released the lock above.
697
0
        throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
698
0
    }
699
700
0
    return block;
701
0
}
702
703
static std::vector<std::byte> GetRawBlockChecked(BlockManager& blockman, const CBlockIndex& blockindex)
704
0
{
705
0
    FlatFilePos pos{};
706
0
    {
707
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
708
0
        CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/false);
709
0
        pos = blockindex.GetBlockPos();
710
0
    }
711
712
0
    if (auto data{blockman.ReadRawBlock(pos)}) return std::move(*data);
713
    // Block not found on disk. This shouldn't normally happen unless the block was
714
    // pruned right after we released the lock above.
715
0
    throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
716
0
}
717
718
static CBlockUndo GetUndoChecked(BlockManager& blockman, const CBlockIndex& blockindex)
719
0
{
720
0
    CBlockUndo blockUndo;
721
722
    // The Genesis block does not have undo data
723
0
    if (blockindex.nHeight == 0) return blockUndo;
724
725
0
    {
726
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
727
0
        CheckBlockDataAvailability(blockman, blockindex, /*check_for_undo=*/true);
728
0
    }
729
730
0
    if (!blockman.ReadBlockUndo(blockUndo, blockindex)) {
731
0
        throw JSONRPCError(RPC_MISC_ERROR, "Can't read undo data from disk");
732
0
    }
733
734
0
    return blockUndo;
735
0
}
736
737
const RPCResult& GetBlockVin()
738
0
{
739
0
    static const RPCResult getblock_vin{
740
0
        RPCResult::Type::ARR, "vin", "",
741
0
        {
742
0
            {RPCResult::Type::OBJ, "", "",
743
0
            {
744
0
                {RPCResult::Type::ELISION, "", "The same output as verbosity = 2"},
745
0
                {RPCResult::Type::OBJ, "prevout", "(Only if undo information is available)",
746
0
                {
747
0
                    {RPCResult::Type::BOOL, "generated", "Coinbase or not"},
748
0
                    {RPCResult::Type::NUM, "height", "The height of the prevout"},
749
0
                    {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
750
0
                    {RPCResult::Type::OBJ, "scriptPubKey", "",
751
0
                    {
752
0
                        {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
753
0
                        {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
754
0
                        {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
755
0
                        {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
756
0
                        {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
757
0
                    }},
758
0
                }},
759
0
            }},
760
0
        }
761
0
    };
762
0
    return getblock_vin;
763
0
}
764
765
static RPCMethod getblock()
766
0
{
767
0
    return RPCMethod{
768
0
        "getblock",
769
0
        "If verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
770
0
                "If verbosity is 1, returns an Object with information about block <hash>.\n"
771
0
                "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
772
0
                "If verbosity is 3, returns an Object with information about block <hash> and information about each transaction, including prevout information for inputs (only for unpruned blocks in the current best chain).\n",
773
0
                {
774
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
775
0
                    {"verbosity|verbose", RPCArg::Type::NUM, RPCArg::Default{1}, "0 for hex-encoded data, 1 for a JSON object, 2 for JSON object with transaction data, and 3 for JSON object with transaction data including prevout information for inputs",
776
0
                     RPCArgOptions{.skip_type_check = true}},
777
0
                },
778
0
                {
779
0
                    RPCResult{"for verbosity = 0",
780
0
                RPCResult::Type::STR_HEX, "", "A string that is serialized, hex-encoded data for block 'hash'"},
781
0
                    RPCResult{"for verbosity = 1",
782
0
                RPCResult::Type::OBJ, "", "",
783
0
                {
784
0
                    {RPCResult::Type::STR_HEX, "hash", "the block hash (same as provided)"},
785
0
                    {RPCResult::Type::NUM, "confirmations", "The number of confirmations, or -1 if the block is not on the main chain"},
786
0
                    {RPCResult::Type::NUM, "size", "The block size"},
787
0
                    {RPCResult::Type::NUM, "strippedsize", "The block size excluding witness data"},
788
0
                    {RPCResult::Type::NUM, "weight", "The block weight as defined in BIP 141"},
789
0
                    {RPCResult::Type::OBJ, "coinbase_tx", "Coinbase transaction metadata",
790
0
                    {
791
0
                        {RPCResult::Type::NUM, "version", "The coinbase transaction version"},
792
0
                        {RPCResult::Type::NUM, "locktime", "The coinbase transaction's locktime (nLockTime)"},
793
0
                        {RPCResult::Type::NUM, "sequence", "The coinbase input's sequence number (nSequence)"},
794
0
                        {RPCResult::Type::STR_HEX, "coinbase", "The coinbase input's script"},
795
0
                        {RPCResult::Type::STR_HEX, "witness", /*optional=*/true, "The coinbase input's first (and only) witness stack element, if present"},
796
0
                    }},
797
0
                    {RPCResult::Type::NUM, "height", "The block height or index"},
798
0
                    {RPCResult::Type::NUM, "version", "The block version"},
799
0
                    {RPCResult::Type::STR_HEX, "versionHex", "The block version formatted in hexadecimal"},
800
0
                    {RPCResult::Type::STR_HEX, "merkleroot", "The merkle root"},
801
0
                    {RPCResult::Type::ARR, "tx", "The transaction ids",
802
0
                        {{RPCResult::Type::STR_HEX, "", "The transaction id"}}},
803
0
                    {RPCResult::Type::NUM_TIME, "time",       "The block time expressed in " + UNIX_EPOCH_TIME},
804
0
                    {RPCResult::Type::NUM_TIME, "mediantime", "The median block time expressed in " + UNIX_EPOCH_TIME},
805
0
                    {RPCResult::Type::NUM, "nonce", "The nonce"},
806
0
                    {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
807
0
                    {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
808
0
                    {RPCResult::Type::NUM, "difficulty", "The difficulty"},
809
0
                    {RPCResult::Type::STR_HEX, "chainwork", "Expected number of hashes required to produce the chain up to this block (in hex)"},
810
0
                    {RPCResult::Type::NUM, "nTx", "The number of transactions in the block"},
811
0
                    {RPCResult::Type::STR_HEX, "previousblockhash", /*optional=*/true, "The hash of the previous block (if available)"},
812
0
                    {RPCResult::Type::STR_HEX, "nextblockhash", /*optional=*/true, "The hash of the next block (if available)"},
813
0
                }},
814
0
                    RPCResult{"for verbosity = 2",
815
0
                RPCResult::Type::OBJ, "", "",
816
0
                {
817
0
                    {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
818
0
                    {RPCResult::Type::ARR, "tx", "",
819
0
                    {
820
0
                        {RPCResult::Type::OBJ, "", "",
821
0
                        {
822
0
                            {RPCResult::Type::ELISION, "", "The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
823
0
                            {RPCResult::Type::NUM, "fee", /*optional=*/true, "The transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
824
0
                        }},
825
0
                    }},
826
0
                }},
827
0
                    RPCResult{"for verbosity = 3",
828
0
                RPCResult::Type::OBJ, "", "",
829
0
                {
830
0
                    {RPCResult::Type::ELISION, "", "Same output as verbosity = 2"},
831
0
                    {RPCResult::Type::ARR, "tx", "",
832
0
                    {
833
0
                        {RPCResult::Type::OBJ, "", "",
834
0
                        {
835
0
                            GetBlockVin(),
836
0
                        }},
837
0
                    }},
838
0
                }},
839
0
        },
840
0
                RPCExamples{
841
0
                    HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
842
0
            + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
843
0
                },
844
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
845
0
{
846
0
    uint256 hash(ParseHashV(request.params[0], "blockhash"));
847
848
0
    int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/1, /*allow_bool=*/true)};
849
850
0
    const CBlockIndex* pblockindex;
851
0
    const CBlockIndex* tip;
852
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
853
0
    {
854
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
855
0
        pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
856
0
        tip = chainman.ActiveChain().Tip();
857
858
0
        if (!pblockindex) {
859
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
860
0
        }
861
0
    }
862
863
0
    const std::vector<std::byte> block_data{GetRawBlockChecked(chainman.m_blockman, *pblockindex)};
864
865
0
    if (verbosity <= 0) {
866
0
        return HexStr(block_data);
867
0
    }
868
869
0
    CBlock block{};
870
0
    SpanReader{block_data} >> TX_WITH_WITNESS(block);
871
872
0
    TxVerbosity tx_verbosity;
873
0
    if (verbosity == 1) {
874
0
        tx_verbosity = TxVerbosity::SHOW_TXID;
875
0
    } else if (verbosity == 2) {
876
0
        tx_verbosity = TxVerbosity::SHOW_DETAILS;
877
0
    } else {
878
0
        tx_verbosity = TxVerbosity::SHOW_DETAILS_AND_PREVOUT;
879
0
    }
880
881
0
    return blockToJSON(chainman.m_blockman, block, *tip, *pblockindex, tx_verbosity, chainman.GetConsensus().powLimit);
882
0
},
883
0
    };
884
0
}
885
886
//! Return height of highest block that has been pruned, or std::nullopt if no blocks have been pruned
887
0
std::optional<int> GetPruneHeight(const BlockManager& blockman, const CChain& chain) {
888
0
    AssertLockHeld(::cs_main);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
889
890
    // Search for the last block missing block data or undo data. Don't let the
891
    // search consider the genesis block, because the genesis block does not
892
    // have undo data, but should not be considered pruned.
893
0
    const CBlockIndex* first_block{chain[1]};
894
0
    const CBlockIndex* chain_tip{chain.Tip()};
895
896
    // If there are no blocks after the genesis block, or no blocks at all, nothing is pruned.
897
0
    if (!first_block || !chain_tip) return std::nullopt;
898
899
    // If the chain tip is pruned, everything is pruned.
900
0
    if ((chain_tip->nStatus & BLOCK_HAVE_MASK) != BLOCK_HAVE_MASK) return chain_tip->nHeight;
901
902
0
    const auto& first_unpruned{blockman.GetFirstBlock(*chain_tip, /*status_mask=*/BLOCK_HAVE_MASK, first_block)};
903
0
    if (&first_unpruned == first_block) {
904
        // All blocks between first_block and chain_tip have data, so nothing is pruned.
905
0
        return std::nullopt;
906
0
    }
907
908
    // Block before the first unpruned block is the last pruned block.
909
0
    return CHECK_NONFATAL(first_unpruned.pprev)->nHeight;
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
910
0
}
911
912
static RPCMethod pruneblockchain()
913
0
{
914
0
    return RPCMethod{"pruneblockchain",
915
0
                "Attempts to delete block and undo data up to a specified height or timestamp, if eligible for pruning.\n"
916
0
                "Requires `-prune` to be enabled at startup. While pruned data may be re-fetched in some cases (e.g., via `getblockfrompeer`), local deletion is irreversible.\n",
917
0
                {
918
0
                    {"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block height to prune up to. May be set to a discrete height, or to a " + UNIX_EPOCH_TIME + "\n"
919
0
            "                  to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
920
0
                },
921
0
                RPCResult{
922
0
                    RPCResult::Type::NUM, "", "Height of the last block pruned"},
923
0
                RPCExamples{
924
0
                    HelpExampleCli("pruneblockchain", "1000")
925
0
            + HelpExampleRpc("pruneblockchain", "1000")
926
0
                },
927
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
928
0
{
929
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
930
0
    if (!chainman.m_blockman.IsPruneMode()) {
931
0
        throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
932
0
    }
933
934
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
935
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
936
0
    CChain& active_chain = active_chainstate.m_chain;
937
938
0
    int heightParam = request.params[0].getInt<int>();
939
0
    if (heightParam < 0) {
940
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
941
0
    }
942
943
    // Height value more than a billion is too high to be a block height, and
944
    // too low to be a block time (corresponds to timestamp from Sep 2001).
945
0
    if (heightParam > 1000000000) {
946
        // Add a 2 hour buffer to include blocks which might have had old timestamps
947
0
        const CBlockIndex* pindex = active_chain.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0);
948
0
        if (!pindex) {
949
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
950
0
        }
951
0
        heightParam = pindex->nHeight;
952
0
    }
953
954
0
    unsigned int height = (unsigned int) heightParam;
955
0
    unsigned int chainHeight = (unsigned int) active_chain.Height();
956
0
    if (chainHeight < chainman.GetParams().PruneAfterHeight()) {
957
0
        throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
958
0
    } else if (height > chainHeight) {
959
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
960
0
    } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
961
0
        LogDebug(BCLog::RPC, "Attempt to prune blocks close to the tip.  Retaining the minimum number of blocks.\n");
Line
Count
Source
117
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
108
0
    do {                                                               \
109
0
        if (util::log::ShouldLog((category), (level))) {               \
110
0
            bool rate_limit{level >= BCLog::Level::Info};              \
111
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
112
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
113
0
        }                                                              \
114
0
    } while (0)
962
0
        height = chainHeight - MIN_BLOCKS_TO_KEEP;
963
0
    }
964
965
0
    PruneBlockFilesManual(active_chainstate, height);
966
0
    return GetPruneHeight(chainman.m_blockman, active_chain).value_or(-1);
967
0
},
968
0
    };
969
0
}
970
971
CoinStatsHashType ParseHashType(std::string_view hash_type_input)
972
0
{
973
0
    if (hash_type_input == "hash_serialized_3") {
974
0
        return CoinStatsHashType::HASH_SERIALIZED;
975
0
    } else if (hash_type_input == "muhash") {
976
0
        return CoinStatsHashType::MUHASH;
977
0
    } else if (hash_type_input == "none") {
978
0
        return CoinStatsHashType::NONE;
979
0
    } else {
980
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("'%s' is not a valid hash_type", hash_type_input));
Line
Count
Source
1172
0
#define strprintf tfm::format
981
0
    }
982
0
}
983
984
/**
985
 * Calculate statistics about the unspent transaction output set
986
 *
987
 * @param[in] index_requested Signals if the coinstatsindex should be used (when available).
988
 */
989
static std::optional<kernel::CCoinsStats> GetUTXOStats(CCoinsView* view, node::BlockManager& blockman,
990
                                                       kernel::CoinStatsHashType hash_type,
991
                                                       const std::function<void()>& interruption_point = {},
992
                                                       const CBlockIndex* pindex = nullptr,
993
                                                       bool index_requested = true)
994
0
{
995
    // Use CoinStatsIndex if it is requested and available and a hash_type of Muhash or None was requested
996
0
    if ((hash_type == kernel::CoinStatsHashType::MUHASH || hash_type == kernel::CoinStatsHashType::NONE) && g_coin_stats_index && index_requested) {
997
0
        if (pindex) {
998
0
            return g_coin_stats_index->LookUpStats(*pindex);
999
0
        } else {
1000
0
            CBlockIndex& block_index = *CHECK_NONFATAL(WITH_LOCK(::cs_main, return blockman.LookupBlockIndex(view->GetBestBlock())));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1001
0
            return g_coin_stats_index->LookUpStats(block_index);
1002
0
        }
1003
0
    }
1004
1005
    // If the coinstats index isn't requested or is otherwise not usable, the
1006
    // pindex should either be null or equal to the view's best block. This is
1007
    // because without the coinstats index we can only get coinstats about the
1008
    // best block.
1009
0
    CHECK_NONFATAL(!pindex || pindex->GetBlockHash() == view->GetBestBlock());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1010
1011
0
    return kernel::ComputeUTXOStats(hash_type, view, blockman, interruption_point);
1012
0
}
1013
1014
static RPCMethod gettxoutsetinfo()
1015
0
{
1016
0
    return RPCMethod{
1017
0
        "gettxoutsetinfo",
1018
0
        "Returns statistics about the unspent transaction output set.\n"
1019
0
                "Note this call may take some time if you are not using coinstatsindex.\n",
1020
0
                {
1021
0
                    {"hash_type", RPCArg::Type::STR, RPCArg::Default{"hash_serialized_3"}, "Which UTXO set hash should be calculated. Options: 'hash_serialized_3' (the legacy algorithm), 'muhash', 'none'."},
1022
0
                    {"hash_or_height", RPCArg::Type::NUM, RPCArg::DefaultHint{"the current best block"}, "The block hash or height of the target height (only available with coinstatsindex).",
1023
0
                     RPCArgOptions{
1024
0
                         .skip_type_check = true,
1025
0
                         .type_str = {"", "string or numeric"},
1026
0
                     }},
1027
0
                    {"use_index", RPCArg::Type::BOOL, RPCArg::Default{true}, "Use coinstatsindex, if available."},
1028
0
                },
1029
0
                RPCResult{
1030
0
                    RPCResult::Type::OBJ, "", "",
1031
0
                    {
1032
0
                        {RPCResult::Type::NUM, "height", "The block height (index) of the returned statistics"},
1033
0
                        {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at which these statistics are calculated"},
1034
0
                        {RPCResult::Type::NUM, "txouts", "The number of unspent transaction outputs"},
1035
0
                        {RPCResult::Type::NUM, "bogosize", "Database-independent, meaningless metric indicating the UTXO set size"},
1036
0
                        {RPCResult::Type::STR_HEX, "hash_serialized_3", /*optional=*/true, "The serialized hash (only present if 'hash_serialized_3' hash_type is chosen)"},
1037
0
                        {RPCResult::Type::STR_HEX, "muhash", /*optional=*/true, "The serialized hash (only present if 'muhash' hash_type is chosen)"},
1038
0
                        {RPCResult::Type::NUM, "transactions", /*optional=*/true, "The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1039
0
                        {RPCResult::Type::NUM, "disk_size", /*optional=*/true, "The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1040
0
                        {RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of coins in the UTXO set"},
1041
0
                        {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount", /*optional=*/true, "The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
1042
0
                        {RPCResult::Type::OBJ, "block_info", /*optional=*/true, "Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1043
0
                        {
1044
0
                            {RPCResult::Type::STR_AMOUNT, "prevout_spent", "Total amount of all prevouts spent in this block"},
1045
0
                            {RPCResult::Type::STR_AMOUNT, "coinbase", "Coinbase subsidy amount of this block"},
1046
0
                            {RPCResult::Type::STR_AMOUNT, "new_outputs_ex_coinbase", "Total amount of new outputs created by this block"},
1047
0
                            {RPCResult::Type::STR_AMOUNT, "unspendable", "Total amount of unspendable outputs created in this block"},
1048
0
                            {RPCResult::Type::OBJ, "unspendables", "Detailed view of the unspendable categories",
1049
0
                            {
1050
0
                                {RPCResult::Type::STR_AMOUNT, "genesis_block", "The unspendable amount of the Genesis block subsidy"},
1051
0
                                {RPCResult::Type::STR_AMOUNT, "bip30", "Transactions overridden by duplicates (no longer possible with BIP30)"},
1052
0
                                {RPCResult::Type::STR_AMOUNT, "scripts", "Amounts sent to scripts that are unspendable (for example OP_RETURN outputs)"},
1053
0
                                {RPCResult::Type::STR_AMOUNT, "unclaimed_rewards", "Fee rewards that miners did not claim in their coinbase transaction"},
1054
0
                            }}
1055
0
                        }},
1056
0
                    }},
1057
0
                RPCExamples{
1058
0
                    HelpExampleCli("gettxoutsetinfo", "") +
1059
0
                    HelpExampleCli("gettxoutsetinfo", R"("none")") +
1060
0
                    HelpExampleCli("gettxoutsetinfo", R"("none" 1000)") +
1061
0
                    HelpExampleCli("gettxoutsetinfo", R"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1062
0
                    HelpExampleCli("-named gettxoutsetinfo", R"(hash_type='muhash' use_index='false')") +
1063
0
                    HelpExampleRpc("gettxoutsetinfo", "") +
1064
0
                    HelpExampleRpc("gettxoutsetinfo", R"("none")") +
1065
0
                    HelpExampleRpc("gettxoutsetinfo", R"("none", 1000)") +
1066
0
                    HelpExampleRpc("gettxoutsetinfo", R"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1067
0
                },
1068
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1069
0
{
1070
0
    UniValue ret(UniValue::VOBJ);
1071
1072
0
    const CBlockIndex* pindex{nullptr};
1073
0
    const CoinStatsHashType hash_type{ParseHashType(self.Arg<std::string_view>("hash_type"))};
1074
0
    bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
1075
1076
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
1077
0
    ChainstateManager& chainman = EnsureChainman(node);
1078
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
1079
0
    active_chainstate.ForceFlushStateToDisk(/*wipe_cache=*/false);
1080
1081
0
    CCoinsView* coins_view;
1082
0
    BlockManager* blockman;
1083
0
    {
1084
0
        LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1085
0
        coins_view = &active_chainstate.CoinsDB();
1086
0
        blockman = &active_chainstate.m_blockman;
1087
0
    }
1088
1089
0
    if (!request.params[1].isNull()) {
1090
0
        if (!g_coin_stats_index) {
1091
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Querying specific block heights requires coinstatsindex");
1092
0
        }
1093
1094
0
        if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1095
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "hash_serialized_3 hash type cannot be queried for a specific block");
1096
0
        }
1097
1098
0
        if (!index_requested) {
1099
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot set use_index to false when querying for a specific block");
1100
0
        }
1101
0
        pindex = ParseHashOrHeight(request.params[1], chainman);
1102
0
    }
1103
1104
0
    if (index_requested && g_coin_stats_index) {
1105
0
        if (!g_coin_stats_index->BlockUntilSyncedToCurrentChain()) {
1106
0
            const IndexSummary summary{g_coin_stats_index->GetSummary()};
1107
1108
            // If a specific block was requested and the index has already synced past that height, we can return the
1109
            // data already even though the index is not fully synced yet.
1110
0
            if (pindex && pindex->nHeight > summary.best_block_height) {
1111
0
                throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Unable to get data because coinstatsindex is still syncing. Current height: %d", summary.best_block_height));
Line
Count
Source
1172
0
#define strprintf tfm::format
1112
0
            }
1113
0
        }
1114
0
    }
1115
1116
0
    const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex, index_requested);
1117
0
    if (maybe_stats.has_value()) {
1118
0
        const CCoinsStats& stats = maybe_stats.value();
1119
0
        ret.pushKV("height", stats.nHeight);
1120
0
        ret.pushKV("bestblock", stats.hashBlock.GetHex());
1121
0
        ret.pushKV("txouts", stats.nTransactionOutputs);
1122
0
        ret.pushKV("bogosize", stats.nBogoSize);
1123
0
        if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1124
0
            ret.pushKV("hash_serialized_3", stats.hashSerialized.GetHex());
1125
0
        }
1126
0
        if (hash_type == CoinStatsHashType::MUHASH) {
1127
0
            ret.pushKV("muhash", stats.hashSerialized.GetHex());
1128
0
        }
1129
0
        CHECK_NONFATAL(stats.total_amount.has_value());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1130
0
        ret.pushKV("total_amount", ValueFromAmount(stats.total_amount.value()));
1131
0
        if (!stats.index_used) {
1132
0
            ret.pushKV("transactions", stats.nTransactions);
1133
0
            ret.pushKV("disk_size", stats.nDiskSize);
1134
0
        } else {
1135
0
            CCoinsStats prev_stats{};
1136
0
            if (stats.nHeight > 0) {
1137
0
                const CBlockIndex& block_index = *CHECK_NONFATAL(WITH_LOCK(::cs_main, return blockman->LookupBlockIndex(stats.hashBlock)));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1138
0
                const std::optional<CCoinsStats> maybe_prev_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, block_index.pprev, index_requested);
1139
0
                if (!maybe_prev_stats) {
1140
0
                    throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1141
0
                }
1142
0
                prev_stats = maybe_prev_stats.value();
1143
0
            }
1144
1145
0
            CAmount block_total_unspendable_amount = stats.total_unspendables_genesis_block +
1146
0
                                                     stats.total_unspendables_bip30 +
1147
0
                                                     stats.total_unspendables_scripts +
1148
0
                                                     stats.total_unspendables_unclaimed_rewards;
1149
0
            CAmount prev_block_total_unspendable_amount = prev_stats.total_unspendables_genesis_block +
1150
0
                                                          prev_stats.total_unspendables_bip30 +
1151
0
                                                          prev_stats.total_unspendables_scripts +
1152
0
                                                          prev_stats.total_unspendables_unclaimed_rewards;
1153
1154
0
            ret.pushKV("total_unspendable_amount", ValueFromAmount(block_total_unspendable_amount));
1155
1156
0
            UniValue block_info(UniValue::VOBJ);
1157
            // These per-block values should fit uint64 under normal circumstances
1158
0
            arith_uint256 diff_prevout = stats.total_prevout_spent_amount - prev_stats.total_prevout_spent_amount;
1159
0
            arith_uint256 diff_coinbase = stats.total_coinbase_amount - prev_stats.total_coinbase_amount;
1160
0
            arith_uint256 diff_outputs = stats.total_new_outputs_ex_coinbase_amount - prev_stats.total_new_outputs_ex_coinbase_amount;
1161
0
            CAmount prevout_amount = static_cast<CAmount>(diff_prevout.GetLow64());
1162
0
            CAmount coinbase_amount = static_cast<CAmount>(diff_coinbase.GetLow64());
1163
0
            CAmount outputs_amount = static_cast<CAmount>(diff_outputs.GetLow64());
1164
0
            block_info.pushKV("prevout_spent", ValueFromAmount(prevout_amount));
1165
0
            block_info.pushKV("coinbase", ValueFromAmount(coinbase_amount));
1166
0
            block_info.pushKV("new_outputs_ex_coinbase", ValueFromAmount(outputs_amount));
1167
0
            block_info.pushKV("unspendable", ValueFromAmount(block_total_unspendable_amount - prev_block_total_unspendable_amount));
1168
1169
0
            UniValue unspendables(UniValue::VOBJ);
1170
0
            unspendables.pushKV("genesis_block", ValueFromAmount(stats.total_unspendables_genesis_block - prev_stats.total_unspendables_genesis_block));
1171
0
            unspendables.pushKV("bip30", ValueFromAmount(stats.total_unspendables_bip30 - prev_stats.total_unspendables_bip30));
1172
0
            unspendables.pushKV("scripts", ValueFromAmount(stats.total_unspendables_scripts - prev_stats.total_unspendables_scripts));
1173
0
            unspendables.pushKV("unclaimed_rewards", ValueFromAmount(stats.total_unspendables_unclaimed_rewards - prev_stats.total_unspendables_unclaimed_rewards));
1174
0
            block_info.pushKV("unspendables", std::move(unspendables));
1175
1176
0
            ret.pushKV("block_info", std::move(block_info));
1177
0
        }
1178
0
    } else {
1179
0
        throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1180
0
    }
1181
0
    return ret;
1182
0
},
1183
0
    };
1184
0
}
1185
1186
static RPCMethod gettxout()
1187
0
{
1188
0
    return RPCMethod{
1189
0
        "gettxout",
1190
0
        "Returns details about an unspent transaction output.\n",
1191
0
        {
1192
0
            {"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
1193
0
            {"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
1194
0
            {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
1195
0
        },
1196
0
        {
1197
0
            RPCResult{"If the UTXO was not found", RPCResult::Type::NONE, "", ""},
1198
0
            RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "", {
1199
0
                {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at the tip of the chain"},
1200
0
                {RPCResult::Type::NUM, "confirmations", "The number of confirmations"},
1201
0
                {RPCResult::Type::STR_AMOUNT, "value", "The transaction value in " + CURRENCY_UNIT},
1202
0
                {RPCResult::Type::OBJ, "scriptPubKey", "", {
1203
0
                    {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1204
0
                    {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1205
0
                    {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1206
0
                    {RPCResult::Type::STR, "type", "The type, eg pubkeyhash"},
1207
0
                    {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1208
0
                }},
1209
0
                {RPCResult::Type::BOOL, "coinbase", "Coinbase or not"},
1210
0
            }},
1211
0
        },
1212
0
        RPCExamples{
1213
0
            "\nGet unspent transactions\n"
1214
0
            + HelpExampleCli("listunspent", "") +
1215
0
            "\nView the details\n"
1216
0
            + HelpExampleCli("gettxout", "\"txid\" 1") +
1217
0
            "\nAs a JSON-RPC call\n"
1218
0
            + HelpExampleRpc("gettxout", "\"txid\", 1")
1219
0
                },
1220
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1221
0
{
1222
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
1223
0
    ChainstateManager& chainman = EnsureChainman(node);
1224
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1225
1226
0
    UniValue ret(UniValue::VOBJ);
1227
1228
0
    auto hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
1229
0
    COutPoint out{hash, request.params[1].getInt<uint32_t>()};
1230
0
    bool fMempool = true;
1231
0
    if (!request.params[2].isNull())
1232
0
        fMempool = request.params[2].get_bool();
1233
1234
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
1235
0
    CCoinsViewCache* coins_view = &active_chainstate.CoinsTip();
1236
1237
0
    std::optional<Coin> coin;
1238
0
    if (fMempool) {
1239
0
        const CTxMemPool& mempool = EnsureMemPool(node);
1240
0
        LOCK(mempool.cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1241
0
        CCoinsViewMemPool view(coins_view, mempool);
1242
0
        if (!mempool.isSpent(out)) coin = view.GetCoin(out);
1243
0
    } else {
1244
0
        coin = coins_view->GetCoin(out);
1245
0
    }
1246
0
    if (!coin) return UniValue::VNULL;
1247
1248
0
    const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(coins_view->GetBestBlock());
1249
0
    ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
1250
0
    if (coin->nHeight == MEMPOOL_HEIGHT) {
1251
0
        ret.pushKV("confirmations", 0);
1252
0
    } else {
1253
0
        ret.pushKV("confirmations", pindex->nHeight - coin->nHeight + 1);
1254
0
    }
1255
0
    ret.pushKV("value", ValueFromAmount(coin->out.nValue));
1256
0
    UniValue o(UniValue::VOBJ);
1257
0
    ScriptToUniv(coin->out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1258
0
    ret.pushKV("scriptPubKey", std::move(o));
1259
0
    ret.pushKV("coinbase", static_cast<bool>(coin->fCoinBase));
1260
1261
0
    return ret;
1262
0
},
1263
0
    };
1264
0
}
1265
1266
static RPCMethod verifychain()
1267
0
{
1268
0
    return RPCMethod{
1269
0
        "verifychain",
1270
0
        "Verifies blockchain database.\n",
1271
0
                {
1272
0
                    {"checklevel", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, range=0-4", DEFAULT_CHECKLEVEL)},
Line
Count
Source
1172
0
#define strprintf tfm::format
1273
0
                        strprintf("How thorough the block verification is:\n%s", MakeUnorderedList(CHECKLEVEL_DOC))},
Line
Count
Source
1172
0
#define strprintf tfm::format
1274
0
                    {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%d, 0=all", DEFAULT_CHECKBLOCKS)}, "The number of blocks to check."},
Line
Count
Source
1172
0
#define strprintf tfm::format
1275
0
                },
1276
0
                RPCResult{
1277
0
                    RPCResult::Type::BOOL, "", "Verification finished successfully. If false, check debug log for reason."},
1278
0
                RPCExamples{
1279
0
                    HelpExampleCli("verifychain", "")
1280
0
            + HelpExampleRpc("verifychain", "")
1281
0
                },
1282
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1283
0
{
1284
0
    const int check_level{request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].getInt<int>()};
1285
0
    const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].getInt<int>()};
1286
1287
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1288
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1289
1290
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
1291
0
    return CVerifyDB(chainman.GetNotifications()).VerifyDB(
1292
0
               active_chainstate, chainman.GetParams().GetConsensus(), active_chainstate.CoinsTip(), check_level, check_depth) == VerifyDBResult::SUCCESS;
1293
0
},
1294
0
    };
1295
0
}
1296
1297
static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::BuriedDeployment dep)
1298
0
{
1299
    // For buried deployments.
1300
1301
0
    if (!DeploymentEnabled(chainman, dep)) return;
1302
1303
0
    UniValue rv(UniValue::VOBJ);
1304
0
    rv.pushKV("type", "buried");
1305
    // getdeploymentinfo reports the softfork as active from when the chain height is
1306
    // one below the activation height
1307
0
    rv.pushKV("active", DeploymentActiveAfter(blockindex, chainman, dep));
1308
0
    rv.pushKV("height", chainman.GetConsensus().DeploymentHeight(dep));
1309
0
    softforks.pushKV(DeploymentName(dep), std::move(rv));
1310
0
}
1311
1312
static void SoftForkDescPushBack(const CBlockIndex* blockindex, UniValue& softforks, const ChainstateManager& chainman, Consensus::DeploymentPos id)
1313
0
{
1314
    // For BIP9 deployments.
1315
0
    if (!DeploymentEnabled(chainman, id)) return;
1316
0
    if (blockindex == nullptr) return;
1317
1318
0
    UniValue bip9(UniValue::VOBJ);
1319
0
    BIP9Info info{chainman.m_versionbitscache.Info(*blockindex, chainman.GetConsensus(), id)};
1320
0
    const auto& depparams{chainman.GetConsensus().vDeployments[id]};
1321
1322
    // BIP9 parameters
1323
0
    if (info.stats.has_value()) {
1324
0
        bip9.pushKV("bit", depparams.bit);
1325
0
    }
1326
0
    bip9.pushKV("start_time", depparams.nStartTime);
1327
0
    bip9.pushKV("timeout", depparams.nTimeout);
1328
0
    bip9.pushKV("min_activation_height", depparams.min_activation_height);
1329
1330
    // BIP9 status
1331
0
    bip9.pushKV("status", info.current_state);
1332
0
    bip9.pushKV("since", info.since);
1333
0
    bip9.pushKV("status_next", info.next_state);
1334
1335
    // BIP9 signalling status, if applicable
1336
0
    if (info.stats.has_value()) {
1337
0
        UniValue statsUV(UniValue::VOBJ);
1338
0
        statsUV.pushKV("period", info.stats->period);
1339
0
        statsUV.pushKV("elapsed", info.stats->elapsed);
1340
0
        statsUV.pushKV("count", info.stats->count);
1341
0
        if (info.stats->threshold > 0 || info.stats->possible) {
1342
0
            statsUV.pushKV("threshold", info.stats->threshold);
1343
0
            statsUV.pushKV("possible", info.stats->possible);
1344
0
        }
1345
0
        bip9.pushKV("statistics", std::move(statsUV));
1346
1347
0
        std::string sig;
1348
0
        sig.reserve(info.signalling_blocks.size());
1349
0
        for (const bool s : info.signalling_blocks) {
1350
0
            sig.push_back(s ? '#' : '-');
1351
0
        }
1352
0
        bip9.pushKV("signalling", sig);
1353
0
    }
1354
1355
0
    UniValue rv(UniValue::VOBJ);
1356
0
    rv.pushKV("type", "bip9");
1357
0
    bool is_active = false;
1358
0
    if (info.active_since.has_value()) {
1359
0
        rv.pushKV("height", *info.active_since);
1360
0
        is_active = (*info.active_since <= blockindex->nHeight + 1);
1361
0
    }
1362
0
    rv.pushKV("active", is_active);
1363
0
    rv.pushKV("bip9", bip9);
1364
0
    softforks.pushKV(DeploymentName(id), std::move(rv));
1365
0
}
1366
1367
// used by rest.cpp:rest_chaininfo, so cannot be static
1368
RPCMethod getblockchaininfo()
1369
0
{
1370
0
    return RPCMethod{"getblockchaininfo",
1371
0
        "Returns an object containing various state info regarding blockchain processing.\n",
1372
0
        {},
1373
0
        RPCResult{
1374
0
            RPCResult::Type::OBJ, "", "",
1375
0
            {
1376
0
                {RPCResult::Type::STR, "chain", "current network name (" LIST_CHAIN_NAMES ")"},
1377
0
                {RPCResult::Type::NUM, "blocks", "the height of the most-work fully-validated chain. The genesis block has height 0"},
1378
0
                {RPCResult::Type::NUM, "headers", "the current number of headers we have validated"},
1379
0
                {RPCResult::Type::STR, "bestblockhash", "the hash of the currently best block"},
1380
0
                {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
1381
0
                {RPCResult::Type::STR_HEX, "target", "the difficulty target"},
1382
0
                {RPCResult::Type::NUM, "difficulty", "the current difficulty"},
1383
0
                {RPCResult::Type::NUM_TIME, "time", "the block time expressed in " + UNIX_EPOCH_TIME},
1384
0
                {RPCResult::Type::NUM_TIME, "mediantime", "the median block time expressed in " + UNIX_EPOCH_TIME},
1385
0
                {RPCResult::Type::NUM, "verificationprogress", "estimate of verification progress [0..1]"},
1386
0
                {RPCResult::Type::BOOL, "initialblockdownload", "(debug information) estimate of whether this node is in Initial Block Download mode"},
1387
0
                {RPCResult::Type::OBJ, "backgroundvalidation", /*optional=*/true, "state info regarding background validation process",
1388
0
                {
1389
0
                    {RPCResult::Type::NUM, "snapshotheight", "the height of the snapshot block. Background validation verifies the chain from genesis up to this height"},
1390
0
                    {RPCResult::Type::NUM, "blocks", "the height of the most-work background fully-validated chain. The genesis block has height 0"},
1391
0
                    {RPCResult::Type::STR, "bestblockhash", "the hash of the currently best block validated in the background"},
1392
0
                    {RPCResult::Type::NUM_TIME, "mediantime", "the median block time expressed in " + UNIX_EPOCH_TIME},
1393
0
                    {RPCResult::Type::NUM, "verificationprogress", "estimate of background verification progress [0..1]"},
1394
0
                    {RPCResult::Type::STR_HEX, "chainwork", "total amount of work in background validated chain, in hexadecimal"},
1395
0
                }},
1396
0
                {RPCResult::Type::STR_HEX, "chainwork", "total amount of work in active chain, in hexadecimal"},
1397
0
                {RPCResult::Type::NUM, "size_on_disk", "the estimated size of the block and undo files on disk"},
1398
0
                {RPCResult::Type::BOOL, "pruned", "if the blocks are subject to pruning"},
1399
0
                {RPCResult::Type::NUM, "pruneheight", /*optional=*/true, "the first block unpruned, all previous blocks were pruned (only present if pruning is enabled)"},
1400
0
                {RPCResult::Type::BOOL, "automatic_pruning", /*optional=*/true, "whether automatic pruning is enabled (only present if pruning is enabled)"},
1401
0
                {RPCResult::Type::NUM, "prune_target_size", /*optional=*/true, "the target size used by pruning (only present if automatic pruning is enabled)"},
1402
0
                {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "the block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
1403
0
                (IsDeprecatedRPCEnabled("warnings") ?
1404
0
                    RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
1405
0
                    RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
1406
0
                    {
1407
0
                        {RPCResult::Type::STR, "", "warning"},
1408
0
                    }
1409
0
                    }
1410
0
                ),
1411
0
            }},
1412
0
        RPCExamples{
1413
0
            HelpExampleCli("getblockchaininfo", "")
1414
0
            + HelpExampleRpc("getblockchaininfo", "")
1415
0
        },
1416
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1417
0
{
1418
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1419
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1420
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
1421
1422
0
    const CBlockIndex& tip{*CHECK_NONFATAL(active_chainstate.m_chain.Tip())};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1423
0
    const int height{tip.nHeight};
1424
0
    UniValue obj(UniValue::VOBJ);
1425
0
    obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
1426
0
    obj.pushKV("blocks", height);
1427
0
    obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
1428
0
    obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
1429
0
    obj.pushKV("bits", strprintf("%08x", tip.nBits));
Line
Count
Source
1172
0
#define strprintf tfm::format
1430
0
    obj.pushKV("target", GetTarget(tip, chainman.GetConsensus().powLimit).GetHex());
1431
0
    obj.pushKV("difficulty", GetDifficulty(tip));
1432
0
    obj.pushKV("time", tip.GetBlockTime());
1433
0
    obj.pushKV("mediantime", tip.GetMedianTimePast());
1434
0
    obj.pushKV("verificationprogress", chainman.GuessVerificationProgress(&tip));
1435
0
    obj.pushKV("initialblockdownload", chainman.IsInitialBlockDownload());
1436
0
    auto historical_blocks{chainman.GetHistoricalBlockRange()};
1437
0
    if (historical_blocks) {
1438
0
        UniValue background_validation(UniValue::VOBJ);
1439
0
        const CBlockIndex& btip{*CHECK_NONFATAL(historical_blocks->first)};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1440
0
        const CBlockIndex& btarget{*CHECK_NONFATAL(historical_blocks->second)};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1441
0
        background_validation.pushKV("snapshotheight", btarget.nHeight);
1442
0
        background_validation.pushKV("blocks", btip.nHeight);
1443
0
        background_validation.pushKV("bestblockhash", btip.GetBlockHash().GetHex());
1444
0
        background_validation.pushKV("mediantime", btip.GetMedianTimePast());
1445
0
        background_validation.pushKV("chainwork", btip.nChainWork.GetHex());
1446
0
        background_validation.pushKV("verificationprogress", chainman.GetBackgroundVerificationProgress(btip));
1447
0
        obj.pushKV("backgroundvalidation", std::move(background_validation));
1448
0
    }
1449
0
    obj.pushKV("chainwork", tip.nChainWork.GetHex());
1450
0
    obj.pushKV("size_on_disk", chainman.m_blockman.CalculateCurrentUsage());
1451
0
    obj.pushKV("pruned", chainman.m_blockman.IsPruneMode());
1452
0
    if (chainman.m_blockman.IsPruneMode()) {
1453
0
        const auto prune_height{GetPruneHeight(chainman.m_blockman, active_chainstate.m_chain)};
1454
0
        obj.pushKV("pruneheight", prune_height ? prune_height.value() + 1 : 0);
1455
1456
0
        const bool automatic_pruning{chainman.m_blockman.GetPruneTarget() != BlockManager::PRUNE_TARGET_MANUAL};
1457
0
        obj.pushKV("automatic_pruning",  automatic_pruning);
1458
0
        if (automatic_pruning) {
1459
0
            obj.pushKV("prune_target_size", chainman.m_blockman.GetPruneTarget());
1460
0
        }
1461
0
    }
1462
0
    if (chainman.GetParams().GetChainType() == ChainType::SIGNET) {
1463
0
        const std::vector<uint8_t>& signet_challenge =
1464
0
            chainman.GetParams().GetConsensus().signet_challenge;
1465
0
        obj.pushKV("signet_challenge", HexStr(signet_challenge));
1466
0
    }
1467
1468
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
1469
0
    obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1470
0
    return obj;
1471
0
},
1472
0
    };
1473
0
}
1474
1475
namespace {
1476
const std::vector<RPCResult> RPCHelpForDeployment{
1477
    {RPCResult::Type::STR, "type", "one of \"buried\", \"bip9\""},
1478
    {RPCResult::Type::NUM, "height", /*optional=*/true, "height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
1479
    {RPCResult::Type::BOOL, "active", "true if the rules are enforced for the mempool and the next block"},
1480
    {RPCResult::Type::OBJ, "bip9", /*optional=*/true, "status of bip9 softforks (only for \"bip9\" type)",
1481
    {
1482
        {RPCResult::Type::NUM, "bit", /*optional=*/true, "the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
1483
        {RPCResult::Type::NUM_TIME, "start_time", "the minimum median time past of a block at which the bit gains its meaning"},
1484
        {RPCResult::Type::NUM_TIME, "timeout", "the median time past of a block at which the deployment is considered failed if not yet locked in"},
1485
        {RPCResult::Type::NUM, "min_activation_height", "minimum height of blocks for which the rules may be enforced"},
1486
        {RPCResult::Type::STR, "status", "status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1487
        {RPCResult::Type::NUM, "since", "height of the first block to which the status applies"},
1488
        {RPCResult::Type::STR, "status_next", "status of deployment at the next block"},
1489
        {RPCResult::Type::OBJ, "statistics", /*optional=*/true, "numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1490
        {
1491
            {RPCResult::Type::NUM, "period", "the length in blocks of the signalling period"},
1492
            {RPCResult::Type::NUM, "threshold", /*optional=*/true, "the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1493
            {RPCResult::Type::NUM, "elapsed", "the number of blocks elapsed since the beginning of the current period"},
1494
            {RPCResult::Type::NUM, "count", "the number of blocks with the version bit set in the current period"},
1495
            {RPCResult::Type::BOOL, "possible", /*optional=*/true, "returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
1496
        }},
1497
        {RPCResult::Type::STR, "signalling", /*optional=*/true, "indicates blocks that signalled with a # and blocks that did not with a -"},
1498
    }},
1499
};
1500
1501
UniValue DeploymentInfo(const CBlockIndex* blockindex, const ChainstateManager& chainman)
1502
0
{
1503
0
    UniValue softforks(UniValue::VOBJ);
1504
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_HEIGHTINCB);
1505
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_DERSIG);
1506
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CLTV);
1507
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_CSV);
1508
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_SEGWIT);
1509
0
    SoftForkDescPushBack(blockindex, softforks, chainman, Consensus::DEPLOYMENT_TESTDUMMY);
1510
0
    return softforks;
1511
0
}
1512
} // anon namespace
1513
1514
RPCMethod getdeploymentinfo()
1515
0
{
1516
0
    return RPCMethod{"getdeploymentinfo",
1517
0
        "Returns an object containing various state info regarding deployments of consensus changes.\n"
1518
0
        "Consensus changes for which the new rules are enforced from genesis are not listed in \"deployments\".",
1519
0
        {
1520
0
            {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Default{"hash of current chain tip"}, "The block hash at which to query deployment state"},
1521
0
        },
1522
0
        RPCResult{
1523
0
            RPCResult::Type::OBJ, "", "", {
1524
0
                {RPCResult::Type::STR, "hash", "requested block hash (or tip)"},
1525
0
                {RPCResult::Type::NUM, "height", "requested block height (or tip)"},
1526
0
                {RPCResult::Type::ARR, "script_flags", "script verify flags for the block", {
1527
0
                    {RPCResult::Type::STR, "flag", "a script verify flag"},
1528
0
                }},
1529
0
                {RPCResult::Type::OBJ_DYN, "deployments", "", {
1530
0
                    {RPCResult::Type::OBJ, "xxxx", "name of the deployment", RPCHelpForDeployment}
1531
0
                }},
1532
0
            }
1533
0
        },
1534
0
        RPCExamples{ HelpExampleCli("getdeploymentinfo", "") + HelpExampleRpc("getdeploymentinfo", "") },
1535
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1536
0
        {
1537
0
            const ChainstateManager& chainman = EnsureAnyChainman(request.context);
1538
0
            LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1539
0
            const Chainstate& active_chainstate = chainman.ActiveChainstate();
1540
1541
0
            const CBlockIndex* blockindex;
1542
0
            if (request.params[0].isNull()) {
1543
0
                blockindex = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1544
0
            } else {
1545
0
                const uint256 hash(ParseHashV(request.params[0], "blockhash"));
1546
0
                blockindex = chainman.m_blockman.LookupBlockIndex(hash);
1547
0
                if (!blockindex) {
1548
0
                    throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1549
0
                }
1550
0
            }
1551
1552
0
            UniValue deploymentinfo(UniValue::VOBJ);
1553
0
            deploymentinfo.pushKV("hash", blockindex->GetBlockHash().ToString());
1554
0
            deploymentinfo.pushKV("height", blockindex->nHeight);
1555
0
            {
1556
0
                const auto flagnames = GetScriptFlagNames(GetBlockScriptFlags(*blockindex, chainman));
1557
0
                UniValue uv_flagnames(UniValue::VARR);
1558
0
                uv_flagnames.push_backV(flagnames.begin(), flagnames.end());
1559
0
                deploymentinfo.pushKV("script_flags", uv_flagnames);
1560
0
            }
1561
0
            deploymentinfo.pushKV("deployments", DeploymentInfo(blockindex, chainman));
1562
0
            return deploymentinfo;
1563
0
        },
1564
0
    };
1565
0
}
1566
1567
/** Comparison function for sorting the getchaintips heads.  */
1568
struct CompareBlocksByHeight
1569
{
1570
    bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
1571
0
    {
1572
        /* Make sure that unequal blocks with the same height do not compare
1573
           equal. Use the pointers themselves to make a distinction. */
1574
1575
0
        if (a->nHeight != b->nHeight)
1576
0
          return (a->nHeight > b->nHeight);
1577
1578
0
        return a < b;
1579
0
    }
1580
};
1581
1582
static RPCMethod getchaintips()
1583
0
{
1584
0
    return RPCMethod{"getchaintips",
1585
0
                "Return information about all known tips in the block tree,"
1586
0
                " including the main chain as well as orphaned branches.\n",
1587
0
                {},
1588
0
                RPCResult{
1589
0
                    RPCResult::Type::ARR, "", "",
1590
0
                    {{RPCResult::Type::OBJ, "", "",
1591
0
                        {
1592
0
                            {RPCResult::Type::NUM, "height", "height of the chain tip"},
1593
0
                            {RPCResult::Type::STR_HEX, "hash", "block hash of the tip"},
1594
0
                            {RPCResult::Type::NUM, "branchlen", "zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1595
0
                            {RPCResult::Type::STR, "status", "status of the chain, \"active\" for the main chain\n"
1596
0
            "Possible values for status:\n"
1597
0
            "1.  \"invalid\"               This branch contains at least one invalid block\n"
1598
0
            "2.  \"headers-only\"          Not all blocks for this branch are available, but the headers are valid\n"
1599
0
            "3.  \"valid-headers\"         All blocks are available for this branch, but they were never fully validated\n"
1600
0
            "4.  \"valid-fork\"            This branch is not part of the active chain, but is fully validated\n"
1601
0
            "5.  \"active\"                This is the tip of the active main chain, which is certainly valid"},
1602
0
                        }}}},
1603
0
                RPCExamples{
1604
0
                    HelpExampleCli("getchaintips", "")
1605
0
            + HelpExampleRpc("getchaintips", "")
1606
0
                },
1607
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1608
0
{
1609
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1610
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1611
0
    CChain& active_chain = chainman.ActiveChain();
1612
1613
    /*
1614
     * Idea: The set of chain tips is the active chain tip, plus orphan blocks which do not have another orphan building off of them.
1615
     * Algorithm:
1616
     *  - Make one pass through BlockIndex(), picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
1617
     *  - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
1618
     *  - Add the active chain tip
1619
     */
1620
0
    std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1621
0
    std::set<const CBlockIndex*> setOrphans;
1622
0
    std::set<const CBlockIndex*> setPrevs;
1623
1624
0
    for (const auto& [_, block_index] : chainman.BlockIndex()) {
1625
0
        if (!active_chain.Contains(&block_index)) {
1626
0
            setOrphans.insert(&block_index);
1627
0
            setPrevs.insert(block_index.pprev);
1628
0
        }
1629
0
    }
1630
1631
0
    for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1632
0
        if (setPrevs.erase(*it) == 0) {
1633
0
            setTips.insert(*it);
1634
0
        }
1635
0
    }
1636
1637
    // Always report the currently active tip.
1638
0
    setTips.insert(active_chain.Tip());
1639
1640
    /* Construct the output array.  */
1641
0
    UniValue res(UniValue::VARR);
1642
0
    for (const CBlockIndex* block : setTips) {
1643
0
        UniValue obj(UniValue::VOBJ);
1644
0
        obj.pushKV("height", block->nHeight);
1645
0
        obj.pushKV("hash", block->phashBlock->GetHex());
1646
1647
0
        const int branchLen = block->nHeight - active_chain.FindFork(block)->nHeight;
1648
0
        obj.pushKV("branchlen", branchLen);
1649
1650
0
        std::string status;
1651
0
        if (active_chain.Contains(block)) {
1652
            // This block is part of the currently active chain.
1653
0
            status = "active";
1654
0
        } else if (block->nStatus & BLOCK_FAILED_VALID) {
1655
            // This block or one of its ancestors is invalid.
1656
0
            status = "invalid";
1657
0
        } else if (!block->HaveNumChainTxs()) {
1658
            // This block cannot be connected because full block data for it or one of its parents is missing.
1659
0
            status = "headers-only";
1660
0
        } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
1661
            // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
1662
0
            status = "valid-fork";
1663
0
        } else if (block->IsValid(BLOCK_VALID_TREE)) {
1664
            // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
1665
0
            status = "valid-headers";
1666
0
        } else {
1667
            // No clue.
1668
0
            status = "unknown";
1669
0
        }
1670
0
        obj.pushKV("status", status);
1671
1672
0
        res.push_back(std::move(obj));
1673
0
    }
1674
1675
0
    return res;
1676
0
},
1677
0
    };
1678
0
}
1679
1680
static RPCMethod preciousblock()
1681
0
{
1682
0
    return RPCMethod{
1683
0
        "preciousblock",
1684
0
        "Treats a block as if it were received before others with the same work.\n"
1685
0
                "\nA later preciousblock call can override the effect of an earlier one.\n"
1686
0
                "\nThe effects of preciousblock are not retained across restarts.\n",
1687
0
                {
1688
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as precious"},
1689
0
                },
1690
0
                RPCResult{RPCResult::Type::NONE, "", ""},
1691
0
                RPCExamples{
1692
0
                    HelpExampleCli("preciousblock", "\"blockhash\"")
1693
0
            + HelpExampleRpc("preciousblock", "\"blockhash\"")
1694
0
                },
1695
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1696
0
{
1697
0
    uint256 hash(ParseHashV(request.params[0], "blockhash"));
1698
0
    CBlockIndex* pblockindex;
1699
1700
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1701
0
    {
1702
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1703
0
        pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1704
0
        if (!pblockindex) {
1705
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1706
0
        }
1707
0
    }
1708
1709
0
    BlockValidationState state;
1710
0
    chainman.ActiveChainstate().PreciousBlock(state, pblockindex);
1711
1712
0
    if (!state.IsValid()) {
1713
0
        throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
1714
0
    }
1715
1716
0
    return UniValue::VNULL;
1717
0
},
1718
0
    };
1719
0
}
1720
1721
0
void InvalidateBlock(ChainstateManager& chainman, const uint256 block_hash) {
1722
0
    BlockValidationState state;
1723
0
    CBlockIndex* pblockindex;
1724
0
    {
1725
0
        LOCK(chainman.GetMutex());
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1726
0
        pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1727
0
        if (!pblockindex) {
1728
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1729
0
        }
1730
0
    }
1731
0
    chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
1732
1733
0
    if (state.IsValid()) {
1734
0
        chainman.ActiveChainstate().ActivateBestChain(state);
1735
0
    }
1736
1737
0
    if (!state.IsValid()) {
1738
0
        throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
1739
0
    }
1740
0
}
1741
1742
static RPCMethod invalidateblock()
1743
0
{
1744
0
    return RPCMethod{
1745
0
        "invalidateblock",
1746
0
        "Permanently marks a block as invalid, as if it violated a consensus rule.\n",
1747
0
                {
1748
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as invalid"},
1749
0
                },
1750
0
                RPCResult{RPCResult::Type::NONE, "", ""},
1751
0
                RPCExamples{
1752
0
                    HelpExampleCli("invalidateblock", "\"blockhash\"")
1753
0
            + HelpExampleRpc("invalidateblock", "\"blockhash\"")
1754
0
                },
1755
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1756
0
{
1757
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1758
0
    uint256 hash(ParseHashV(request.params[0], "blockhash"));
1759
1760
0
    InvalidateBlock(chainman, hash);
1761
1762
0
    return UniValue::VNULL;
1763
0
},
1764
0
    };
1765
0
}
1766
1767
0
void ReconsiderBlock(ChainstateManager& chainman, uint256 block_hash) {
1768
0
    {
1769
0
        LOCK(chainman.GetMutex());
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1770
0
        CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(block_hash);
1771
0
        if (!pblockindex) {
1772
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1773
0
        }
1774
1775
0
        chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1776
0
        chainman.RecalculateBestHeader();
1777
0
    }
1778
1779
0
    BlockValidationState state;
1780
0
    chainman.ActiveChainstate().ActivateBestChain(state);
1781
1782
0
    if (!state.IsValid()) {
1783
0
        throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString());
1784
0
    }
1785
0
}
1786
1787
static RPCMethod reconsiderblock()
1788
0
{
1789
0
    return RPCMethod{
1790
0
        "reconsiderblock",
1791
0
        "Removes invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1792
0
                "This can be used to undo the effects of invalidateblock.\n",
1793
0
                {
1794
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to reconsider"},
1795
0
                },
1796
0
                RPCResult{RPCResult::Type::NONE, "", ""},
1797
0
                RPCExamples{
1798
0
                    HelpExampleCli("reconsiderblock", "\"blockhash\"")
1799
0
            + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
1800
0
                },
1801
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1802
0
{
1803
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1804
0
    uint256 hash(ParseHashV(request.params[0], "blockhash"));
1805
1806
0
    ReconsiderBlock(chainman, hash);
1807
1808
0
    return UniValue::VNULL;
1809
0
},
1810
0
    };
1811
0
}
1812
1813
static RPCMethod getchaintxstats()
1814
0
{
1815
0
    return RPCMethod{
1816
0
        "getchaintxstats",
1817
0
        "Compute statistics about the total number and rate of transactions in the chain.\n",
1818
0
                {
1819
0
                    {"nblocks", RPCArg::Type::NUM, RPCArg::DefaultHint{"one month"}, "Size of the window in number of blocks"},
1820
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::DefaultHint{"chain tip"}, "The hash of the block that ends the window."},
1821
0
                },
1822
0
                RPCResult{
1823
0
                    RPCResult::Type::OBJ, "", "",
1824
0
                    {
1825
0
                        {RPCResult::Type::NUM_TIME, "time", "The timestamp for the final block in the window, expressed in " + UNIX_EPOCH_TIME},
1826
0
                        {RPCResult::Type::NUM, "txcount", /*optional=*/true,
1827
0
                         "The total number of transactions in the chain up to that point, if known. "
1828
0
                         "It may be unknown when using assumeutxo."},
1829
0
                        {RPCResult::Type::STR_HEX, "window_final_block_hash", "The hash of the final block in the window"},
1830
0
                        {RPCResult::Type::NUM, "window_final_block_height", "The height of the final block in the window."},
1831
0
                        {RPCResult::Type::NUM, "window_block_count", "Size of the window in number of blocks"},
1832
0
                        {RPCResult::Type::NUM, "window_interval", /*optional=*/true, "The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1833
0
                        {RPCResult::Type::NUM, "window_tx_count", /*optional=*/true,
1834
0
                         "The number of transactions in the window. "
1835
0
                         "Only returned if \"window_block_count\" is > 0 and if txcount exists for the start and end of the window."},
1836
0
                        {RPCResult::Type::NUM, "txrate", /*optional=*/true,
1837
0
                         "The average rate of transactions per second in the window. "
1838
0
                         "Only returned if \"window_interval\" is > 0 and if window_tx_count exists."},
1839
0
                    }},
1840
0
                RPCExamples{
1841
0
                    HelpExampleCli("getchaintxstats", "")
1842
0
            + HelpExampleRpc("getchaintxstats", "2016")
1843
0
                },
1844
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1845
0
{
1846
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
1847
0
    const CBlockIndex* pindex;
1848
0
    int blockcount = 30 * 24 * 60 * 60 / chainman.GetParams().GetConsensus().nPowTargetSpacing; // By default: 1 month
1849
1850
0
    if (request.params[1].isNull()) {
1851
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1852
0
        pindex = chainman.ActiveChain().Tip();
1853
0
    } else {
1854
0
        uint256 hash(ParseHashV(request.params[1], "blockhash"));
1855
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1856
0
        pindex = chainman.m_blockman.LookupBlockIndex(hash);
1857
0
        if (!pindex) {
1858
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1859
0
        }
1860
0
        if (!chainman.ActiveChain().Contains(pindex)) {
1861
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
1862
0
        }
1863
0
    }
1864
1865
0
    CHECK_NONFATAL(pindex != nullptr);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1866
1867
0
    if (request.params[0].isNull()) {
1868
0
        blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
1869
0
    } else {
1870
0
        blockcount = request.params[0].getInt<int>();
1871
1872
0
        if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
1873
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
1874
0
        }
1875
0
    }
1876
1877
0
    const CBlockIndex& past_block{*CHECK_NONFATAL(pindex->GetAncestor(pindex->nHeight - blockcount))};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1878
0
    const int64_t nTimeDiff{pindex->GetMedianTimePast() - past_block.GetMedianTimePast()};
1879
1880
0
    UniValue ret(UniValue::VOBJ);
1881
0
    ret.pushKV("time", pindex->nTime);
1882
0
    if (pindex->m_chain_tx_count) {
1883
0
        ret.pushKV("txcount", pindex->m_chain_tx_count);
1884
0
    }
1885
0
    ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex());
1886
0
    ret.pushKV("window_final_block_height", pindex->nHeight);
1887
0
    ret.pushKV("window_block_count", blockcount);
1888
0
    if (blockcount > 0) {
1889
0
        ret.pushKV("window_interval", nTimeDiff);
1890
0
        if (pindex->m_chain_tx_count != 0 && past_block.m_chain_tx_count != 0) {
1891
0
            const auto window_tx_count = pindex->m_chain_tx_count - past_block.m_chain_tx_count;
1892
0
            ret.pushKV("window_tx_count", window_tx_count);
1893
0
            if (nTimeDiff > 0) {
1894
0
                ret.pushKV("txrate", double(window_tx_count) / nTimeDiff);
1895
0
            }
1896
0
        }
1897
0
    }
1898
1899
0
    return ret;
1900
0
},
1901
0
    };
1902
0
}
1903
1904
template<typename T>
1905
static T CalculateTruncatedMedian(std::vector<T>& scores)
1906
0
{
1907
0
    size_t size = scores.size();
1908
0
    if (size == 0) {
1909
0
        return 0;
1910
0
    }
1911
1912
0
    std::sort(scores.begin(), scores.end());
1913
0
    if (size % 2 == 0) {
1914
0
        return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1915
0
    } else {
1916
0
        return scores[size / 2];
1917
0
    }
1918
0
}
1919
1920
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight)
1921
0
{
1922
0
    if (scores.empty()) {
1923
0
        return;
1924
0
    }
1925
1926
0
    std::sort(scores.begin(), scores.end());
1927
1928
    // 10th, 25th, 50th, 75th, and 90th percentile weight units.
1929
0
    const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
1930
0
        total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1931
0
    };
1932
1933
0
    int64_t next_percentile_index = 0;
1934
0
    int64_t cumulative_weight = 0;
1935
0
    for (const auto& element : scores) {
1936
0
        cumulative_weight += element.second;
1937
0
        while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1938
0
            result[next_percentile_index] = element.first;
1939
0
            ++next_percentile_index;
1940
0
        }
1941
0
    }
1942
1943
    // Fill any remaining percentiles with the last value.
1944
0
    for (int64_t i = next_percentile_index; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
1945
0
        result[i] = scores.back().first;
1946
0
    }
1947
0
}
1948
1949
template<typename T>
1950
0
static inline bool SetHasKeys(const std::set<T>& set) {return false;}
1951
template<typename T, typename Tk, typename... Args>
1952
static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
1953
0
{
1954
0
    return (set.contains(key)) || SetHasKeys(set, args...);
1955
0
}
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [14], char [21], char [14], char [21], char [9], char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [14], char const (&) [21], char const (&) [14], char const (&) [21], char const (&) [9], char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [21], char [14], char [21], char [9], char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [21], char const (&) [14], char const (&) [21], char const (&) [9], char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [14], char [21], char [9], char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [14], char const (&) [21], char const (&) [9], char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [21], char [9], char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [21], char const (&) [9], char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [9], char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [9], char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [7], char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [7], char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11], char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11], char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [7], char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [7], char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [7], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [7], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11], char [10], char [10], char [10], char [13]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11], char const (&) [10], char const (&) [10], char const (&) [10], char const (&) [13])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [10], char [10], char [10], char [13]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [10], char const (&) [10], char const (&) [10], char const (&) [13])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [10], char [10], char [13]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [10], char const (&) [10], char const (&) [13])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [10], char [13]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [10], char const (&) [13])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [13]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [13])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [13], char [11], char [15], char [11], char [20], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [13], char const (&) [11], char const (&) [15], char const (&) [11], char const (&) [20], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11], char [15], char [11], char [20], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11], char const (&) [15], char const (&) [11], char const (&) [20], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [15], char [11], char [20], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [15], char const (&) [11], char const (&) [20], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [11], char [20], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [11], char const (&) [20], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [20], char [11], char [11]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [20], char const (&) [11], char const (&) [11])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [6], char [13], char [15]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [6], char const (&) [13], char const (&) [15])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [13], char [15]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [13], char const (&) [15])
Unexecuted instantiation: blockchain.cpp:bool SetHasKeys<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, char [15]>(std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>> const&, char const (&) [15])
1956
1957
// outpoint (needed for the utxo index) + nHeight + fCoinBase
1958
static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
1959
1960
static RPCMethod getblockstats()
1961
0
{
1962
0
    return RPCMethod{
1963
0
        "getblockstats",
1964
0
        "Compute per block statistics for a given window. All amounts are in satoshis.\n"
1965
0
                "It won't work for some heights with pruning.\n",
1966
0
                {
1967
0
                    {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block hash or height of the target block",
1968
0
                     RPCArgOptions{
1969
0
                         .skip_type_check = true,
1970
0
                         .type_str = {"", "string or numeric"},
1971
0
                     }},
1972
0
                    {"stats", RPCArg::Type::ARR, RPCArg::DefaultHint{"all values"}, "Values to plot (see result below)",
1973
0
                        {
1974
0
                            {"height", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
1975
0
                            {"time", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
1976
0
                        },
1977
0
                        RPCArgOptions{.oneline_description="stats"}},
1978
0
                },
1979
0
                RPCResult{
1980
0
            RPCResult::Type::OBJ, "", "",
1981
0
            {
1982
0
                {RPCResult::Type::NUM, "avgfee", /*optional=*/true, "Average fee in the block"},
1983
0
                {RPCResult::Type::NUM, "avgfeerate", /*optional=*/true, "Average feerate (in satoshis per virtual byte)"},
1984
0
                {RPCResult::Type::NUM, "avgtxsize", /*optional=*/true, "Average transaction size"},
1985
0
                {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block hash (to check for potential reorgs)"},
1986
0
                {RPCResult::Type::ARR_FIXED, "feerate_percentiles", /*optional=*/true, "Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
1987
0
                {
1988
0
                    {RPCResult::Type::NUM, "10th_percentile_feerate", "The 10th percentile feerate"},
1989
0
                    {RPCResult::Type::NUM, "25th_percentile_feerate", "The 25th percentile feerate"},
1990
0
                    {RPCResult::Type::NUM, "50th_percentile_feerate", "The 50th percentile feerate"},
1991
0
                    {RPCResult::Type::NUM, "75th_percentile_feerate", "The 75th percentile feerate"},
1992
0
                    {RPCResult::Type::NUM, "90th_percentile_feerate", "The 90th percentile feerate"},
1993
0
                }},
1994
0
                {RPCResult::Type::NUM, "height", /*optional=*/true, "The height of the block"},
1995
0
                {RPCResult::Type::NUM, "ins", /*optional=*/true, "The number of inputs (excluding coinbase)"},
1996
0
                {RPCResult::Type::NUM, "maxfee", /*optional=*/true, "Maximum fee in the block"},
1997
0
                {RPCResult::Type::NUM, "maxfeerate", /*optional=*/true, "Maximum feerate (in satoshis per virtual byte)"},
1998
0
                {RPCResult::Type::NUM, "maxtxsize", /*optional=*/true, "Maximum transaction size"},
1999
0
                {RPCResult::Type::NUM, "medianfee", /*optional=*/true, "Truncated median fee in the block"},
2000
0
                {RPCResult::Type::NUM, "mediantime", /*optional=*/true, "The block median time past"},
2001
0
                {RPCResult::Type::NUM, "mediantxsize", /*optional=*/true, "Truncated median transaction size"},
2002
0
                {RPCResult::Type::NUM, "minfee", /*optional=*/true, "Minimum fee in the block"},
2003
0
                {RPCResult::Type::NUM, "minfeerate", /*optional=*/true, "Minimum feerate (in satoshis per virtual byte)"},
2004
0
                {RPCResult::Type::NUM, "mintxsize", /*optional=*/true, "Minimum transaction size"},
2005
0
                {RPCResult::Type::NUM, "outs", /*optional=*/true, "The number of outputs"},
2006
0
                {RPCResult::Type::NUM, "subsidy", /*optional=*/true, "The block subsidy"},
2007
0
                {RPCResult::Type::NUM, "swtotal_size", /*optional=*/true, "Total size of all segwit transactions"},
2008
0
                {RPCResult::Type::NUM, "swtotal_weight", /*optional=*/true, "Total weight of all segwit transactions"},
2009
0
                {RPCResult::Type::NUM, "swtxs", /*optional=*/true, "The number of segwit transactions"},
2010
0
                {RPCResult::Type::NUM, "time", /*optional=*/true, "The block time"},
2011
0
                {RPCResult::Type::NUM, "total_out", /*optional=*/true, "Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
2012
0
                {RPCResult::Type::NUM, "total_size", /*optional=*/true, "Total size of all non-coinbase transactions"},
2013
0
                {RPCResult::Type::NUM, "total_weight", /*optional=*/true, "Total weight of all non-coinbase transactions"},
2014
0
                {RPCResult::Type::NUM, "totalfee", /*optional=*/true, "The fee total"},
2015
0
                {RPCResult::Type::NUM, "txs", /*optional=*/true, "The number of transactions (including coinbase)"},
2016
0
                {RPCResult::Type::NUM, "utxo_increase", /*optional=*/true, "The increase/decrease in the number of unspent outputs (not discounting op_return and similar)"},
2017
0
                {RPCResult::Type::NUM, "utxo_size_inc", /*optional=*/true, "The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2018
0
                {RPCResult::Type::NUM, "utxo_increase_actual", /*optional=*/true, "The increase/decrease in the number of unspent outputs, not counting unspendables"},
2019
0
                {RPCResult::Type::NUM, "utxo_size_inc_actual", /*optional=*/true, "The increase/decrease in size for the utxo index, not counting unspendables"},
2020
0
            }},
2021
0
                RPCExamples{
2022
0
                    HelpExampleCli("getblockstats", R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2023
0
                    HelpExampleCli("getblockstats", R"(1000 '["minfeerate","avgfeerate"]')") +
2024
0
                    HelpExampleRpc("getblockstats", R"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2025
0
                    HelpExampleRpc("getblockstats", R"(1000, ["minfeerate","avgfeerate"])")
2026
0
                },
2027
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2028
0
{
2029
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
2030
0
    const CBlockIndex& pindex{*CHECK_NONFATAL(ParseHashOrHeight(request.params[0], chainman))};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2031
2032
0
    std::set<std::string> stats;
2033
0
    if (!request.params[1].isNull()) {
2034
0
        const UniValue stats_univalue = request.params[1].get_array();
2035
0
        for (unsigned int i = 0; i < stats_univalue.size(); i++) {
2036
0
            const std::string stat = stats_univalue[i].get_str();
2037
0
            stats.insert(stat);
2038
0
        }
2039
0
    }
2040
2041
0
    const CBlock& block = GetBlockChecked(chainman.m_blockman, pindex);
2042
0
    const CBlockUndo& blockUndo = GetUndoChecked(chainman.m_blockman, pindex);
2043
2044
0
    const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
2045
0
    const bool do_mediantxsize = do_all || stats.contains("mediantxsize");
2046
0
    const bool do_medianfee = do_all || stats.contains("medianfee");
2047
0
    const bool do_feerate_percentiles = do_all || stats.contains("feerate_percentiles");
2048
0
    const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
2049
0
        SetHasKeys(stats, "utxo_increase", "utxo_increase_actual", "utxo_size_inc", "utxo_size_inc_actual", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
2050
0
    const bool loop_outputs = do_all || loop_inputs || stats.contains("total_out");
2051
0
    const bool do_calculate_size = do_mediantxsize ||
2052
0
        SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size");
2053
0
    const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "feerate_percentiles", "minfeerate", "maxfeerate");
2054
0
    const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight");
2055
2056
0
    CAmount maxfee = 0;
2057
0
    CAmount maxfeerate = 0;
2058
0
    CAmount minfee = MAX_MONEY;
2059
0
    CAmount minfeerate = MAX_MONEY;
2060
0
    CAmount total_out = 0;
2061
0
    CAmount totalfee = 0;
2062
0
    int64_t inputs = 0;
2063
0
    int64_t maxtxsize = 0;
2064
0
    int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
2065
0
    int64_t outputs = 0;
2066
0
    int64_t swtotal_size = 0;
2067
0
    int64_t swtotal_weight = 0;
2068
0
    int64_t swtxs = 0;
2069
0
    int64_t total_size = 0;
2070
0
    int64_t total_weight = 0;
2071
0
    int64_t utxos = 0;
2072
0
    int64_t utxo_size_inc = 0;
2073
0
    int64_t utxo_size_inc_actual = 0;
2074
0
    std::vector<CAmount> fee_array;
2075
0
    std::vector<std::pair<CAmount, int64_t>> feerate_array;
2076
0
    std::vector<int64_t> txsize_array;
2077
2078
0
    for (size_t i = 0; i < block.vtx.size(); ++i) {
2079
0
        const auto& tx = block.vtx.at(i);
2080
0
        outputs += tx->vout.size();
2081
2082
0
        CAmount tx_total_out = 0;
2083
0
        if (loop_outputs) {
2084
0
            for (const CTxOut& out : tx->vout) {
2085
0
                tx_total_out += out.nValue;
2086
2087
0
                uint64_t out_size{GetSerializeSize(out) + PER_UTXO_OVERHEAD};
2088
0
                utxo_size_inc += out_size;
2089
2090
                // The Genesis block and the repeated BIP30 block coinbases don't change the UTXO
2091
                // set counts, so they have to be excluded from the statistics
2092
0
                if (pindex.nHeight == 0 || (IsBIP30Repeat(pindex) && tx->IsCoinBase())) continue;
2093
                // Skip unspendable outputs since they are not included in the UTXO set
2094
0
                if (out.scriptPubKey.IsUnspendable()) continue;
2095
2096
0
                ++utxos;
2097
0
                utxo_size_inc_actual += out_size;
2098
0
            }
2099
0
        }
2100
2101
0
        if (tx->IsCoinBase()) {
2102
0
            continue;
2103
0
        }
2104
2105
0
        inputs += tx->vin.size(); // Don't count coinbase's fake input
2106
0
        total_out += tx_total_out; // Don't count coinbase reward
2107
2108
0
        int64_t tx_size = 0;
2109
0
        if (do_calculate_size) {
2110
2111
0
            tx_size = tx->ComputeTotalSize();
2112
0
            if (do_mediantxsize) {
2113
0
                txsize_array.push_back(tx_size);
2114
0
            }
2115
0
            maxtxsize = std::max(maxtxsize, tx_size);
2116
0
            mintxsize = std::min(mintxsize, tx_size);
2117
0
            total_size += tx_size;
2118
0
        }
2119
2120
0
        int64_t weight = 0;
2121
0
        if (do_calculate_weight) {
2122
0
            weight = GetTransactionWeight(*tx);
2123
0
            total_weight += weight;
2124
0
        }
2125
2126
0
        if (do_calculate_sw && tx->HasWitness()) {
2127
0
            ++swtxs;
2128
0
            swtotal_size += tx_size;
2129
0
            swtotal_weight += weight;
2130
0
        }
2131
2132
0
        if (loop_inputs) {
2133
0
            CAmount tx_total_in = 0;
2134
0
            const auto& txundo = blockUndo.vtxundo.at(i - 1);
2135
0
            for (const Coin& coin: txundo.vprevout) {
2136
0
                const CTxOut& prevoutput = coin.out;
2137
2138
0
                tx_total_in += prevoutput.nValue;
2139
0
                uint64_t prevout_size{GetSerializeSize(prevoutput) + PER_UTXO_OVERHEAD};
2140
0
                utxo_size_inc -= prevout_size;
2141
0
                utxo_size_inc_actual -= prevout_size;
2142
0
            }
2143
2144
0
            CAmount txfee = tx_total_in - tx_total_out;
2145
0
            CHECK_NONFATAL(MoneyRange(txfee));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2146
0
            if (do_medianfee) {
2147
0
                fee_array.push_back(txfee);
2148
0
            }
2149
0
            maxfee = std::max(maxfee, txfee);
2150
0
            minfee = std::min(minfee, txfee);
2151
0
            totalfee += txfee;
2152
2153
            // New feerate uses satoshis per virtual byte instead of per serialized byte
2154
0
            CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
2155
0
            if (do_feerate_percentiles) {
2156
0
                feerate_array.emplace_back(feerate, weight);
2157
0
            }
2158
0
            maxfeerate = std::max(maxfeerate, feerate);
2159
0
            minfeerate = std::min(minfeerate, feerate);
2160
0
        }
2161
0
    }
2162
2163
0
    CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
2164
0
    CalculatePercentilesByWeight(feerate_percentiles, feerate_array, total_weight);
2165
2166
0
    UniValue feerates_res(UniValue::VARR);
2167
0
    for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
2168
0
        feerates_res.push_back(feerate_percentiles[i]);
2169
0
    }
2170
2171
0
    UniValue ret_all(UniValue::VOBJ);
2172
0
    ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
2173
0
    ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
2174
0
    ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
2175
0
    ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
2176
0
    ret_all.pushKV("feerate_percentiles", std::move(feerates_res));
2177
0
    ret_all.pushKV("height", pindex.nHeight);
2178
0
    ret_all.pushKV("ins", inputs);
2179
0
    ret_all.pushKV("maxfee", maxfee);
2180
0
    ret_all.pushKV("maxfeerate", maxfeerate);
2181
0
    ret_all.pushKV("maxtxsize", maxtxsize);
2182
0
    ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
2183
0
    ret_all.pushKV("mediantime", pindex.GetMedianTimePast());
2184
0
    ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
2185
0
    ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
2186
0
    ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
2187
0
    ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
2188
0
    ret_all.pushKV("outs", outputs);
2189
0
    ret_all.pushKV("subsidy", GetBlockSubsidy(pindex.nHeight, chainman.GetParams().GetConsensus()));
2190
0
    ret_all.pushKV("swtotal_size", swtotal_size);
2191
0
    ret_all.pushKV("swtotal_weight", swtotal_weight);
2192
0
    ret_all.pushKV("swtxs", swtxs);
2193
0
    ret_all.pushKV("time", pindex.GetBlockTime());
2194
0
    ret_all.pushKV("total_out", total_out);
2195
0
    ret_all.pushKV("total_size", total_size);
2196
0
    ret_all.pushKV("total_weight", total_weight);
2197
0
    ret_all.pushKV("totalfee", totalfee);
2198
0
    ret_all.pushKV("txs", block.vtx.size());
2199
0
    ret_all.pushKV("utxo_increase", outputs - inputs);
2200
0
    ret_all.pushKV("utxo_size_inc", utxo_size_inc);
2201
0
    ret_all.pushKV("utxo_increase_actual", utxos - inputs);
2202
0
    ret_all.pushKV("utxo_size_inc_actual", utxo_size_inc_actual);
2203
2204
0
    if (do_all) {
2205
0
        return ret_all;
2206
0
    }
2207
2208
0
    UniValue ret(UniValue::VOBJ);
2209
0
    for (const std::string& stat : stats) {
2210
0
        const UniValue& value = ret_all[stat];
2211
0
        if (value.isNull()) {
2212
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic '%s'", stat));
Line
Count
Source
1172
0
#define strprintf tfm::format
2213
0
        }
2214
0
        ret.pushKV(stat, value);
2215
0
    }
2216
0
    return ret;
2217
0
},
2218
0
    };
2219
0
}
2220
2221
namespace {
2222
//! Search for a given set of pubkey scripts
2223
bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>& should_abort, int64_t& count, CCoinsViewCursor* cursor, const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results, std::function<void()>& interruption_point)
2224
0
{
2225
0
    scan_progress = 0;
2226
0
    count = 0;
2227
0
    while (cursor->Valid()) {
2228
0
        COutPoint key;
2229
0
        Coin coin;
2230
0
        if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
2231
0
        if (++count % 8192 == 0) {
2232
0
            interruption_point();
2233
0
            if (should_abort) {
2234
                // allow to abort the scan via the abort reference
2235
0
                return false;
2236
0
            }
2237
0
        }
2238
0
        if (count % 256 == 0) {
2239
            // update progress reference every 256 item
2240
0
            uint32_t high = 0x100 * *UCharCast(key.hash.begin()) + *(UCharCast(key.hash.begin()) + 1);
2241
0
            scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2242
0
        }
2243
0
        if (needles.contains(coin.out.scriptPubKey)) {
2244
0
            out_results.emplace(key, coin);
2245
0
        }
2246
0
        cursor->Next();
2247
0
    }
2248
0
    scan_progress = 100;
2249
0
    return true;
2250
0
}
2251
} // namespace
2252
2253
/** RAII object to prevent concurrency issue when scanning the txout set */
2254
static std::atomic<int> g_scan_progress;
2255
static std::atomic<bool> g_scan_in_progress;
2256
static std::atomic<bool> g_should_abort_scan;
2257
class CoinsViewScanReserver
2258
{
2259
private:
2260
    bool m_could_reserve{false};
2261
public:
2262
0
    explicit CoinsViewScanReserver() = default;
2263
2264
0
    bool reserve() {
2265
0
        CHECK_NONFATAL(!m_could_reserve);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2266
0
        if (g_scan_in_progress.exchange(true)) {
2267
0
            return false;
2268
0
        }
2269
0
        CHECK_NONFATAL(g_scan_progress == 0);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2270
0
        m_could_reserve = true;
2271
0
        return true;
2272
0
    }
2273
2274
0
    ~CoinsViewScanReserver() {
2275
0
        if (m_could_reserve) {
2276
0
            g_scan_in_progress = false;
2277
0
            g_scan_progress = 0;
2278
0
        }
2279
0
    }
2280
};
2281
2282
static const auto scan_action_arg_desc = RPCArg{
2283
    "action", RPCArg::Type::STR, RPCArg::Optional::NO, "The action to execute\n"
2284
        "\"start\" for starting a scan\n"
2285
        "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2286
        "\"status\" for progress report (in %) of the current scan"
2287
};
2288
2289
static const auto output_descriptor_obj = RPCArg{
2290
    "", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with output descriptor and metadata",
2291
    {
2292
        {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
2293
        {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "The range of HD chain indexes to explore (either end or [begin,end])"},
2294
    }
2295
};
2296
2297
static const auto scan_objects_arg_desc = RPCArg{
2298
    "scanobjects", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Array of scan objects. Required for \"start\" action\n"
2299
        "Every scan object is either a string descriptor or an object:",
2300
    {
2301
        {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
2302
        output_descriptor_obj,
2303
    },
2304
    RPCArgOptions{.oneline_description="[scanobjects,...]"},
2305
};
2306
2307
static const auto scan_result_abort = RPCResult{
2308
    "when action=='abort'", RPCResult::Type::BOOL, "success",
2309
    "True if scan will be aborted (not necessarily before this RPC returns), or false if there is no scan to abort"
2310
};
2311
static const auto scan_result_status_none = RPCResult{
2312
    "when action=='status' and no scan is in progress - possibly already completed", RPCResult::Type::NONE, "", ""
2313
};
2314
static const auto scan_result_status_some = RPCResult{
2315
    "when action=='status' and a scan is currently in progress", RPCResult::Type::OBJ, "", "",
2316
    {{RPCResult::Type::NUM, "progress", "Approximate percent complete"},}
2317
};
2318
2319
2320
static RPCMethod scantxoutset()
2321
0
{
2322
    // raw() descriptor corresponding to mainnet address 12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S
2323
0
    const std::string EXAMPLE_DESCRIPTOR_RAW = "raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2324
2325
0
    return RPCMethod{
2326
0
        "scantxoutset",
2327
0
        "Scans the unspent transaction output set for entries that match certain output descriptors.\n"
2328
0
        "Examples of output descriptors are:\n"
2329
0
        "    addr(<address>)                      Outputs whose output script corresponds to the specified address (does not include P2PK)\n"
2330
0
        "    raw(<hex script>)                    Outputs whose output script equals the specified hex-encoded bytes\n"
2331
0
        "    combo(<pubkey>)                      P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2332
0
        "    pkh(<pubkey>)                        P2PKH outputs for the given pubkey\n"
2333
0
        "    sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2334
0
        "    tr(<pubkey>)                         P2TR\n"
2335
0
        "    tr(<pubkey>,{pk(<pubkey>)})          P2TR with single fallback pubkey in tapscript\n"
2336
0
        "    rawtr(<pubkey>)                      P2TR with the specified key as output key rather than inner\n"
2337
0
        "    wsh(and_v(v:pk(<pubkey>),after(2)))  P2WSH miniscript with mandatory pubkey and a timelock\n"
2338
0
        "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2339
0
        "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2340
0
        "unhardened or hardened child keys.\n"
2341
0
        "In the latter case, a range needs to be specified by below if different from 1000.\n"
2342
0
        "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2343
0
        {
2344
0
            scan_action_arg_desc,
2345
0
            scan_objects_arg_desc,
2346
0
        },
2347
0
        {
2348
0
            RPCResult{"when action=='start'; only returns after scan completes", RPCResult::Type::OBJ, "", "", {
2349
0
                {RPCResult::Type::BOOL, "success", "Whether the scan was completed"},
2350
0
                {RPCResult::Type::NUM, "txouts", "The number of unspent transaction outputs scanned"},
2351
0
                {RPCResult::Type::NUM, "height", "The block height at which the scan was done"},
2352
0
                {RPCResult::Type::STR_HEX, "bestblock", "The hash of the block at the tip of the chain"},
2353
0
                {RPCResult::Type::ARR, "unspents", "",
2354
0
                {
2355
0
                    {RPCResult::Type::OBJ, "", "",
2356
0
                    {
2357
0
                        {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
2358
0
                        {RPCResult::Type::NUM, "vout", "The vout value"},
2359
0
                        {RPCResult::Type::STR_HEX, "scriptPubKey", "The output script"},
2360
0
                        {RPCResult::Type::STR, "desc", "A specialized descriptor for the matched output script"},
2361
0
                        {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the unspent output"},
2362
0
                        {RPCResult::Type::BOOL, "coinbase", "Whether this is a coinbase output"},
2363
0
                        {RPCResult::Type::NUM, "height", "Height of the unspent transaction output"},
2364
0
                        {RPCResult::Type::STR_HEX, "blockhash", "Blockhash of the unspent transaction output"},
2365
0
                        {RPCResult::Type::NUM, "confirmations", "Number of confirmations of the unspent transaction output when the scan was done"},
2366
0
                    }},
2367
0
                }},
2368
0
                {RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of all found unspent outputs in " + CURRENCY_UNIT},
2369
0
            }},
2370
0
            scan_result_abort,
2371
0
            scan_result_status_some,
2372
0
            scan_result_status_none,
2373
0
        },
2374
0
        RPCExamples{
2375
0
            HelpExampleCli("scantxoutset", "start \'[\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]\'") +
2376
0
            HelpExampleCli("scantxoutset", "status") +
2377
0
            HelpExampleCli("scantxoutset", "abort") +
2378
0
            HelpExampleRpc("scantxoutset", "\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW + "\"]") +
2379
0
            HelpExampleRpc("scantxoutset", "\"status\"") +
2380
0
            HelpExampleRpc("scantxoutset", "\"abort\"")
2381
0
        },
2382
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2383
0
{
2384
0
    UniValue result(UniValue::VOBJ);
2385
0
    const auto action{self.Arg<std::string_view>("action")};
2386
0
    if (action == "status") {
2387
0
        CoinsViewScanReserver reserver;
2388
0
        if (reserver.reserve()) {
2389
            // no scan in progress
2390
0
            return UniValue::VNULL;
2391
0
        }
2392
0
        result.pushKV("progress", g_scan_progress.load());
2393
0
        return result;
2394
0
    } else if (action == "abort") {
2395
0
        CoinsViewScanReserver reserver;
2396
0
        if (reserver.reserve()) {
2397
            // reserve was possible which means no scan was running
2398
0
            return false;
2399
0
        }
2400
        // set the abort flag
2401
0
        g_should_abort_scan = true;
2402
0
        return true;
2403
0
    } else if (action == "start") {
2404
0
        CoinsViewScanReserver reserver;
2405
0
        if (!reserver.reserve()) {
2406
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
2407
0
        }
2408
2409
0
        if (request.params.size() < 2) {
2410
0
            throw JSONRPCError(RPC_MISC_ERROR, "scanobjects argument is required for the start action");
2411
0
        }
2412
2413
0
        std::set<CScript> needles;
2414
0
        std::map<CScript, std::string> descriptors;
2415
0
        CAmount total_in = 0;
2416
2417
        // loop through the scan objects
2418
0
        for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2419
0
            FlatSigningProvider provider;
2420
0
            auto scripts = EvalDescriptorStringOrObject(scanobject, provider);
2421
0
            for (CScript& script : scripts) {
2422
0
                std::string inferred = InferDescriptor(script, provider)->ToString();
2423
0
                needles.emplace(script);
2424
0
                descriptors.emplace(std::move(script), std::move(inferred));
2425
0
            }
2426
0
        }
2427
2428
        // Scan the unspent transaction output set for inputs
2429
0
        UniValue unspents(UniValue::VARR);
2430
0
        std::vector<CTxOut> input_txos;
2431
0
        std::map<COutPoint, Coin> coins;
2432
0
        g_should_abort_scan = false;
2433
0
        int64_t count = 0;
2434
0
        std::unique_ptr<CCoinsViewCursor> pcursor;
2435
0
        const CBlockIndex* tip;
2436
0
        NodeContext& node = EnsureAnyNodeContext(request.context);
2437
0
        {
2438
0
            ChainstateManager& chainman = EnsureChainman(node);
2439
0
            LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2440
0
            Chainstate& active_chainstate = chainman.ActiveChainstate();
2441
0
            active_chainstate.ForceFlushStateToDisk(/*wipe_cache=*/false);
2442
0
            pcursor = CHECK_NONFATAL(active_chainstate.CoinsDB().Cursor());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2443
0
            tip = CHECK_NONFATAL(active_chainstate.m_chain.Tip());
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2444
0
        }
2445
0
        bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point);
2446
0
        result.pushKV("success", res);
2447
0
        result.pushKV("txouts", count);
2448
0
        result.pushKV("height", tip->nHeight);
2449
0
        result.pushKV("bestblock", tip->GetBlockHash().GetHex());
2450
2451
0
        for (const auto& it : coins) {
2452
0
            const COutPoint& outpoint = it.first;
2453
0
            const Coin& coin = it.second;
2454
0
            const CTxOut& txo = coin.out;
2455
0
            const CBlockIndex& coinb_block{*CHECK_NONFATAL(tip->GetAncestor(coin.nHeight))};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2456
0
            input_txos.push_back(txo);
2457
0
            total_in += txo.nValue;
2458
2459
0
            UniValue unspent(UniValue::VOBJ);
2460
0
            unspent.pushKV("txid", outpoint.hash.GetHex());
2461
0
            unspent.pushKV("vout", outpoint.n);
2462
0
            unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey));
2463
0
            unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
2464
0
            unspent.pushKV("amount", ValueFromAmount(txo.nValue));
2465
0
            unspent.pushKV("coinbase", coin.IsCoinBase());
2466
0
            unspent.pushKV("height", coin.nHeight);
2467
0
            unspent.pushKV("blockhash", coinb_block.GetBlockHash().GetHex());
2468
0
            unspent.pushKV("confirmations", tip->nHeight - coin.nHeight + 1);
2469
2470
0
            unspents.push_back(std::move(unspent));
2471
0
        }
2472
0
        result.pushKV("unspents", std::move(unspents));
2473
0
        result.pushKV("total_amount", ValueFromAmount(total_in));
2474
0
    } else {
2475
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid action '%s'", action));
Line
Count
Source
1172
0
#define strprintf tfm::format
2476
0
    }
2477
0
    return result;
2478
0
},
2479
0
    };
2480
0
}
2481
2482
/** RAII object to prevent concurrency issue when scanning blockfilters */
2483
static std::atomic<int> g_scanfilter_progress;
2484
static std::atomic<int> g_scanfilter_progress_height;
2485
static std::atomic<bool> g_scanfilter_in_progress;
2486
static std::atomic<bool> g_scanfilter_should_abort_scan;
2487
class BlockFiltersScanReserver
2488
{
2489
private:
2490
    bool m_could_reserve{false};
2491
public:
2492
0
    explicit BlockFiltersScanReserver() = default;
2493
2494
0
    bool reserve() {
2495
0
        CHECK_NONFATAL(!m_could_reserve);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2496
0
        if (g_scanfilter_in_progress.exchange(true)) {
2497
0
            return false;
2498
0
        }
2499
0
        m_could_reserve = true;
2500
0
        return true;
2501
0
    }
2502
2503
0
    ~BlockFiltersScanReserver() {
2504
0
        if (m_could_reserve) {
2505
0
            g_scanfilter_in_progress = false;
2506
0
        }
2507
0
    }
2508
};
2509
2510
static bool CheckBlockFilterMatches(BlockManager& blockman, const CBlockIndex& blockindex, const GCSFilter::ElementSet& needles)
2511
0
{
2512
0
    const CBlock block{GetBlockChecked(blockman, blockindex)};
2513
0
    const CBlockUndo block_undo{GetUndoChecked(blockman, blockindex)};
2514
2515
    // Check if any of the outputs match the scriptPubKey
2516
0
    for (const auto& tx : block.vtx) {
2517
0
        if (std::any_of(tx->vout.cbegin(), tx->vout.cend(), [&](const auto& txout) {
2518
0
                return needles.contains(std::vector<unsigned char>(txout.scriptPubKey.begin(), txout.scriptPubKey.end()));
2519
0
            })) {
2520
0
            return true;
2521
0
        }
2522
0
    }
2523
    // Check if any of the inputs match the scriptPubKey
2524
0
    for (const auto& txundo : block_undo.vtxundo) {
2525
0
        if (std::any_of(txundo.vprevout.cbegin(), txundo.vprevout.cend(), [&](const auto& coin) {
2526
0
                return needles.contains(std::vector<unsigned char>(coin.out.scriptPubKey.begin(), coin.out.scriptPubKey.end()));
2527
0
            })) {
2528
0
            return true;
2529
0
        }
2530
0
    }
2531
2532
0
    return false;
2533
0
}
2534
2535
static RPCMethod scanblocks()
2536
0
{
2537
0
    return RPCMethod{
2538
0
        "scanblocks",
2539
0
        "Return relevant blockhashes for given descriptors (requires blockfilterindex).\n"
2540
0
        "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2541
0
        {
2542
0
            scan_action_arg_desc,
2543
0
            scan_objects_arg_desc,
2544
0
            RPCArg{"start_height", RPCArg::Type::NUM, RPCArg::Default{0}, "Height to start to scan from"},
2545
0
            RPCArg{"stop_height", RPCArg::Type::NUM, RPCArg::DefaultHint{"chain tip"}, "Height to stop to scan"},
2546
0
            RPCArg{"filtertype", RPCArg::Type::STR, RPCArg::Default{BlockFilterTypeName(BlockFilterType::BASIC)}, "The type name of the filter"},
2547
0
            RPCArg{"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
2548
0
                {
2549
0
                    {"filter_false_positives", RPCArg::Type::BOOL, RPCArg::Default{false}, "Filter false positives (slower and may fail on pruned nodes). Otherwise they may occur at a rate of 1/M"},
2550
0
                },
2551
0
                RPCArgOptions{.oneline_description="options"}},
2552
0
        },
2553
0
        {
2554
0
            scan_result_status_none,
2555
0
            RPCResult{"When action=='start'; only returns after scan completes", RPCResult::Type::OBJ, "", "", {
2556
0
                {RPCResult::Type::NUM, "from_height", "The height we started the scan from"},
2557
0
                {RPCResult::Type::NUM, "to_height", "The height we ended the scan at"},
2558
0
                {RPCResult::Type::ARR, "relevant_blocks", "Blocks that may have matched a scanobject.", {
2559
0
                    {RPCResult::Type::STR_HEX, "blockhash", "A relevant blockhash"},
2560
0
                }},
2561
0
                {RPCResult::Type::BOOL, "completed", "true if the scan process was not aborted"}
2562
0
            }},
2563
0
            RPCResult{"when action=='status' and a scan is currently in progress", RPCResult::Type::OBJ, "", "", {
2564
0
                    {RPCResult::Type::NUM, "progress", "Approximate percent complete"},
2565
0
                    {RPCResult::Type::NUM, "current_height", "Height of the block currently being scanned"},
2566
0
                },
2567
0
            },
2568
0
            scan_result_abort,
2569
0
        },
2570
0
        RPCExamples{
2571
0
            HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 300000") +
2572
0
            HelpExampleCli("scanblocks", "start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 100 150 basic") +
2573
0
            HelpExampleCli("scanblocks", "status") +
2574
0
            HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 300000") +
2575
0
            HelpExampleRpc("scanblocks", "\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 100, 150, \"basic\"") +
2576
0
            HelpExampleRpc("scanblocks", "\"status\"")
2577
0
        },
2578
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2579
0
{
2580
0
    UniValue ret(UniValue::VOBJ);
2581
0
    auto action{self.Arg<std::string_view>("action")};
2582
0
    if (action == "status") {
2583
0
        BlockFiltersScanReserver reserver;
2584
0
        if (reserver.reserve()) {
2585
            // no scan in progress
2586
0
            return NullUniValue;
2587
0
        }
2588
0
        ret.pushKV("progress", g_scanfilter_progress.load());
2589
0
        ret.pushKV("current_height", g_scanfilter_progress_height.load());
2590
0
        return ret;
2591
0
    } else if (action == "abort") {
2592
0
        BlockFiltersScanReserver reserver;
2593
0
        if (reserver.reserve()) {
2594
            // reserve was possible which means no scan was running
2595
0
            return false;
2596
0
        }
2597
        // set the abort flag
2598
0
        g_scanfilter_should_abort_scan = true;
2599
0
        return true;
2600
0
    } else if (action == "start") {
2601
0
        BlockFiltersScanReserver reserver;
2602
0
        if (!reserver.reserve()) {
2603
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
2604
0
        }
2605
0
        auto filtertype_name{self.Arg<std::string_view>("filtertype")};
2606
2607
0
        BlockFilterType filtertype;
2608
0
        if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2609
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
2610
0
        }
2611
2612
0
        UniValue options{request.params[5].isNull() ? UniValue::VOBJ : request.params[5]};
2613
0
        bool filter_false_positives{options.exists("filter_false_positives") ? options["filter_false_positives"].get_bool() : false};
2614
2615
0
        BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
2616
0
        if (!index) {
2617
0
            throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
2618
0
        }
2619
2620
0
        NodeContext& node = EnsureAnyNodeContext(request.context);
2621
0
        ChainstateManager& chainman = EnsureChainman(node);
2622
2623
        // set the start-height
2624
0
        const CBlockIndex* start_index = nullptr;
2625
0
        const CBlockIndex* stop_block = nullptr;
2626
0
        {
2627
0
            LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2628
0
            CChain& active_chain = chainman.ActiveChain();
2629
0
            start_index = active_chain.Genesis();
2630
0
            stop_block = active_chain.Tip(); // If no stop block is provided, stop at the chain tip.
2631
0
            if (!request.params[2].isNull()) {
2632
0
                start_index = active_chain[request.params[2].getInt<int>()];
2633
0
                if (!start_index) {
2634
0
                    throw JSONRPCError(RPC_MISC_ERROR, "Invalid start_height");
2635
0
                }
2636
0
            }
2637
0
            if (!request.params[3].isNull()) {
2638
0
                stop_block = active_chain[request.params[3].getInt<int>()];
2639
0
                if (!stop_block || stop_block->nHeight < start_index->nHeight) {
2640
0
                    throw JSONRPCError(RPC_MISC_ERROR, "Invalid stop_height");
2641
0
                }
2642
0
            }
2643
0
        }
2644
0
        CHECK_NONFATAL(start_index);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2645
0
        CHECK_NONFATAL(stop_block);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2646
2647
        // loop through the scan objects, add scripts to the needle_set
2648
0
        GCSFilter::ElementSet needle_set;
2649
0
        for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2650
0
            FlatSigningProvider provider;
2651
0
            std::vector<CScript> scripts = EvalDescriptorStringOrObject(scanobject, provider);
2652
0
            for (const CScript& script : scripts) {
2653
0
                needle_set.emplace(script.begin(), script.end());
2654
0
            }
2655
0
        }
2656
0
        UniValue blocks(UniValue::VARR);
2657
0
        const int amount_per_chunk = 10000;
2658
0
        std::vector<BlockFilter> filters;
2659
0
        int start_block_height = start_index->nHeight; // for progress reporting
2660
0
        const int total_blocks_to_process = stop_block->nHeight - start_block_height;
2661
2662
0
        g_scanfilter_should_abort_scan = false;
2663
0
        g_scanfilter_progress = 0;
2664
0
        g_scanfilter_progress_height = start_block_height;
2665
0
        bool completed = true;
2666
2667
0
        const CBlockIndex* end_range = nullptr;
2668
0
        do {
2669
0
            node.rpc_interruption_point(); // allow a clean shutdown
2670
0
            if (g_scanfilter_should_abort_scan) {
2671
0
                completed = false;
2672
0
                break;
2673
0
            }
2674
2675
            // split the lookup range in chunks if we are deeper than 'amount_per_chunk' blocks from the stopping block
2676
0
            int start_block = !end_range ? start_index->nHeight : start_index->nHeight + 1; // to not include the previous round 'end_range' block
2677
0
            end_range = (start_block + amount_per_chunk < stop_block->nHeight) ?
2678
0
                    WITH_LOCK(::cs_main, return chainman.ActiveChain()[start_block + amount_per_chunk]) :
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
2679
0
                    stop_block;
2680
2681
0
            if (index->LookupFilterRange(start_block, end_range, filters)) {
2682
0
                for (const BlockFilter& filter : filters) {
2683
                    // compare the elements-set with each filter
2684
0
                    if (filter.GetFilter().MatchAny(needle_set)) {
2685
0
                        if (filter_false_positives) {
2686
                            // Double check the filter matches by scanning the block
2687
0
                            const CBlockIndex& blockindex = *CHECK_NONFATAL(WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(filter.GetBlockHash())));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2688
2689
0
                            if (!CheckBlockFilterMatches(chainman.m_blockman, blockindex, needle_set)) {
2690
0
                                continue;
2691
0
                            }
2692
0
                        }
2693
2694
0
                        blocks.push_back(filter.GetBlockHash().GetHex());
2695
0
                    }
2696
0
                }
2697
0
            }
2698
0
            start_index = end_range;
2699
2700
            // update progress
2701
0
            int blocks_processed = end_range->nHeight - start_block_height;
2702
0
            if (total_blocks_to_process > 0) { // avoid division by zero
2703
0
                g_scanfilter_progress = (int)(100.0 / total_blocks_to_process * blocks_processed);
2704
0
            } else {
2705
0
                g_scanfilter_progress = 100;
2706
0
            }
2707
0
            g_scanfilter_progress_height = end_range->nHeight;
2708
2709
        // Finish if we reached the stop block
2710
0
        } while (start_index != stop_block);
2711
2712
0
        ret.pushKV("from_height", start_block_height);
2713
0
        ret.pushKV("to_height", start_index->nHeight); // start_index is always the last scanned block here
2714
0
        ret.pushKV("relevant_blocks", std::move(blocks));
2715
0
        ret.pushKV("completed", completed);
2716
0
    } else {
2717
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("Invalid action '%s'", action));
2718
0
    }
2719
0
    return ret;
2720
0
},
2721
0
    };
2722
0
}
2723
2724
static RPCMethod getdescriptoractivity()
2725
0
{
2726
0
    return RPCMethod{
2727
0
        "getdescriptoractivity",
2728
0
        "Get spend and receive activity associated with a set of descriptors for a set of blocks. "
2729
0
        "This command pairs well with the `relevant_blocks` output of `scanblocks()`.\n"
2730
0
        "This call may take several minutes. If you encounter timeouts, try specifying no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2731
0
        {
2732
0
            RPCArg{"blockhashes", RPCArg::Type::ARR, RPCArg::Optional::NO, "The list of blockhashes to examine for activity. Order doesn't matter. Must be along main chain or an error is thrown.\n", {
2733
0
                {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A valid blockhash"},
2734
0
            }},
2735
0
            RPCArg{"scanobjects", RPCArg::Type::ARR, RPCArg::Optional::NO, "The list of descriptors (scan objects) to examine for activity. Every scan object is either a string descriptor or an object:",
2736
0
                {
2737
0
                    {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
2738
0
                    output_descriptor_obj,
2739
0
                },
2740
0
                RPCArgOptions{.oneline_description="[scanobjects,...]"},
2741
0
            },
2742
0
            {"include_mempool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to include unconfirmed activity"},
2743
0
        },
2744
0
        RPCResult{
2745
0
            RPCResult::Type::OBJ, "", "", {
2746
0
                {RPCResult::Type::ARR, "activity", "events", {
2747
0
                    {RPCResult::Type::OBJ, "", "", {
2748
0
                        {RPCResult::Type::STR, "type", "always 'spend'"},
2749
0
                        {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the spent output"},
2750
0
                        {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The blockhash this spend appears in (omitted if unconfirmed)"},
2751
0
                        {RPCResult::Type::NUM, "height", /*optional=*/true, "Height of the spend (omitted if unconfirmed)"},
2752
0
                        {RPCResult::Type::STR_HEX, "spend_txid", "The txid of the spending transaction"},
2753
0
                        {RPCResult::Type::NUM, "spend_vin", "The input index of the spend"},
2754
0
                        {RPCResult::Type::STR_HEX, "prevout_txid", "The txid of the prevout"},
2755
0
                        {RPCResult::Type::NUM, "prevout_vout", "The vout of the prevout"},
2756
0
                        {RPCResult::Type::OBJ, "prevout_spk", "", ScriptPubKeyDoc()},
2757
0
                    }},
2758
0
                    {RPCResult::Type::OBJ, "", "", {
2759
0
                        {RPCResult::Type::STR, "type", "always 'receive'"},
2760
0
                        {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " of the new output"},
2761
0
                        {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block that this receive is in (omitted if unconfirmed)"},
2762
0
                        {RPCResult::Type::NUM, "height", /*optional=*/true, "The height of the receive (omitted if unconfirmed)"},
2763
0
                        {RPCResult::Type::STR_HEX, "txid", "The txid of the receiving transaction"},
2764
0
                        {RPCResult::Type::NUM, "vout", "The vout of the receiving output"},
2765
0
                        {RPCResult::Type::OBJ, "output_spk", "", ScriptPubKeyDoc()},
2766
0
                    }},
2767
                    // TODO is the skip_type_check avoidable with a heterogeneous ARR?
2768
0
                }, {.skip_type_check=true}, },
2769
0
            },
2770
0
        },
2771
0
        RPCExamples{
2772
0
            HelpExampleCli("getdescriptoractivity", "'[\"000000000000000000001347062c12fded7c528943c8ce133987e2e2f5a840ee\"]' '[\"addr(bc1qzl6nsgqzu89a66l50cvwapnkw5shh23zarqkw9)\"]'")
2773
0
        },
2774
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2775
0
{
2776
0
    UniValue ret(UniValue::VOBJ);
2777
0
    UniValue activity(UniValue::VARR);
2778
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
2779
0
    ChainstateManager& chainman = EnsureChainman(node);
2780
2781
0
    struct CompareByHeightAscending {
2782
0
        bool operator()(const CBlockIndex* a, const CBlockIndex* b) const {
2783
0
            return a->nHeight < b->nHeight;
2784
0
        }
2785
0
    };
2786
2787
0
    std::set<const CBlockIndex*, CompareByHeightAscending> blockindexes_sorted;
2788
2789
0
    {
2790
        // Validate all given blockhashes, and ensure blocks are along a single chain.
2791
0
        LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2792
0
        for (const UniValue& blockhash : request.params[0].get_array().getValues()) {
2793
0
            uint256 bhash = ParseHashV(blockhash, "blockhash");
2794
0
            CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(bhash);
2795
0
            if (!pindex) {
2796
0
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2797
0
            }
2798
0
            if (!chainman.ActiveChain().Contains(pindex)) {
2799
0
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
2800
0
            }
2801
0
            blockindexes_sorted.insert(pindex);
2802
0
        }
2803
0
    }
2804
2805
0
    std::set<CScript> scripts_to_watch;
2806
2807
    // Determine scripts to watch.
2808
0
    for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
2809
0
        FlatSigningProvider provider;
2810
0
        std::vector<CScript> scripts = EvalDescriptorStringOrObject(scanobject, provider);
2811
2812
0
        for (const CScript& script : scripts) {
2813
0
            scripts_to_watch.insert(script);
2814
0
        }
2815
0
    }
2816
2817
0
    const auto AddSpend = [&](
2818
0
            const CScript& spk,
2819
0
            const CAmount val,
2820
0
            const CTransactionRef& tx,
2821
0
            int vin,
2822
0
            const CTxIn& txin,
2823
0
            const CBlockIndex* index
2824
0
            ) {
2825
0
        UniValue event(UniValue::VOBJ);
2826
0
        UniValue spkUv(UniValue::VOBJ);
2827
0
        ScriptToUniv(spk, /*out=*/spkUv, /*include_hex=*/true, /*include_address=*/true);
2828
2829
0
        event.pushKV("type", "spend");
2830
0
        event.pushKV("amount", ValueFromAmount(val));
2831
0
        if (index) {
2832
0
            event.pushKV("blockhash", index->GetBlockHash().ToString());
2833
0
            event.pushKV("height", index->nHeight);
2834
0
        }
2835
0
        event.pushKV("spend_txid", tx->GetHash().ToString());
2836
0
        event.pushKV("spend_vin", vin);
2837
0
        event.pushKV("prevout_txid", txin.prevout.hash.ToString());
2838
0
        event.pushKV("prevout_vout", txin.prevout.n);
2839
0
        event.pushKV("prevout_spk", spkUv);
2840
2841
0
        return event;
2842
0
    };
2843
2844
0
    const auto AddReceive = [&](const CTxOut& txout, const CBlockIndex* index, int vout, const CTransactionRef& tx) {
2845
0
        UniValue event(UniValue::VOBJ);
2846
0
        UniValue spkUv(UniValue::VOBJ);
2847
0
        ScriptToUniv(txout.scriptPubKey, /*out=*/spkUv, /*include_hex=*/true, /*include_address=*/true);
2848
2849
0
        event.pushKV("type", "receive");
2850
0
        event.pushKV("amount", ValueFromAmount(txout.nValue));
2851
0
        if (index) {
2852
0
            event.pushKV("blockhash", index->GetBlockHash().ToString());
2853
0
            event.pushKV("height", index->nHeight);
2854
0
        }
2855
0
        event.pushKV("txid", tx->GetHash().ToString());
2856
0
        event.pushKV("vout", vout);
2857
0
        event.pushKV("output_spk", spkUv);
2858
2859
0
        return event;
2860
0
    };
2861
2862
0
    BlockManager* blockman;
2863
0
    Chainstate& active_chainstate = chainman.ActiveChainstate();
2864
0
    {
2865
0
        LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2866
0
        blockman = CHECK_NONFATAL(&active_chainstate.m_blockman);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2867
0
    }
2868
2869
0
    for (const CBlockIndex* blockindex : blockindexes_sorted) {
2870
0
        const CBlock block{GetBlockChecked(chainman.m_blockman, *blockindex)};
2871
0
        const CBlockUndo block_undo{GetUndoChecked(*blockman, *blockindex)};
2872
2873
0
        for (size_t i = 0; i < block.vtx.size(); ++i) {
2874
0
            const auto& tx = block.vtx.at(i);
2875
2876
0
            if (!tx->IsCoinBase()) {
2877
                // skip coinbase; spends can't happen there.
2878
0
                const auto& txundo = block_undo.vtxundo.at(i - 1);
2879
2880
0
                for (size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2881
0
                    const auto& coin = txundo.vprevout.at(vin_idx);
2882
0
                    const auto& txin = tx->vin.at(vin_idx);
2883
0
                    if (scripts_to_watch.contains(coin.out.scriptPubKey)) {
2884
0
                        activity.push_back(AddSpend(
2885
0
                                    coin.out.scriptPubKey, coin.out.nValue, tx, vin_idx, txin, blockindex));
2886
0
                    }
2887
0
                }
2888
0
            }
2889
2890
0
            for (size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2891
0
                const auto& vout = tx->vout.at(vout_idx);
2892
0
                if (scripts_to_watch.contains(vout.scriptPubKey)) {
2893
0
                    activity.push_back(AddReceive(vout, blockindex, vout_idx, tx));
2894
0
                }
2895
0
            }
2896
0
        }
2897
0
    }
2898
2899
0
    bool search_mempool = true;
2900
0
    if (!request.params[2].isNull()) {
2901
0
        search_mempool = request.params[2].get_bool();
2902
0
    }
2903
2904
0
    if (search_mempool) {
2905
0
        const CTxMemPool& mempool = EnsureMemPool(node);
2906
0
        LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2907
0
        LOCK(mempool.cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2908
0
        const CCoinsViewCache& coins_view = &active_chainstate.CoinsTip();
2909
2910
0
        for (const CTxMemPoolEntry& e : mempool.entryAll()) {
2911
0
            const auto& tx = e.GetSharedTx();
2912
2913
0
            for (size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2914
0
                CScript scriptPubKey;
2915
0
                CAmount value;
2916
0
                const auto& txin = tx->vin.at(vin_idx);
2917
0
                std::optional<Coin> coin = coins_view.GetCoin(txin.prevout);
2918
2919
                // Check if the previous output is in the chain
2920
0
                if (!coin) {
2921
                    // If not found in the chain, check the mempool. Likely, this is a
2922
                    // child transaction of another transaction in the mempool.
2923
0
                    CTransactionRef prev_tx = CHECK_NONFATAL(mempool.get(txin.prevout.hash));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
2924
2925
0
                    if (txin.prevout.n >= prev_tx->vout.size()) {
2926
0
                        throw std::runtime_error("Invalid output index");
2927
0
                    }
2928
0
                    const CTxOut& out = prev_tx->vout[txin.prevout.n];
2929
0
                    scriptPubKey = out.scriptPubKey;
2930
0
                    value = out.nValue;
2931
0
                } else {
2932
                    // Coin found in the chain
2933
0
                    const CTxOut& out = coin->out;
2934
0
                    scriptPubKey = out.scriptPubKey;
2935
0
                    value = out.nValue;
2936
0
                }
2937
2938
0
                if (scripts_to_watch.contains(scriptPubKey)) {
2939
0
                    UniValue event(UniValue::VOBJ);
2940
0
                    activity.push_back(AddSpend(
2941
0
                                scriptPubKey, value, tx, vin_idx, txin, nullptr));
2942
0
                }
2943
0
            }
2944
2945
0
            for (size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2946
0
                const auto& vout = tx->vout.at(vout_idx);
2947
0
                if (scripts_to_watch.contains(vout.scriptPubKey)) {
2948
0
                    activity.push_back(AddReceive(vout, nullptr, vout_idx, tx));
2949
0
                }
2950
0
            }
2951
0
        }
2952
0
    }
2953
2954
0
    ret.pushKV("activity", activity);
2955
0
    return ret;
2956
0
},
2957
0
    };
2958
0
}
2959
2960
static RPCMethod getblockfilter()
2961
0
{
2962
0
    return RPCMethod{
2963
0
        "getblockfilter",
2964
0
        "Retrieve a BIP 157 content filter for a particular block.\n",
2965
0
                {
2966
0
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the block"},
2967
0
                    {"filtertype", RPCArg::Type::STR, RPCArg::Default{BlockFilterTypeName(BlockFilterType::BASIC)}, "The type name of the filter"},
2968
0
                },
2969
0
                RPCResult{
2970
0
                    RPCResult::Type::OBJ, "", "",
2971
0
                    {
2972
0
                        {RPCResult::Type::STR_HEX, "filter", "the hex-encoded filter data"},
2973
0
                        {RPCResult::Type::STR_HEX, "header", "the hex-encoded filter header"},
2974
0
                    }},
2975
0
                RPCExamples{
2976
0
                    HelpExampleCli("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2977
0
                    HelpExampleRpc("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2978
0
                },
2979
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2980
0
{
2981
0
    uint256 block_hash = ParseHashV(request.params[0], "blockhash");
2982
0
    auto filtertype_name{self.Arg<std::string_view>("filtertype")};
2983
2984
0
    BlockFilterType filtertype;
2985
0
    if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
2986
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
2987
0
    }
2988
2989
0
    BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
2990
0
    if (!index) {
2991
0
        throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
2992
0
    }
2993
2994
0
    const CBlockIndex* block_index;
2995
0
    bool block_was_connected;
2996
0
    {
2997
0
        ChainstateManager& chainman = EnsureAnyChainman(request.context);
2998
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
2999
0
        block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
3000
0
        if (!block_index) {
3001
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
3002
0
        }
3003
0
        block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
3004
0
    }
3005
3006
0
    bool index_ready = index->BlockUntilSyncedToCurrentChain();
3007
3008
0
    BlockFilter filter;
3009
0
    uint256 filter_header;
3010
0
    if (!index->LookupFilter(block_index, filter) ||
3011
0
        !index->LookupFilterHeader(block_index, filter_header)) {
3012
0
        int err_code;
3013
0
        std::string errmsg = "Filter not found.";
3014
3015
0
        if (!block_was_connected) {
3016
0
            err_code = RPC_INVALID_ADDRESS_OR_KEY;
3017
0
            errmsg += " Block was not connected to active chain.";
3018
0
        } else if (!index_ready) {
3019
0
            err_code = RPC_MISC_ERROR;
3020
0
            errmsg += " Block filters are still in the process of being indexed.";
3021
0
        } else {
3022
0
            err_code = RPC_INTERNAL_ERROR;
3023
0
            errmsg += " This error is unexpected and indicates index corruption.";
3024
0
        }
3025
3026
0
        throw JSONRPCError(err_code, errmsg);
3027
0
    }
3028
3029
0
    UniValue ret(UniValue::VOBJ);
3030
0
    ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
3031
0
    ret.pushKV("header", filter_header.GetHex());
3032
0
    return ret;
3033
0
},
3034
0
    };
3035
0
}
3036
3037
/**
3038
 * RAII class that disables the network in its constructor and enables it in its
3039
 * destructor.
3040
 */
3041
class NetworkDisable
3042
{
3043
    CConnman& m_connman;
3044
public:
3045
0
    NetworkDisable(CConnman& connman) : m_connman(connman) {
3046
0
        m_connman.SetNetworkActive(false);
3047
0
        if (m_connman.GetNetworkActive()) {
3048
0
            throw JSONRPCError(RPC_MISC_ERROR, "Network activity could not be suspended.");
3049
0
        }
3050
0
    };
3051
0
    ~NetworkDisable() {
3052
0
        m_connman.SetNetworkActive(true);
3053
0
    };
3054
};
3055
3056
/**
3057
 * RAII class that temporarily rolls back the local chain in it's constructor
3058
 * and rolls it forward again in it's destructor.
3059
 */
3060
class TemporaryRollback
3061
{
3062
    ChainstateManager& m_chainman;
3063
    const CBlockIndex& m_invalidate_index;
3064
public:
3065
0
    TemporaryRollback(ChainstateManager& chainman, const CBlockIndex& index) : m_chainman(chainman), m_invalidate_index(index) {
3066
0
        InvalidateBlock(m_chainman, m_invalidate_index.GetBlockHash());
3067
0
    };
3068
0
    ~TemporaryRollback() {
3069
0
        ReconsiderBlock(m_chainman, m_invalidate_index.GetBlockHash());
3070
0
    };
3071
};
3072
3073
/**
3074
 * Serialize the UTXO set to a file for loading elsewhere.
3075
 *
3076
 * @see SnapshotMetadata
3077
 */
3078
static RPCMethod dumptxoutset()
3079
0
{
3080
0
    return RPCMethod{
3081
0
        "dumptxoutset",
3082
0
        "Write the serialized UTXO set to a file. This can be used in loadtxoutset afterwards if this snapshot height is supported in the chainparams as well.\n\n"
3083
0
        "Unless the \"latest\" type is requested, the node will roll back to the requested height and network activity will be suspended during this process. "
3084
0
        "Because of this it is discouraged to interact with the node in any other way during the execution of this call to avoid inconsistent results and race conditions, particularly RPCs that interact with blockstorage.\n\n"
3085
0
        "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
3086
0
        {
3087
0
            {"path", RPCArg::Type::STR, RPCArg::Optional::NO, "Path to the output file. If relative, will be prefixed by datadir."},
3088
0
            {"type", RPCArg::Type::STR, RPCArg::Default(""), "The type of snapshot to create. Can be \"latest\" to create a snapshot of the current UTXO set or \"rollback\" to temporarily roll back the state of the node to a historical block before creating the snapshot of a historical UTXO set. This parameter can be omitted if a separate \"rollback\" named parameter is specified indicating the height or hash of a specific historical block. If \"rollback\" is specified and separate \"rollback\" named parameter is not specified, this will roll back to the latest valid snapshot block that can currently be loaded with loadtxoutset."},
3089
0
            {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
3090
0
                {
3091
0
                    {"rollback", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
3092
0
                        "Height or hash of the block to roll back to before creating the snapshot. Note: The further this number is from the tip, the longer this process will take. Consider setting a higher -rpcclienttimeout value in this case.",
3093
0
                    RPCArgOptions{.skip_type_check = true, .type_str = {"", "string or numeric"}}},
3094
0
                },
3095
0
            },
3096
0
        },
3097
0
        RPCResult{
3098
0
            RPCResult::Type::OBJ, "", "",
3099
0
                {
3100
0
                    {RPCResult::Type::NUM, "coins_written", "the number of coins written in the snapshot"},
3101
0
                    {RPCResult::Type::STR_HEX, "base_hash", "the hash of the base of the snapshot"},
3102
0
                    {RPCResult::Type::NUM, "base_height", "the height of the base of the snapshot"},
3103
0
                    {RPCResult::Type::STR, "path", "the absolute path that the snapshot was written to"},
3104
0
                    {RPCResult::Type::STR_HEX, "txoutset_hash", "the hash of the UTXO set contents"},
3105
0
                    {RPCResult::Type::NUM, "nchaintx", "the number of transactions in the chain up to and including the base block"},
3106
0
                }
3107
0
        },
3108
0
        RPCExamples{
3109
0
            HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat latest") +
3110
0
            HelpExampleCli("-rpcclienttimeout=0 dumptxoutset", "utxo.dat rollback") +
3111
0
            HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset", R"(utxo.dat rollback=853456)")
3112
0
        },
3113
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
3114
0
{
3115
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
3116
0
    const CBlockIndex* tip{WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Tip())};
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
3117
0
    const CBlockIndex* target_index{nullptr};
3118
0
    const auto snapshot_type{self.Arg<std::string_view>("type")};
3119
0
    const UniValue options{request.params[2].isNull() ? UniValue::VOBJ : request.params[2]};
3120
0
    if (options.exists("rollback")) {
3121
0
        if (!snapshot_type.empty() && snapshot_type != "rollback") {
3122
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid snapshot type \"%s\" specified with rollback option", snapshot_type));
Line
Count
Source
1172
0
#define strprintf tfm::format
3123
0
        }
3124
0
        target_index = ParseHashOrHeight(options["rollback"], *node.chainman);
3125
0
    } else if (snapshot_type == "rollback") {
3126
0
        auto snapshot_heights = node.chainman->GetParams().GetAvailableSnapshotHeights();
3127
0
        CHECK_NONFATAL(snapshot_heights.size() > 0);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
3128
0
        auto max_height = std::max_element(snapshot_heights.begin(), snapshot_heights.end());
3129
0
        target_index = ParseHashOrHeight(*max_height, *node.chainman);
3130
0
    } else if (snapshot_type == "latest") {
3131
0
        target_index = tip;
3132
0
    } else {
3133
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid snapshot type \"%s\" specified. Please specify \"rollback\" or \"latest\"", snapshot_type));
Line
Count
Source
1172
0
#define strprintf tfm::format
3134
0
    }
3135
3136
0
    const ArgsManager& args{EnsureAnyArgsman(request.context)};
3137
0
    const fs::path path = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(self.Arg<std::string_view>("path")));
3138
0
    const auto path_info{fs::status(path)};
3139
    // Write to a temporary path and then move into `path` on completion
3140
    // to avoid confusion due to an interruption. If a named pipe passed, write directly to it.
3141
0
    const fs::path temppath = fs::is_fifo(path_info) ? path : path + ".incomplete";
3142
3143
0
    if (fs::exists(path_info) && !fs::is_fifo(path_info)) {
3144
0
        throw JSONRPCError(
3145
0
            RPC_INVALID_PARAMETER,
3146
0
            path.utf8string() + " already exists. If you are sure this is what you want, "
3147
0
            "move it out of the way first");
3148
0
    }
3149
3150
0
    FILE* file{fsbridge::fopen(temppath, "wb")};
3151
0
    AutoFile afile{file};
3152
0
    if (afile.IsNull()) {
3153
0
        throw JSONRPCError(
3154
0
            RPC_INVALID_PARAMETER,
3155
0
            "Couldn't open file " + temppath.utf8string() + " for writing.");
3156
0
    }
3157
3158
0
    CConnman& connman = EnsureConnman(node);
3159
0
    const CBlockIndex* invalidate_index{nullptr};
3160
0
    std::optional<NetworkDisable> disable_network;
3161
0
    std::optional<TemporaryRollback> temporary_rollback;
3162
3163
    // If the user wants to dump the txoutset of the current tip, we don't have
3164
    // to roll back at all
3165
0
    if (target_index != tip) {
3166
        // If the node is running in pruned mode we ensure all necessary block
3167
        // data is available before starting to roll back.
3168
0
        if (node.chainman->m_blockman.IsPruneMode()) {
3169
0
            LOCK(node.chainman->GetMutex());
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
3170
0
            const CBlockIndex* current_tip{node.chainman->ActiveChain().Tip()};
3171
0
            const CBlockIndex& first_block{node.chainman->m_blockman.GetFirstBlock(*current_tip, /*status_mask=*/BLOCK_HAVE_MASK)};
3172
0
            if (first_block.nHeight > target_index->nHeight) {
3173
0
                throw JSONRPCError(RPC_MISC_ERROR, "Could not roll back to requested height since necessary block data is already pruned.");
3174
0
            }
3175
0
        }
3176
3177
        // Suspend network activity for the duration of the process when we are
3178
        // rolling back the chain to get a utxo set from a past height. We do
3179
        // this so we don't punish peers that send us that send us data that
3180
        // seems wrong in this temporary state. For example a normal new block
3181
        // would be classified as a block connecting an invalid block.
3182
        // Skip if the network is already disabled because this
3183
        // automatically re-enables the network activity at the end of the
3184
        // process which may not be what the user wants.
3185
0
        if (connman.GetNetworkActive()) {
3186
0
            disable_network.emplace(connman);
3187
0
        }
3188
3189
0
        invalidate_index = WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Next(target_index));
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
3190
0
        temporary_rollback.emplace(*node.chainman, *invalidate_index);
3191
0
    }
3192
3193
0
    Chainstate* chainstate;
3194
0
    std::unique_ptr<CCoinsViewCursor> cursor;
3195
0
    CCoinsStats stats;
3196
0
    {
3197
        // Lock the chainstate before calling PrepareUtxoSnapshot, to be able
3198
        // to get a UTXO database cursor while the chain is pointing at the
3199
        // target block. After that, release the lock while calling
3200
        // WriteUTXOSnapshot. The cursor will remain valid and be used by
3201
        // WriteUTXOSnapshot to write a consistent snapshot even if the
3202
        // chainstate changes.
3203
0
        LOCK(node.chainman->GetMutex());
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
3204
0
        chainstate = &node.chainman->ActiveChainstate();
3205
        // In case there is any issue with a block being read from disk we need
3206
        // to stop here, otherwise the dump could still be created for the wrong
3207
        // height.
3208
        // The new tip could also not be the target block if we have a stale
3209
        // sister block of invalidate_index. This block (or a descendant) would
3210
        // be activated as the new tip and we would not get to new_tip_index.
3211
0
        if (target_index != chainstate->m_chain.Tip()) {
3212
0
            LogWarning("dumptxoutset failed to roll back to requested height, reverting to tip.\n");
Line
Count
Source
98
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
3213
0
            throw JSONRPCError(RPC_MISC_ERROR, "Could not roll back to requested height.");
3214
0
        } else {
3215
0
            std::tie(cursor, stats, tip) = PrepareUTXOSnapshot(*chainstate, node.rpc_interruption_point);
3216
0
        }
3217
0
    }
3218
3219
0
    UniValue result = WriteUTXOSnapshot(*chainstate,
3220
0
                                        cursor.get(),
3221
0
                                        &stats,
3222
0
                                        tip,
3223
0
                                        std::move(afile),
3224
0
                                        path,
3225
0
                                        temppath,
3226
0
                                        node.rpc_interruption_point);
3227
0
    if (!fs::is_fifo(path_info)) {
3228
0
        fs::rename(temppath, path);
3229
0
    }
3230
3231
0
    result.pushKV("path", path.utf8string());
3232
0
    return result;
3233
0
},
3234
0
    };
3235
0
}
3236
3237
std::tuple<std::unique_ptr<CCoinsViewCursor>, CCoinsStats, const CBlockIndex*>
3238
PrepareUTXOSnapshot(
3239
    Chainstate& chainstate,
3240
    const std::function<void()>& interruption_point)
3241
0
{
3242
0
    std::unique_ptr<CCoinsViewCursor> pcursor;
3243
0
    std::optional<CCoinsStats> maybe_stats;
3244
0
    const CBlockIndex* tip;
3245
3246
0
    {
3247
        // We need to lock cs_main to ensure that the coinsdb isn't written to
3248
        // between (i) flushing coins cache to disk (coinsdb), (ii) getting stats
3249
        // based upon the coinsdb, and (iii) constructing a cursor to the
3250
        // coinsdb for use in WriteUTXOSnapshot.
3251
        //
3252
        // Cursors returned by leveldb iterate over snapshots, so the contents
3253
        // of the pcursor will not be affected by simultaneous writes during
3254
        // use below this block.
3255
        //
3256
        // See discussion here:
3257
        //   https://github.com/bitcoin/bitcoin/pull/15606#discussion_r274479369
3258
        //
3259
0
        AssertLockHeld(::cs_main);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
3260
3261
0
        chainstate.ForceFlushStateToDisk(/*wipe_cache=*/false);
3262
3263
0
        maybe_stats = GetUTXOStats(&chainstate.CoinsDB(), chainstate.m_blockman, CoinStatsHashType::HASH_SERIALIZED, interruption_point);
3264
0
        if (!maybe_stats) {
3265
0
            throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
3266
0
        }
3267
3268
0
        pcursor = chainstate.CoinsDB().Cursor();
3269
0
        tip = CHECK_NONFATAL(chainstate.m_blockman.LookupBlockIndex(maybe_stats->hashBlock));
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
3270
0
    }
3271
3272
0
    return {std::move(pcursor), *CHECK_NONFATAL(maybe_stats), tip};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
3273
0
}
3274
3275
UniValue WriteUTXOSnapshot(
3276
    Chainstate& chainstate,
3277
    CCoinsViewCursor* pcursor,
3278
    CCoinsStats* maybe_stats,
3279
    const CBlockIndex* tip,
3280
    AutoFile&& afile,
3281
    const fs::path& path,
3282
    const fs::path& temppath,
3283
    const std::function<void()>& interruption_point)
3284
0
{
3285
0
    LOG_TIME_SECONDS(strprintf("writing UTXO snapshot at height %s (%s) to file %s (via %s)",
Line
Count
Source
108
0
    BCLog::Timer<std::chrono::seconds> UNIQUE_NAME(logging_timer)(__func__, end_msg)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
3286
0
        tip->nHeight, tip->GetBlockHash().ToString(),
3287
0
        fs::PathToString(path), fs::PathToString(temppath)));
3288
3289
0
    SnapshotMetadata metadata{chainstate.m_chainman.GetParams().MessageStart(), tip->GetBlockHash(), maybe_stats->coins_count};
3290
3291
0
    afile << metadata;
3292
3293
0
    COutPoint key;
3294
0
    Txid last_hash;
3295
0
    Coin coin;
3296
0
    unsigned int iter{0};
3297
0
    size_t written_coins_count{0};
3298
0
    std::vector<std::pair<uint32_t, Coin>> coins;
3299
3300
    // To reduce space the serialization format of the snapshot avoids
3301
    // duplication of tx hashes. The code takes advantage of the guarantee by
3302
    // leveldb that keys are lexicographically sorted.
3303
    // In the coins vector we collect all coins that belong to a certain tx hash
3304
    // (key.hash) and when we have them all (key.hash != last_hash) we write
3305
    // them to file using the below lambda function.
3306
    // See also https://github.com/bitcoin/bitcoin/issues/25675
3307
0
    auto write_coins_to_file = [&](AutoFile& afile, const Txid& last_hash, const std::vector<std::pair<uint32_t, Coin>>& coins, size_t& written_coins_count) {
3308
0
        afile << last_hash;
3309
0
        WriteCompactSize(afile, coins.size());
3310
0
        for (const auto& [n, coin] : coins) {
3311
0
            WriteCompactSize(afile, n);
3312
0
            afile << coin;
3313
0
            ++written_coins_count;
3314
0
        }
3315
0
    };
3316
3317
0
    pcursor->GetKey(key);
3318
0
    last_hash = key.hash;
3319
0
    while (pcursor->Valid()) {
3320
0
        if (iter % 5000 == 0) interruption_point();
3321
0
        ++iter;
3322
0
        if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3323
0
            if (key.hash != last_hash) {
3324
0
                write_coins_to_file(afile, last_hash, coins, written_coins_count);
3325
0
                last_hash = key.hash;
3326
0
                coins.clear();
3327
0
            }
3328
0
            coins.emplace_back(key.n, coin);
3329
0
        }
3330
0
        pcursor->Next();
3331
0
    }
3332
3333
0
    if (!coins.empty()) {
3334
0
        write_coins_to_file(afile, last_hash, coins, written_coins_count);
3335
0
    }
3336
3337
0
    CHECK_NONFATAL(written_coins_count == maybe_stats->coins_count);
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
3338
3339
0
    if (afile.fclose() != 0) {
3340
0
        throw std::ios_base::failure(
3341
0
            strprintf("Error closing %s: %s", fs::PathToString(temppath), SysErrorString(errno)));
Line
Count
Source
1172
0
#define strprintf tfm::format
3342
0
    }
3343
3344
0
    UniValue result(UniValue::VOBJ);
3345
0
    result.pushKV("coins_written", written_coins_count);
3346
0
    result.pushKV("base_hash", tip->GetBlockHash().ToString());
3347
0
    result.pushKV("base_height", tip->nHeight);
3348
0
    result.pushKV("path", path.utf8string());
3349
0
    result.pushKV("txoutset_hash", maybe_stats->hashSerialized.ToString());
3350
0
    result.pushKV("nchaintx", tip->m_chain_tx_count);
3351
0
    return result;
3352
0
}
3353
3354
UniValue CreateUTXOSnapshot(
3355
    node::NodeContext& node,
3356
    Chainstate& chainstate,
3357
    AutoFile&& afile,
3358
    const fs::path& path,
3359
    const fs::path& tmppath)
3360
0
{
3361
0
    auto [cursor, stats, tip]{WITH_LOCK(::cs_main, return PrepareUTXOSnapshot(chainstate, node.rpc_interruption_point))};
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
3362
0
    return WriteUTXOSnapshot(chainstate,
3363
0
                             cursor.get(),
3364
0
                             &stats,
3365
0
                             tip,
3366
0
                             std::move(afile),
3367
0
                             path,
3368
0
                             tmppath,
3369
0
                             node.rpc_interruption_point);
3370
0
}
3371
3372
static RPCMethod loadtxoutset()
3373
0
{
3374
0
    return RPCMethod{
3375
0
        "loadtxoutset",
3376
0
        "Load the serialized UTXO set from a file.\n"
3377
0
        "Once this snapshot is loaded, its contents will be "
3378
0
        "deserialized into a second chainstate data structure, which is then used to sync to "
3379
0
        "the network's tip. "
3380
0
        "Meanwhile, the original chainstate will complete the initial block download process in "
3381
0
        "the background, eventually validating up to the block that the snapshot is based upon.\n\n"
3382
3383
0
        "The result is a usable bitcoind instance that is current with the network tip in a "
3384
0
        "matter of minutes rather than hours. UTXO snapshot are typically obtained from "
3385
0
        "third-party sources (HTTP, torrent, etc.) which is reasonable since their "
3386
0
        "contents are always checked by hash.\n\n"
3387
3388
0
        "You can find more information on this process in the `assumeutxo` design "
3389
0
        "document (<https://github.com/bitcoin/bitcoin/blob/master/doc/design/assumeutxo.md>).",
3390
0
        {
3391
0
            {"path",
3392
0
                RPCArg::Type::STR,
3393
0
                RPCArg::Optional::NO,
3394
0
                "path to the snapshot file. If relative, will be prefixed by datadir."},
3395
0
        },
3396
0
        RPCResult{
3397
0
            RPCResult::Type::OBJ, "", "",
3398
0
                {
3399
0
                    {RPCResult::Type::NUM, "coins_loaded", "the number of coins loaded from the snapshot"},
3400
0
                    {RPCResult::Type::STR_HEX, "tip_hash", "the hash of the base of the snapshot"},
3401
0
                    {RPCResult::Type::NUM, "base_height", "the height of the base of the snapshot"},
3402
0
                    {RPCResult::Type::STR, "path", "the absolute path that the snapshot was loaded from"},
3403
0
                }
3404
0
        },
3405
0
        RPCExamples{
3406
0
            HelpExampleCli("-rpcclienttimeout=0 loadtxoutset", "utxo.dat")
3407
0
        },
3408
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
3409
0
{
3410
0
    NodeContext& node = EnsureAnyNodeContext(request.context);
3411
0
    ChainstateManager& chainman = EnsureChainman(node);
3412
0
    const fs::path path{AbsPathForConfigVal(EnsureArgsman(node), fs::u8path(self.Arg<std::string_view>("path")))};
3413
3414
0
    FILE* file{fsbridge::fopen(path, "rb")};
3415
0
    AutoFile afile{file};
3416
0
    if (afile.IsNull()) {
3417
0
        throw JSONRPCError(
3418
0
            RPC_INVALID_PARAMETER,
3419
0
            "Couldn't open file " + path.utf8string() + " for reading.");
3420
0
    }
3421
3422
0
    SnapshotMetadata metadata{chainman.GetParams().MessageStart()};
3423
0
    try {
3424
0
        afile >> metadata;
3425
0
    } catch (const std::ios_base::failure& e) {
3426
0
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Unable to parse metadata: %s", e.what()));
Line
Count
Source
1172
0
#define strprintf tfm::format
3427
0
    }
3428
3429
0
    auto activation_result{chainman.ActivateSnapshot(afile, metadata, false)};
3430
0
    if (!activation_result) {
3431
0
        throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Unable to load UTXO snapshot: %s. (%s)", util::ErrorString(activation_result).original, path.utf8string()));
Line
Count
Source
1172
0
#define strprintf tfm::format
3432
0
    }
3433
3434
    // Because we can't provide historical blocks during tip or background sync.
3435
    // Update local services to reflect we are a limited peer until we are fully sync.
3436
0
    node.connman->RemoveLocalServices(NODE_NETWORK);
3437
    // Setting the limited state is usually redundant because the node can always
3438
    // provide the last 288 blocks, but it doesn't hurt to set it.
3439
0
    node.connman->AddLocalServices(NODE_NETWORK_LIMITED);
3440
3441
0
    CBlockIndex& snapshot_index{*CHECK_NONFATAL(*activation_result)};
Line
Count
Source
113
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
3442
3443
0
    UniValue result(UniValue::VOBJ);
3444
0
    result.pushKV("coins_loaded", metadata.m_coins_count);
3445
0
    result.pushKV("tip_hash", snapshot_index.GetBlockHash().ToString());
3446
0
    result.pushKV("base_height", snapshot_index.nHeight);
3447
0
    result.pushKV("path", fs::PathToString(path));
3448
0
    return result;
3449
0
},
3450
0
    };
3451
0
}
3452
3453
const std::vector<RPCResult> RPCHelpForChainstate{
3454
    {RPCResult::Type::NUM, "blocks", "number of blocks in this chainstate"},
3455
    {RPCResult::Type::STR_HEX, "bestblockhash", "blockhash of the tip"},
3456
    {RPCResult::Type::STR_HEX, "bits", "nBits: compact representation of the block difficulty target"},
3457
    {RPCResult::Type::STR_HEX, "target", "The difficulty target"},
3458
    {RPCResult::Type::NUM, "difficulty", "difficulty of the tip"},
3459
    {RPCResult::Type::NUM, "verificationprogress", "progress towards the network tip"},
3460
    {RPCResult::Type::STR_HEX, "snapshot_blockhash", /*optional=*/true, "the base block of the snapshot this chainstate is based on, if any"},
3461
    {RPCResult::Type::NUM, "coins_db_cache_bytes", "size of the coinsdb cache"},
3462
    {RPCResult::Type::NUM, "coins_tip_cache_bytes", "size of the coinstip cache"},
3463
    {RPCResult::Type::BOOL, "validated", "whether the chainstate is fully validated. True if all blocks in the chainstate were validated, false if the chain is based on a snapshot and the snapshot has not yet been validated."},
3464
};
3465
3466
static RPCMethod getchainstates()
3467
0
{
3468
0
return RPCMethod{
3469
0
        "getchainstates",
3470
0
        "Return information about chainstates.\n",
3471
0
        {},
3472
0
        RPCResult{
3473
0
            RPCResult::Type::OBJ, "", "", {
3474
0
                {RPCResult::Type::NUM, "headers", "the number of headers seen so far"},
3475
0
                {RPCResult::Type::ARR, "chainstates", "list of the chainstates ordered by work, with the most-work (active) chainstate last", {{RPCResult::Type::OBJ, "", "", RPCHelpForChainstate},}},
3476
0
            }
3477
0
        },
3478
0
        RPCExamples{
3479
0
            HelpExampleCli("getchainstates", "")
3480
0
    + HelpExampleRpc("getchainstates", "")
3481
0
        },
3482
0
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
3483
0
{
3484
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
3485
0
    UniValue obj(UniValue::VOBJ);
3486
3487
0
    ChainstateManager& chainman = EnsureAnyChainman(request.context);
3488
3489
0
    auto make_chain_data = [&](const Chainstate& cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
3490
0
        AssertLockHeld(::cs_main);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
3491
0
        UniValue data(UniValue::VOBJ);
3492
0
        if (!cs.m_chain.Tip()) {
3493
0
            return data;
3494
0
        }
3495
0
        const CChain& chain = cs.m_chain;
3496
0
        const CBlockIndex* tip = chain.Tip();
3497
3498
0
        data.pushKV("blocks", chain.Height());
3499
0
        data.pushKV("bestblockhash",         tip->GetBlockHash().GetHex());
3500
0
        data.pushKV("bits", strprintf("%08x", tip->nBits));
Line
Count
Source
1172
0
#define strprintf tfm::format
3501
0
        data.pushKV("target", GetTarget(*tip, chainman.GetConsensus().powLimit).GetHex());
3502
0
        data.pushKV("difficulty", GetDifficulty(*tip));
3503
0
        data.pushKV("verificationprogress", chainman.GuessVerificationProgress(tip));
3504
0
        data.pushKV("coins_db_cache_bytes",  cs.m_coinsdb_cache_size_bytes);
3505
0
        data.pushKV("coins_tip_cache_bytes", cs.m_coinstip_cache_size_bytes);
3506
0
        if (cs.m_from_snapshot_blockhash) {
3507
0
            data.pushKV("snapshot_blockhash", cs.m_from_snapshot_blockhash->ToString());
3508
0
        }
3509
0
        data.pushKV("validated", cs.m_assumeutxo == Assumeutxo::VALIDATED);
3510
0
        return data;
3511
0
    };
3512
3513
0
    obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
3514
0
    UniValue obj_chainstates{UniValue::VARR};
3515
0
    if (const Chainstate * cs{chainman.HistoricalChainstate()}) {
3516
0
        obj_chainstates.push_back(make_chain_data(*cs));
3517
0
    }
3518
0
    obj_chainstates.push_back(make_chain_data(chainman.CurrentChainstate()));
3519
0
    obj.pushKV("chainstates", std::move(obj_chainstates));
3520
0
    return obj;
3521
0
}
3522
0
    };
3523
0
}
3524
3525
3526
void RegisterBlockchainRPCCommands(CRPCTable& t)
3527
0
{
3528
0
    static const CRPCCommand commands[]{
3529
0
        {"blockchain", &getblockchaininfo},
3530
0
        {"blockchain", &getchaintxstats},
3531
0
        {"blockchain", &getblockstats},
3532
0
        {"blockchain", &getbestblockhash},
3533
0
        {"blockchain", &getblockcount},
3534
0
        {"blockchain", &getblock},
3535
0
        {"blockchain", &getblockfrompeer},
3536
0
        {"blockchain", &getblockhash},
3537
0
        {"blockchain", &getblockheader},
3538
0
        {"blockchain", &getchaintips},
3539
0
        {"blockchain", &getdifficulty},
3540
0
        {"blockchain", &getdeploymentinfo},
3541
0
        {"blockchain", &gettxout},
3542
0
        {"blockchain", &gettxoutsetinfo},
3543
0
        {"blockchain", &pruneblockchain},
3544
0
        {"blockchain", &verifychain},
3545
0
        {"blockchain", &preciousblock},
3546
0
        {"blockchain", &scantxoutset},
3547
0
        {"blockchain", &scanblocks},
3548
0
        {"blockchain", &getdescriptoractivity},
3549
0
        {"blockchain", &getblockfilter},
3550
0
        {"blockchain", &dumptxoutset},
3551
0
        {"blockchain", &loadtxoutset},
3552
0
        {"blockchain", &getchainstates},
3553
0
        {"hidden", &invalidateblock},
3554
0
        {"hidden", &reconsiderblock},
3555
0
        {"blockchain", &waitfornewblock},
3556
0
        {"blockchain", &waitforblock},
3557
0
        {"blockchain", &waitforblockheight},
3558
0
        {"hidden", &syncwithvalidationinterfacequeue},
3559
0
    };
3560
0
    for (const auto& c : commands) {
3561
0
        t.appendCommand(c.name, &c);
3562
0
    }
3563
0
}