fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

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