Coverage Report

Created: 2026-11-13 17:38

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