Coverage Report

Created: 2026-07-23 20:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/util.cpp
Line
Count
Source
1
// Copyright (c) 2017-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <chain.h>
6
#include <common/args.h>
7
#include <common/messages.h>
8
#include <common/types.h>
9
#include <consensus/amount.h>
10
#include <core_io.h>
11
#include <key_io.h>
12
#include <node/types.h>
13
#include <outputtype.h>
14
#include <pow.h>
15
#include <rpc/util.h>
16
#include <script/descriptor.h>
17
#include <script/interpreter.h>
18
#include <script/signingprovider.h>
19
#include <script/solver.h>
20
#include <tinyformat.h>
21
#include <uint256.h>
22
#include <univalue.h>
23
#include <util/check.h>
24
#include <util/result.h>
25
#include <util/strencodings.h>
26
#include <util/string.h>
27
#include <util/translation.h>
28
29
#include <algorithm>
30
#include <iterator>
31
#include <string_view>
32
#include <tuple>
33
#include <utility>
34
35
using common::PSBTError;
36
using common::PSBTErrorString;
37
using common::TransactionErrorString;
38
using node::TransactionError;
39
using util::Join;
40
using util::SplitString;
41
using util::TrimString;
42
43
const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
44
const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
45
46
std::string GetAllOutputTypes()
47
53.7k
{
48
53.7k
    std::vector<std::string> ret;
49
53.7k
    using U = std::underlying_type_t<TxoutType>;
50
644k
    for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
51
590k
        ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
52
590k
    }
53
53.7k
    return Join(ret, ", ");
54
53.7k
}
55
56
void RPCTypeCheckObj(const UniValue& o,
57
    const std::map<std::string, UniValueType>& typesExpected,
58
    bool fAllowNull,
59
    bool fStrict)
60
2.01k
{
61
21.3k
    for (const auto& t : typesExpected) {
62
21.3k
        const UniValue& v = o.find_value(t.first);
63
21.3k
        if (!fAllowNull && v.isNull())
64
11
            throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
65
66
21.3k
        if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull())))
67
25
            throw JSONRPCError(RPC_TYPE_ERROR, strprintf("JSON value of type %s for field %s is not of expected type %s", uvTypeName(v.type()),  t.first, uvTypeName(t.second.type)));
68
21.3k
    }
69
70
1.98k
    if (fStrict)
71
1.01k
    {
72
1.01k
        for (const std::string& k : o.getKeys())
73
2.15k
        {
74
2.15k
            if (!typesExpected.contains(k))
75
4
            {
76
4
                std::string err = strprintf("Unexpected key %s", k);
77
4
                throw JSONRPCError(RPC_TYPE_ERROR, err);
78
4
            }
79
2.15k
        }
80
1.01k
    }
81
1.98k
}
82
83
int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool)
84
6.64k
{
85
6.64k
    if (!arg.isNull()) {
86
5.19k
        if (arg.isBool()) {
87
3.43k
            if (!allow_bool) {
88
2
                throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed");
89
2
            }
90
3.43k
            return arg.get_bool(); // true = 1
91
3.43k
        } else {
92
1.75k
            return arg.getInt<int>();
93
1.75k
        }
94
5.19k
    }
95
1.45k
    return default_verbosity;
96
6.64k
}
97
98
CAmount AmountFromValue(const UniValue& value, int decimals)
99
50.6k
{
100
50.6k
    if (!value.isNum() && !value.isStr())
101
12
        throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
102
50.6k
    int64_t amount;
103
50.6k
    if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
104
83
        throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
105
50.5k
    if (!MoneyRange(amount))
106
12
        throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
107
50.5k
    return amount;
108
50.5k
}
109
110
CFeeRate ParseFeeRate(const UniValue& json)
111
34.2k
{
112
34.2k
    CAmount val{AmountFromValue(json)};
113
34.2k
    if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted");
114
34.2k
    return CFeeRate{val};
115
34.2k
}
116
117
uint256 ParseHashV(const UniValue& v, std::string_view name)
118
29.8k
{
119
29.8k
    const std::string& strHex(v.get_str());
120
29.8k
    if (auto rv{uint256::FromHex(strHex)}) return *rv;
121
29
    if (auto expected_len{uint256::size() * 2}; strHex.length() != expected_len) {
122
16
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", name, expected_len, strHex.length(), strHex));
123
16
    }
124
13
    throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
125
29
}
126
uint256 ParseHashO(const UniValue& o, std::string_view strKey)
127
6.53k
{
128
6.53k
    return ParseHashV(o.find_value(strKey), strKey);
129
6.53k
}
130
std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name)
131
961
{
132
961
    std::string strHex;
133
961
    if (v.isStr())
134
961
        strHex = v.get_str();
135
961
    if (!IsHex(strHex))
136
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
137
957
    return ParseHex(strHex);
138
961
}
139
std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey)
140
600
{
141
600
    return ParseHexV(o.find_value(strKey), strKey);
142
600
}
143
144
namespace {
145
146
/**
147
 * Quote an argument for shell.
148
 *
149
 * @note This is intended for help, not for security-sensitive purposes.
150
 */
151
std::string ShellQuote(const std::string& s)
152
3.33k
{
153
3.33k
    std::string result;
154
3.33k
    result.reserve(s.size() * 2);
155
237k
    for (const char ch: s) {
156
237k
        if (ch == '\'') {
157
1
            result += "'\''";
158
237k
        } else {
159
237k
            result += ch;
160
237k
        }
161
237k
    }
162
3.33k
    return "'" + result + "'";
163
3.33k
}
164
165
/**
166
 * Shell-quotes the argument if it needs quoting, else returns it literally, to save typing.
167
 *
168
 * @note This is intended for help, not for security-sensitive purposes.
169
 */
170
std::string ShellQuoteIfNeeded(const std::string& s)
171
13.6k
{
172
89.1k
    for (const char ch: s) {
173
89.1k
        if (ch == ' ' || ch == '\'' || ch == '"') {
174
3.33k
            return ShellQuote(s);
175
3.33k
        }
176
89.1k
    }
177
178
10.3k
    return s;
179
13.6k
}
180
181
}
182
183
std::string HelpExampleCli(const std::string& methodname, const std::string& args)
184
719k
{
185
719k
    return "> bitcoin-cli " + methodname + " " + args + "\n";
186
719k
}
187
188
std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
189
5.66k
{
190
5.66k
    std::string result = "> bitcoin-cli -named " + methodname;
191
13.6k
    for (const auto& argpair: args) {
192
13.6k
        const auto& value = argpair.second.isStr()
193
13.6k
                ? argpair.second.get_str()
194
13.6k
                : argpair.second.write();
195
13.6k
        result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
196
13.6k
    }
197
5.66k
    result += "\n";
198
5.66k
    return result;
199
5.66k
}
200
201
std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
202
473k
{
203
473k
    return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
204
473k
        "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
205
473k
}
206
207
std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
208
3.19k
{
209
3.19k
    UniValue params(UniValue::VOBJ);
210
8.71k
    for (const auto& param: args) {
211
8.71k
        params.pushKV(param.first, param.second);
212
8.71k
    }
213
214
3.19k
    return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
215
3.19k
           "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
216
3.19k
}
217
218
// Converts a hex string to a public key if possible
219
CPubKey HexToPubKey(const std::string& hex_in)
220
568
{
221
568
    if (!IsHex(hex_in)) {
222
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be a hex string");
223
1
    }
224
567
    if (hex_in.length() != 66 && hex_in.length() != 130) {
225
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must have a length of either 33 or 65 bytes");
226
1
    }
227
566
    CPubKey vchPubKey(ParseHex(hex_in));
228
566
    if (!vchPubKey.IsFullyValid()) {
229
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be cryptographically valid.");
230
0
    }
231
566
    return vchPubKey;
232
566
}
233
234
// Creates a multisig address from a given list of public keys, number of signatures required, and the address type
235
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out)
236
83
{
237
    // Gather public keys
238
83
    if (required < 1) {
239
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
240
0
    }
241
83
    if ((int)pubkeys.size() < required) {
242
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required));
243
0
    }
244
83
    if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
245
2
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG));
246
2
    }
247
248
81
    script_out = GetScriptForMultisig(required, pubkeys);
249
250
    // Check if any keys are uncompressed. If so, the type is legacy
251
480
    for (const CPubKey& pk : pubkeys) {
252
480
        if (!pk.IsCompressed()) {
253
18
            type = OutputType::LEGACY;
254
18
            break;
255
18
        }
256
480
    }
257
258
81
    if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
259
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE)));
260
1
    }
261
262
    // Make the address
263
80
    CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
264
265
80
    return dest;
266
81
}
267
268
class DescribeAddressVisitor
269
{
270
public:
271
    explicit DescribeAddressVisitor() = default;
272
273
    UniValue operator()(const CNoDestination& dest) const
274
0
    {
275
0
        return UniValue(UniValue::VOBJ);
276
0
    }
277
278
    UniValue operator()(const PubKeyDestination& dest) const
279
0
    {
280
0
        return UniValue(UniValue::VOBJ);
281
0
    }
282
283
    UniValue operator()(const PKHash& keyID) const
284
101
    {
285
101
        UniValue obj(UniValue::VOBJ);
286
101
        obj.pushKV("isscript", false);
287
101
        obj.pushKV("iswitness", false);
288
101
        return obj;
289
101
    }
290
291
    UniValue operator()(const ScriptHash& scriptID) const
292
126
    {
293
126
        UniValue obj(UniValue::VOBJ);
294
126
        obj.pushKV("isscript", true);
295
126
        obj.pushKV("iswitness", false);
296
126
        return obj;
297
126
    }
298
299
    UniValue operator()(const WitnessV0KeyHash& id) const
300
501
    {
301
501
        UniValue obj(UniValue::VOBJ);
302
501
        obj.pushKV("isscript", false);
303
501
        obj.pushKV("iswitness", true);
304
501
        obj.pushKV("witness_version", 0);
305
501
        obj.pushKV("witness_program", HexStr(id));
306
501
        return obj;
307
501
    }
308
309
    UniValue operator()(const WitnessV0ScriptHash& id) const
310
43
    {
311
43
        UniValue obj(UniValue::VOBJ);
312
43
        obj.pushKV("isscript", true);
313
43
        obj.pushKV("iswitness", true);
314
43
        obj.pushKV("witness_version", 0);
315
43
        obj.pushKV("witness_program", HexStr(id));
316
43
        return obj;
317
43
    }
318
319
    UniValue operator()(const WitnessV1Taproot& tap) const
320
123
    {
321
123
        UniValue obj(UniValue::VOBJ);
322
123
        obj.pushKV("isscript", true);
323
123
        obj.pushKV("iswitness", true);
324
123
        obj.pushKV("witness_version", 1);
325
123
        obj.pushKV("witness_program", HexStr(tap));
326
123
        return obj;
327
123
    }
328
329
    UniValue operator()(const PayToAnchor& anchor) const
330
1
    {
331
1
        UniValue obj(UniValue::VOBJ);
332
1
        obj.pushKV("isscript", true);
333
1
        obj.pushKV("iswitness", true);
334
1
        return obj;
335
1
    }
336
337
    UniValue operator()(const WitnessUnknown& id) const
338
5
    {
339
5
        UniValue obj(UniValue::VOBJ);
340
5
        obj.pushKV("iswitness", true);
341
5
        obj.pushKV("witness_version", id.GetWitnessVersion());
342
5
        obj.pushKV("witness_program", HexStr(id.GetWitnessProgram()));
343
5
        return obj;
344
5
    }
345
};
346
347
UniValue DescribeAddress(const CTxDestination& dest)
348
900
{
349
900
    return std::visit(DescribeAddressVisitor(), dest);
350
900
}
351
352
/**
353
 * Returns a sighash value corresponding to the passed in argument.
354
 *
355
 * @pre The sighash argument should be string or null.
356
*/
357
std::optional<int> ParseSighashString(const UniValue& sighash)
358
1.05k
{
359
1.05k
    if (sighash.isNull()) {
360
971
        return std::nullopt;
361
971
    }
362
85
    const auto result{SighashFromStr(sighash.get_str())};
363
85
    if (!result) {
364
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, util::ErrorString(result).original);
365
4
    }
366
81
    return result.value();
367
85
}
368
369
unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
370
333
{
371
333
    const int target{value.getInt<int>()};
372
333
    const unsigned int unsigned_target{static_cast<unsigned int>(target)};
373
333
    if (target < 1 || unsigned_target > max_target) {
374
31
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
375
31
    }
376
302
    return unsigned_target;
377
333
}
378
379
RPCErrorCode RPCErrorFromPSBTError(PSBTError err)
380
15
{
381
15
    switch (err) {
382
0
        case PSBTError::UNSUPPORTED:
383
0
            return RPC_INVALID_PARAMETER;
384
14
        case PSBTError::SIGHASH_MISMATCH:
385
14
            return RPC_DESERIALIZATION_ERROR;
386
1
        default: break;
387
15
    }
388
1
    return RPC_TRANSACTION_ERROR;
389
15
}
390
391
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
392
4.34k
{
393
4.34k
    switch (terr) {
394
4.32k
        case TransactionError::MEMPOOL_REJECTED:
395
4.32k
            return RPC_TRANSACTION_REJECTED;
396
3
        case TransactionError::ALREADY_IN_UTXO_SET:
397
3
            return RPC_VERIFY_ALREADY_IN_UTXO_SET;
398
5
        case TransactionError::PRIVATE_BROADCAST_FULL:
399
5
            return RPC_LIMIT_EXCEEDED;
400
12
        default: break;
401
4.34k
    }
402
12
    return RPC_TRANSACTION_ERROR;
403
4.34k
}
404
405
UniValue JSONRPCPSBTError(PSBTError err)
406
15
{
407
15
    return JSONRPCError(RPCErrorFromPSBTError(err), PSBTErrorString(err).original);
408
15
}
409
410
UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
411
4.34k
{
412
4.34k
    if (err_string.length() > 0) {
413
4.33k
        return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
414
4.33k
    } else {
415
15
        return JSONRPCError(RPCErrorFromTransactionError(terr), TransactionErrorString(terr).original);
416
15
    }
417
4.34k
}
418
419
/**
420
 * A pair of strings that can be aligned (through padding) with other Sections
421
 * later on
422
 */
423
struct Section {
424
    Section(const std::string& left, const std::string& right)
425
20.4k
        : m_left{left}, m_right{right} {}
426
    std::string m_left;
427
    const std::string m_right;
428
};
429
430
/**
431
 * Keeps track of RPCArgs by transforming them into sections for the purpose
432
 * of serializing everything to a single string
433
 */
434
struct Sections {
435
    std::vector<Section> m_sections;
436
    size_t m_max_pad{0};
437
438
    void PushSection(const Section& s)
439
18.5k
    {
440
18.5k
        m_max_pad = std::max(m_max_pad, s.m_left.size());
441
18.5k
        m_sections.push_back(s);
442
18.5k
    }
443
444
    /**
445
     * Recursive helper to translate an RPCArg into sections
446
     */
447
    // NOLINTNEXTLINE(misc-no-recursion)
448
    void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
449
3.19k
    {
450
3.19k
        const auto indent = std::string(current_indent, ' ');
451
3.19k
        const auto indent_next = std::string(current_indent + 2, ' ');
452
3.19k
        const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
453
3.19k
        const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion
454
455
3.19k
        switch (arg.m_type) {
456
486
        case RPCArg::Type::STR_HEX:
457
1.31k
        case RPCArg::Type::STR:
458
1.90k
        case RPCArg::Type::NUM:
459
2.05k
        case RPCArg::Type::AMOUNT:
460
2.11k
        case RPCArg::Type::RANGE:
461
2.58k
        case RPCArg::Type::BOOL:
462
2.65k
        case RPCArg::Type::OBJ_NAMED_PARAMS: {
463
2.65k
            if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion
464
679
            auto left = indent;
465
679
            if (arg.m_opts.type_str.size() != 0 && push_name) {
466
3
                left += "\"" + arg.GetName() + "\": " + arg.m_opts.type_str.at(0);
467
676
            } else {
468
676
                left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false);
469
676
            }
470
679
            left += ",";
471
679
            PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)});
472
679
            break;
473
2.65k
        }
474
164
        case RPCArg::Type::OBJ:
475
204
        case RPCArg::Type::OBJ_USER_KEYS: {
476
204
            const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
477
204
            PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
478
476
            for (const auto& arg_inner : arg.m_inner) {
479
476
                Push(arg_inner, current_indent + 2, OuterType::OBJ);
480
476
            }
481
204
            if (arg.m_type != RPCArg::Type::OBJ) {
482
40
                PushSection({indent_next + "...", ""});
483
40
            }
484
204
            PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
485
204
            break;
486
164
        }
487
332
        case RPCArg::Type::ARR: {
488
332
            auto left = indent;
489
332
            left += push_name ? "\"" + arg.GetName() + "\": " : "";
490
332
            left += "[";
491
332
            const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
492
332
            PushSection({left, right});
493
437
            for (const auto& arg_inner : arg.m_inner) {
494
437
                Push(arg_inner, current_indent + 2, OuterType::ARR);
495
437
            }
496
332
            PushSection({indent_next + "...", ""});
497
332
            PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
498
332
            break;
499
164
        }
500
3.19k
        } // no default case, so the compiler can warn about missing cases
501
3.19k
    }
502
503
    /**
504
     * Concatenate all sections with proper padding
505
     */
506
    std::string ToString() const
507
3.53k
    {
508
3.53k
        std::string ret;
509
3.53k
        const size_t pad = m_max_pad + 4;
510
20.4k
        for (const auto& s : m_sections) {
511
            // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a
512
            // brace like {, }, [, or ]
513
20.4k
            CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
514
20.4k
            if (s.m_right.empty()) {
515
5.46k
                ret += s.m_left;
516
5.46k
                ret += "\n";
517
5.46k
                continue;
518
5.46k
            }
519
520
14.9k
            std::string left = s.m_left;
521
14.9k
            left.resize(pad, ' ');
522
14.9k
            ret += left;
523
524
            // Properly pad after newlines
525
14.9k
            std::string right;
526
14.9k
            size_t begin = 0;
527
14.9k
            size_t new_line_pos = s.m_right.find_first_of('\n');
528
16.8k
            while (true) {
529
16.8k
                right += s.m_right.substr(begin, new_line_pos - begin);
530
16.8k
                if (new_line_pos == std::string::npos) {
531
14.8k
                    break; //No new line
532
14.8k
                }
533
2.05k
                right += "\n" + std::string(pad, ' ');
534
2.05k
                begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
535
2.05k
                if (begin == std::string::npos) {
536
158
                    break; // Empty line
537
158
                }
538
1.89k
                new_line_pos = s.m_right.find_first_of('\n', begin + 1);
539
1.89k
            }
540
14.9k
            ret += right;
541
14.9k
            ret += "\n";
542
14.9k
        }
543
3.53k
        return ret;
544
3.53k
    }
545
};
546
547
RPCMethod::RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
548
19
    : RPCMethod{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
549
550
RPCMethod::RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
551
520k
    : m_name{std::move(name)},
552
520k
      m_fun{std::move(fun)},
553
520k
      m_description{std::move(description)},
554
520k
      m_args{std::move(args)},
555
520k
      m_results{std::move(results)},
556
520k
      m_examples{std::move(examples)}
557
520k
{
558
    // Map of parameter names and types just used to check whether the names are
559
    // unique. Parameter names always need to be unique, with the exception that
560
    // there can be pairs of POSITIONAL and NAMED parameters with the same name.
561
520k
    enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
562
520k
    std::map<std::string, int> param_names;
563
564
969k
    for (const auto& arg : m_args) {
565
969k
        std::vector<std::string> names = SplitString(arg.m_names, '|');
566
        // Should have unique named arguments
567
980k
        for (const std::string& name : names) {
568
980k
            auto& param_type = param_names[name];
569
980k
            CHECK_NONFATAL(!(param_type & POSITIONAL));
570
980k
            CHECK_NONFATAL(!(param_type & NAMED_ONLY));
571
980k
            param_type |= POSITIONAL;
572
980k
        }
573
969k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
574
114k
            for (const auto& inner : arg.m_inner) {
575
114k
                std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
576
114k
                for (const std::string& inner_name : inner_names) {
577
114k
                    auto& param_type = param_names[inner_name];
578
114k
                    CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
579
114k
                    CHECK_NONFATAL(!(param_type & NAMED));
580
114k
                    CHECK_NONFATAL(!(param_type & NAMED_ONLY));
581
114k
                    param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
582
114k
                }
583
114k
            }
584
19.4k
        }
585
        // Default value type should match argument type only when defined
586
969k
        if (arg.m_fallback.index() == 2) {
587
344k
            const RPCArg::Type type = arg.m_type;
588
344k
            [&]() {
589
344k
                switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) {
590
0
                case UniValue::VOBJ:
591
0
                    CHECK_NONFATAL(type == RPCArg::Type::OBJ);
592
0
                    return;
593
2.11k
                case UniValue::VARR:
594
2.11k
                    CHECK_NONFATAL(type == RPCArg::Type::ARR);
595
2.11k
                    return;
596
123k
                case UniValue::VSTR:
597
123k
                    CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
598
123k
                    return;
599
73.5k
                case UniValue::VNUM:
600
73.5k
                    CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
601
73.5k
                    return;
602
144k
                case UniValue::VBOOL:
603
144k
                    CHECK_NONFATAL(type == RPCArg::Type::BOOL);
604
144k
                    return;
605
0
                case UniValue::VNULL:
606
                    // Null values are accepted in all arguments
607
0
                    return;
608
344k
                } // no default case, so the compiler can warn about missing cases
609
344k
                NONFATAL_UNREACHABLE();
610
344k
            }();
611
344k
        }
612
969k
    }
613
520k
}
614
615
std::string RPCResults::ToDescriptionString() const
616
1.10k
{
617
1.10k
    std::string result;
618
1.32k
    for (const auto& r : m_results) {
619
1.32k
        if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
620
1.31k
        if (r.m_cond.empty()) {
621
979
            result += "\nResult:\n";
622
979
        } else {
623
337
            result += "\nResult (" + r.m_cond + "):\n";
624
337
        }
625
1.31k
        Sections sections;
626
1.31k
        r.ToSections(sections);
627
1.31k
        result += sections.ToString();
628
1.31k
    }
629
1.10k
    return result;
630
1.10k
}
631
632
std::string RPCExamples::ToDescriptionString() const
633
1.10k
{
634
1.10k
    return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
635
1.10k
}
636
637
UniValue RPCMethod::HandleRequest(const JSONRPCRequest& request) const
638
197k
{
639
197k
    if (request.mode == JSONRPCRequest::GET_ARGS) {
640
348
        return GetArgMap();
641
348
    }
642
    /*
643
     * Check if the given request is valid according to this command or if
644
     * the user is asking for help information, and throw help when appropriate.
645
     */
646
196k
    if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
647
1.10k
        throw HelpResult{ToString()};
648
1.10k
    }
649
195k
    UniValue arg_mismatch{UniValue::VOBJ};
650
573k
    for (size_t i{0}; i < m_args.size(); ++i) {
651
377k
        const auto& arg{m_args.at(i)};
652
377k
        UniValue match{arg.MatchesType(request.params[i])};
653
377k
        if (!match.isTrue()) {
654
30
            arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match));
655
30
        }
656
377k
    }
657
195k
    if (!arg_mismatch.empty()) {
658
28
        throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
659
28
    }
660
195k
    CHECK_NONFATAL(m_req == nullptr);
661
195k
    m_req = &request;
662
195k
    UniValue ret = m_fun(*this, request);
663
195k
    m_req = nullptr;
664
195k
    if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
665
189k
        UniValue mismatch{UniValue::VARR};
666
203k
        for (const auto& res : m_results.m_results) {
667
203k
            UniValue match{res.MatchesType(ret)};
668
203k
            if (match.isTrue()) {
669
189k
                mismatch.setNull();
670
189k
                break;
671
189k
            }
672
14.1k
            mismatch.push_back(std::move(match));
673
14.1k
        }
674
189k
        if (!mismatch.isNull()) {
675
0
            std::string explain{
676
0
                mismatch.empty() ? "no possible results defined" :
677
0
                mismatch.size() == 1 ? mismatch[0].write(4) :
678
0
                mismatch.write(4)};
679
0
            throw std::runtime_error{
680
0
                STR_INTERNAL_BUG(strprintf("RPC call \"%s\" returned incorrect type:\n%s", m_name, explain)),
681
0
            };
682
0
        }
683
189k
    }
684
195k
    return ret;
685
195k
}
686
687
using CheckFn = void(const RPCArg&);
688
static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
689
45.2k
{
690
45.2k
    CHECK_NONFATAL(i < params.size());
691
45.2k
    const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
692
45.2k
    const RPCArg& param{params.at(i)};
693
45.2k
    if (check) check(param);
694
695
45.2k
    if (!arg.isNull()) return &arg;
696
20.2k
    if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
697
17.9k
    return &std::get<RPCArg::Default>(param.m_fallback);
698
20.2k
}
699
700
static void CheckRequiredOrDefault(const RPCArg& param)
701
42.4k
{
702
    // Must use `Arg<Type>(key)` to get the argument or its default value.
703
42.4k
    const bool required{
704
42.4k
        std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
705
42.4k
    };
706
42.4k
    CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
707
42.4k
}
708
709
#define TMPL_INST(check_param, ret_type, return_code)       \
710
    template <>                                             \
711
    ret_type RPCMethod::ArgValue<ret_type>(size_t i) const \
712
45.2k
    {                                                       \
713
45.2k
        const UniValue* maybe_arg{                          \
714
45.2k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
45.2k
        };                                                  \
716
45.2k
        return return_code                                  \
717
45.2k
    }                                                       \
Unexecuted instantiation: UniValue const* RPCMethod::ArgValue<UniValue const*>(unsigned long) const
std::optional<double> RPCMethod::ArgValue<std::optional<double>>(unsigned long) const
Line
Count
Source
712
723
    {                                                       \
713
723
        const UniValue* maybe_arg{                          \
714
723
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
723
        };                                                  \
716
1.44k
        return return_code                                  \
717
723
    }                                                       \
std::optional<bool> RPCMethod::ArgValue<std::optional<bool>>(unsigned long) const
Line
Count
Source
712
763
    {                                                       \
713
763
        const UniValue* maybe_arg{                          \
714
763
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
763
        };                                                  \
716
1.52k
        return return_code                                  \
717
763
    }                                                       \
std::optional<long> RPCMethod::ArgValue<std::optional<long>>(unsigned long) const
Line
Count
Source
712
106
    {                                                       \
713
106
        const UniValue* maybe_arg{                          \
714
106
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
106
        };                                                  \
716
212
        return return_code                                  \
717
106
    }                                                       \
std::optional<std::basic_string_view<char, std::char_traits<char>>> RPCMethod::ArgValue<std::optional<std::basic_string_view<char, std::char_traits<char>>>>(unsigned long) const
Line
Count
Source
712
1.22k
    {                                                       \
713
1.22k
        const UniValue* maybe_arg{                          \
714
1.22k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
1.22k
        };                                                  \
716
2.44k
        return return_code                                  \
717
1.22k
    }                                                       \
UniValue const& RPCMethod::ArgValue<UniValue const&>(unsigned long) const
Line
Count
Source
712
34.2k
    {                                                       \
713
34.2k
        const UniValue* maybe_arg{                          \
714
34.2k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
34.2k
        };                                                  \
716
34.2k
        return return_code                                  \
717
34.2k
    }                                                       \
bool RPCMethod::ArgValue<bool>(unsigned long) const
Line
Count
Source
712
845
    {                                                       \
713
845
        const UniValue* maybe_arg{                          \
714
845
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
845
        };                                                  \
716
845
        return return_code                                  \
717
845
    }                                                       \
int RPCMethod::ArgValue<int>(unsigned long) const
Line
Count
Source
712
1.41k
    {                                                       \
713
1.41k
        const UniValue* maybe_arg{                          \
714
1.41k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
1.41k
        };                                                  \
716
1.41k
        return return_code                                  \
717
1.41k
    }                                                       \
unsigned long RPCMethod::ArgValue<unsigned long>(unsigned long) const
Line
Count
Source
712
829
    {                                                       \
713
829
        const UniValue* maybe_arg{                          \
714
829
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
829
        };                                                  \
716
829
        return return_code                                  \
717
829
    }                                                       \
unsigned int RPCMethod::ArgValue<unsigned int>(unsigned long) const
Line
Count
Source
712
975
    {                                                       \
713
975
        const UniValue* maybe_arg{                          \
714
975
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
975
        };                                                  \
716
975
        return return_code                                  \
717
975
    }                                                       \
std::basic_string_view<char, std::char_traits<char>> RPCMethod::ArgValue<std::basic_string_view<char, std::char_traits<char>>>(unsigned long) const
Line
Count
Source
712
4.07k
    {                                                       \
713
4.07k
        const UniValue* maybe_arg{                          \
714
4.07k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
715
4.07k
        };                                                  \
716
4.07k
        return return_code                                  \
717
4.07k
    }                                                       \
718
    void force_semicolon(ret_type)
719
720
// Optional arg (without default). Can also be called on required args, if needed.
721
TMPL_INST(nullptr, const UniValue*, maybe_arg;);
722
TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
723
TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
724
TMPL_INST(nullptr, std::optional<int64_t>, maybe_arg ? std::optional{maybe_arg->getInt<int64_t>()} : std::nullopt;);
725
TMPL_INST(nullptr, std::optional<std::string_view>, maybe_arg ? std::optional<std::string_view>{maybe_arg->get_str()} : std::nullopt;);
726
727
// Required arg or optional arg with default value.
728
TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg););
729
TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
730
TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
731
TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
732
TMPL_INST(CheckRequiredOrDefault, uint32_t, CHECK_NONFATAL(maybe_arg)->getInt<uint32_t>(););
733
TMPL_INST(CheckRequiredOrDefault, std::string_view, CHECK_NONFATAL(maybe_arg)->get_str(););
734
735
bool RPCMethod::IsValidNumArgs(size_t num_args) const
736
195k
{
737
195k
    size_t num_required_args = 0;
738
408k
    for (size_t n = m_args.size(); n > 0; --n) {
739
337k
        if (!m_args.at(n - 1).IsOptional()) {
740
124k
            num_required_args = n;
741
124k
            break;
742
124k
        }
743
337k
    }
744
195k
    return num_required_args <= num_args && num_args <= m_args.size();
745
195k
}
746
747
std::vector<std::pair<std::string, bool>> RPCMethod::GetArgNames() const
748
161k
{
749
161k
    std::vector<std::pair<std::string, bool>> ret;
750
161k
    ret.reserve(m_args.size());
751
294k
    for (const auto& arg : m_args) {
752
294k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
753
47.3k
            for (const auto& inner : arg.m_inner) {
754
47.3k
                ret.emplace_back(inner.m_names, /*named_only=*/true);
755
47.3k
            }
756
8.80k
        }
757
294k
        ret.emplace_back(arg.m_names, /*named_only=*/false);
758
294k
    }
759
161k
    return ret;
760
161k
}
761
762
size_t RPCMethod::GetParamIndex(std::string_view key) const
763
45.2k
{
764
45.2k
    auto it{std::find_if(
765
93.7k
        m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;}
766
45.2k
    )};
767
768
45.2k
    CHECK_NONFATAL(it != m_args.end());  // TODO: ideally this is checked at compile time
769
45.2k
    return std::distance(m_args.begin(), it);
770
45.2k
}
771
772
std::string RPCMethod::ToString() const
773
1.10k
{
774
1.10k
    std::string ret;
775
776
    // Oneline summary
777
1.10k
    ret += m_name;
778
1.10k
    bool was_optional{false};
779
1.93k
    for (const auto& arg : m_args) {
780
1.93k
        if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
781
1.92k
        const bool optional = arg.IsOptional();
782
1.92k
        ret += " ";
783
1.92k
        if (optional) {
784
1.08k
            if (!was_optional) ret += "( ";
785
1.08k
            was_optional = true;
786
1.08k
        } else {
787
846
            if (was_optional) ret += ") ";
788
846
            was_optional = false;
789
846
        }
790
1.92k
        ret += arg.ToString(/*oneline=*/true);
791
1.92k
    }
792
1.10k
    if (was_optional) ret += " )";
793
794
    // Description
795
1.10k
    CHECK_NONFATAL(!m_description.starts_with('\n'));  // Historically \n was required, but reject it for new code.
796
1.10k
    ret += "\n\n" + TrimString(m_description) + "\n";
797
798
    // Arguments
799
1.10k
    Sections sections;
800
1.10k
    Sections named_only_sections;
801
3.03k
    for (size_t i{0}; i < m_args.size(); ++i) {
802
1.93k
        const auto& arg = m_args.at(i);
803
1.93k
        if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
804
805
        // Push named argument name and description
806
1.92k
        sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
807
1.92k
        sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
808
809
        // Recursively push nested args
810
1.92k
        sections.Push(arg);
811
812
        // Push named-only argument sections
813
1.92k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
814
351
            for (const auto& arg_inner : arg.m_inner) {
815
351
                named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
816
351
                named_only_sections.Push(arg_inner);
817
351
            }
818
66
        }
819
1.92k
    }
820
821
1.10k
    if (!sections.m_sections.empty()) ret += "\nArguments:\n";
822
1.10k
    ret += sections.ToString();
823
1.10k
    if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
824
1.10k
    ret += named_only_sections.ToString();
825
826
    // Result
827
1.10k
    ret += m_results.ToDescriptionString();
828
829
    // Examples
830
1.10k
    ret += m_examples.ToDescriptionString();
831
832
1.10k
    return ret;
833
1.10k
}
834
835
UniValue RPCMethod::GetArgMap() const
836
348
{
837
348
    UniValue arr{UniValue::VARR};
838
839
896
    auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
840
896
        UniValue map{UniValue::VARR};
841
896
        map.push_back(rpc_name);
842
896
        map.push_back(pos);
843
896
        map.push_back(arg_name);
844
896
        map.push_back(type == RPCArg::Type::STR ||
845
896
                      type == RPCArg::Type::STR_HEX);
846
896
        arr.push_back(std::move(map));
847
896
    };
848
849
1.03k
    for (int i{0}; i < int(m_args.size()); ++i) {
850
690
        const auto& arg = m_args.at(i);
851
690
        std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
852
694
        for (const auto& arg_name : arg_names) {
853
694
            push_back_arg_info(m_name, i, arg_name, arg.m_type);
854
694
            if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
855
202
                for (const auto& inner : arg.m_inner) {
856
202
                    std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
857
202
                    for (const std::string& inner_name : inner_names) {
858
202
                        push_back_arg_info(m_name, i, inner_name, inner.m_type);
859
202
                    }
860
202
                }
861
28
            }
862
694
        }
863
690
    }
864
348
    return arr;
865
348
}
866
867
static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
868
198k
{
869
198k
    using Type = RPCArg::Type;
870
198k
    switch (type) {
871
68.4k
    case Type::STR_HEX:
872
119k
    case Type::STR: {
873
119k
        return UniValue::VSTR;
874
68.4k
    }
875
46.4k
    case Type::NUM: {
876
46.4k
        return UniValue::VNUM;
877
68.4k
    }
878
21.0k
    case Type::AMOUNT: {
879
        // VNUM or VSTR, checked inside AmountFromValue()
880
21.0k
        return std::nullopt;
881
68.4k
    }
882
80
    case Type::RANGE: {
883
        // VNUM or VARR, checked inside ParseRange()
884
80
        return std::nullopt;
885
68.4k
    }
886
3.55k
    case Type::BOOL: {
887
3.55k
        return UniValue::VBOOL;
888
68.4k
    }
889
2.41k
    case Type::OBJ:
890
3.06k
    case Type::OBJ_NAMED_PARAMS:
891
3.15k
    case Type::OBJ_USER_KEYS: {
892
3.15k
        return UniValue::VOBJ;
893
3.06k
    }
894
5.62k
    case Type::ARR: {
895
5.62k
        return UniValue::VARR;
896
3.06k
    }
897
198k
    } // no default case, so the compiler can warn about missing cases
898
198k
    NONFATAL_UNREACHABLE();
899
198k
}
900
901
UniValue RPCArg::MatchesType(const UniValue& request) const
902
377k
{
903
377k
    if (m_opts.skip_type_check) return true;
904
369k
    if (IsOptional() && request.isNull()) return true;
905
198k
    const auto exp_type{ExpectedType(m_type)};
906
198k
    if (!exp_type) return true; // nothing to check
907
908
177k
    if (*exp_type != request.getType()) {
909
30
        return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type));
910
30
    }
911
177k
    return true;
912
177k
}
913
914
std::string RPCArg::GetFirstName() const
915
5.73k
{
916
5.73k
    return m_names.substr(0, m_names.find('|'));
917
5.73k
}
918
919
std::string RPCArg::GetName() const
920
93.8k
{
921
93.8k
    CHECK_NONFATAL(std::string::npos == m_names.find('|'));
922
93.8k
    return m_names;
923
93.8k
}
924
925
bool RPCArg::IsOptional() const
926
709k
{
927
709k
    if (m_fallback.index() != 0) {
928
392k
        return true;
929
392k
    } else {
930
317k
        return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
931
317k
    }
932
709k
}
933
934
std::string RPCArg::ToDescriptionString(bool is_named_arg) const
935
3.19k
{
936
3.19k
    std::string ret;
937
3.19k
    ret += "(";
938
3.19k
    if (m_opts.type_str.size() != 0) {
939
32
        ret += m_opts.type_str.at(1);
940
3.15k
    } else {
941
3.15k
        switch (m_type) {
942
486
        case Type::STR_HEX:
943
1.31k
        case Type::STR: {
944
1.31k
            ret += "string";
945
1.31k
            break;
946
486
        }
947
559
        case Type::NUM: {
948
559
            ret += "numeric";
949
559
            break;
950
486
        }
951
147
        case Type::AMOUNT: {
952
147
            ret += "numeric or string";
953
147
            break;
954
486
        }
955
60
        case Type::RANGE: {
956
60
            ret += "numeric or array";
957
60
            break;
958
486
        }
959
478
        case Type::BOOL: {
960
478
            ret += "boolean";
961
478
            break;
962
486
        }
963
164
        case Type::OBJ:
964
230
        case Type::OBJ_NAMED_PARAMS:
965
270
        case Type::OBJ_USER_KEYS: {
966
270
            ret += "json object";
967
270
            break;
968
230
        }
969
332
        case Type::ARR: {
970
332
            ret += "json array";
971
332
            break;
972
230
        }
973
3.15k
        } // no default case, so the compiler can warn about missing cases
974
3.15k
    }
975
3.19k
    if (m_fallback.index() == 1) {
976
383
        ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
977
2.80k
    } else if (m_fallback.index() == 2) {
978
898
        ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
979
1.91k
    } else {
980
1.91k
        switch (std::get<RPCArg::Optional>(m_fallback)) {
981
775
        case RPCArg::Optional::OMITTED: {
982
775
            if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
983
            // nothing to do. Element is treated as if not present and has no default value
984
775
            break;
985
0
        }
986
1.13k
        case RPCArg::Optional::NO: {
987
1.13k
            ret += ", required";
988
1.13k
            break;
989
0
        }
990
1.91k
        } // no default case, so the compiler can warn about missing cases
991
1.91k
    }
992
3.19k
    ret += ")";
993
3.19k
    if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
994
3.19k
    ret += m_description.empty() ? "" : " " + m_description;
995
3.19k
    return ret;
996
3.19k
}
997
998
// NOLINTNEXTLINE(misc-no-recursion)
999
void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1000
12.7k
{
1001
    // Indentation
1002
12.7k
    const std::string indent(current_indent, ' ');
1003
12.7k
    const std::string indent_next(current_indent + 2, ' ');
1004
1005
    // Elements in a JSON structure (dictionary or array) are separated by a comma
1006
12.7k
    const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1007
1008
    // The key name if recursed into a dictionary
1009
12.7k
    const std::string maybe_key{
1010
12.7k
        outer_type == OuterType::OBJ ?
1011
10.2k
            "\"" + this->m_key_name + "\" : " :
1012
12.7k
            ""};
1013
1014
    // Format description with type
1015
12.7k
    const auto Description = [&](const std::string& type) {
1016
11.7k
        return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
1017
11.7k
               (this->m_description.empty() ? "" : " " + this->m_description);
1018
11.7k
    };
1019
1020
    // Ensure at least one visible field exists when elision is used
1021
12.7k
    const auto elision_has_description{[](const std::vector<RPCResult>& inner) {
1022
3.00k
        return std::ranges::any_of(inner, [](const auto& res) {
1023
3.00k
            return !std::holds_alternative<HelpElisionSkip>(res.m_opts.print_elision);
1024
3.00k
        });
1025
2.94k
    }};
1026
1027
12.7k
    if (const auto* text = std::get_if<std::string>(&m_opts.print_elision)) {
1028
95
        sections.PushSection({indent + "..." + maybe_separator, *text});
1029
95
        return;
1030
95
    }
1031
12.6k
    if (std::holds_alternative<HelpElisionSkip>(m_opts.print_elision)) {
1032
984
        return;
1033
984
    }
1034
1035
11.7k
    switch (m_type) {
1036
36
    case Type::ANY: {
1037
36
        sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("any")});
1038
36
        return;
1039
0
    }
1040
139
    case Type::NONE: {
1041
139
        sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
1042
139
        return;
1043
0
    }
1044
2.07k
    case Type::STR: {
1045
2.07k
        sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
1046
2.07k
        return;
1047
0
    }
1048
547
    case Type::STR_AMOUNT: {
1049
547
        sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1050
547
        return;
1051
0
    }
1052
1.91k
    case Type::STR_HEX: {
1053
1.91k
        sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
1054
1.91k
        return;
1055
0
    }
1056
2.94k
    case Type::NUM: {
1057
2.94k
        sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1058
2.94k
        return;
1059
0
    }
1060
357
    case Type::NUM_TIME: {
1061
357
        sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
1062
357
        return;
1063
0
    }
1064
728
    case Type::BOOL: {
1065
728
        sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
1066
728
        return;
1067
0
    }
1068
17
    case Type::ARR_FIXED:
1069
1.11k
    case Type::ARR: {
1070
1.11k
        sections.PushSection({indent + maybe_key + "[", Description("json array")});
1071
1.17k
        for (const auto& i : m_inner) {
1072
1.17k
            i.ToSections(sections, OuterType::ARR, current_indent + 2);
1073
1.17k
        }
1074
1.11k
        CHECK_NONFATAL(!m_inner.empty());
1075
1.11k
        CHECK_NONFATAL(elision_has_description(m_inner));
1076
1.11k
        if (m_type == Type::ARR && !std::holds_alternative<std::string>(m_inner.back().m_opts.print_elision)) {
1077
1.09k
            sections.PushSection({indent_next + "...", ""});
1078
1.09k
        } else {
1079
            // Remove final comma, which would be invalid JSON
1080
20
            sections.m_sections.back().m_left.pop_back();
1081
20
        }
1082
1.11k
        sections.PushSection({indent + "]" + maybe_separator, ""});
1083
1.11k
        return;
1084
17
    }
1085
202
    case Type::OBJ_DYN:
1086
1.84k
    case Type::OBJ: {
1087
1.84k
        if (m_inner.empty()) {
1088
18
            sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
1089
18
            return;
1090
18
        }
1091
1.83k
        CHECK_NONFATAL(elision_has_description(m_inner));
1092
1.83k
        sections.PushSection({indent + maybe_key + "{", Description("json object")});
1093
10.2k
        for (const auto& i : m_inner) {
1094
10.2k
            i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1095
10.2k
        }
1096
1.83k
        if (m_type == Type::OBJ_DYN) {
1097
            // If the dictionary keys are dynamic, use three dots for continuation
1098
202
            sections.PushSection({indent_next + "...", ""});
1099
1.62k
        } else {
1100
            // Remove final comma, which would be invalid JSON
1101
1.62k
            sections.m_sections.back().m_left.pop_back();
1102
1.62k
        }
1103
1.83k
        sections.PushSection({indent + "}" + maybe_separator, ""});
1104
1.83k
        return;
1105
1.84k
    }
1106
11.7k
    } // no default case, so the compiler can warn about missing cases
1107
11.7k
    NONFATAL_UNREACHABLE();
1108
11.7k
}
1109
1110
static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1111
5.16M
{
1112
5.16M
    using Type = RPCResult::Type;
1113
5.16M
    switch (type) {
1114
24
    case Type::ANY: {
1115
24
        return std::nullopt;
1116
0
    }
1117
17.2k
    case Type::NONE: {
1118
17.2k
        return UniValue::VNULL;
1119
0
    }
1120
623k
    case Type::STR:
1121
2.10M
    case Type::STR_HEX: {
1122
2.10M
        return UniValue::VSTR;
1123
623k
    }
1124
1.44M
    case Type::NUM:
1125
1.69M
    case Type::STR_AMOUNT:
1126
1.91M
    case Type::NUM_TIME: {
1127
1.91M
        return UniValue::VNUM;
1128
1.69M
    }
1129
372k
    case Type::BOOL: {
1130
372k
        return UniValue::VBOOL;
1131
1.69M
    }
1132
1.46k
    case Type::ARR_FIXED:
1133
251k
    case Type::ARR: {
1134
251k
        return UniValue::VARR;
1135
1.46k
    }
1136
33.2k
    case Type::OBJ_DYN:
1137
506k
    case Type::OBJ: {
1138
506k
        return UniValue::VOBJ;
1139
33.2k
    }
1140
5.16M
    } // no default case, so the compiler can warn about missing cases
1141
5.16M
    NONFATAL_UNREACHABLE();
1142
5.16M
}
1143
1144
// NOLINTNEXTLINE(misc-no-recursion)
1145
UniValue RPCResult::MatchesType(const UniValue& result) const
1146
5.16M
{
1147
5.16M
    if (m_opts.skip_type_check) {
1148
446
        return true;
1149
446
    }
1150
1151
5.16M
    const auto exp_type = ExpectedType(m_type);
1152
5.16M
    if (!exp_type) return true; // can be any type, so nothing to check
1153
1154
5.16M
    if (*exp_type != result.getType()) {
1155
14.1k
        return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1156
14.1k
    }
1157
1158
5.14M
    if (UniValue::VARR == result.getType()) {
1159
250k
        UniValue errors(UniValue::VOBJ);
1160
1.26M
        for (size_t i{0}; i < result.get_array().size(); ++i) {
1161
            // If there are more results than documented, reuse the last doc_inner.
1162
1.01M
            const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
1163
1.01M
            UniValue match{doc_inner.MatchesType(result.get_array()[i])};
1164
1.01M
            if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
1165
1.01M
        }
1166
250k
        if (errors.empty()) return true; // empty result array is valid
1167
403
        return errors;
1168
250k
    }
1169
1170
4.89M
    if (UniValue::VOBJ == result.getType()) {
1171
505k
        UniValue errors(UniValue::VOBJ);
1172
505k
        if (m_type == Type::OBJ_DYN) {
1173
33.2k
            const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first
1174
318k
            for (size_t i{0}; i < result.get_obj().size(); ++i) {
1175
284k
                UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
1176
284k
                if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match));
1177
284k
            }
1178
33.2k
            if (errors.empty()) return true; // empty result obj is valid
1179
5
            return errors;
1180
33.2k
        }
1181
472k
        std::set<std::string> doc_keys;
1182
3.96M
        for (const auto& doc_entry : m_inner) {
1183
3.96M
            doc_keys.insert(doc_entry.m_key_name);
1184
3.96M
        }
1185
472k
        std::map<std::string, UniValue> result_obj;
1186
472k
        result.getObjMap(result_obj);
1187
3.66M
        for (const auto& result_entry : result_obj) {
1188
3.66M
            if (!doc_keys.contains(result_entry.first)) {
1189
30
                errors.pushKV(result_entry.first, "key returned that was not in doc");
1190
30
            }
1191
3.66M
        }
1192
1193
3.96M
        for (const auto& doc_entry : m_inner) {
1194
3.96M
            const auto result_it{result_obj.find(doc_entry.m_key_name)};
1195
3.96M
            if (result_it == result_obj.end()) {
1196
298k
                if (!doc_entry.m_optional) {
1197
0
                    errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc");
1198
0
                }
1199
298k
                continue;
1200
298k
            }
1201
3.66M
            UniValue match{doc_entry.MatchesType(result_it->second)};
1202
3.66M
            if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match));
1203
3.66M
        }
1204
472k
        if (errors.empty()) return true;
1205
388
        return errors;
1206
472k
    }
1207
1208
4.39M
    return true;
1209
4.89M
}
1210
1211
void RPCResult::CheckInnerDoc() const
1212
6.27M
{
1213
6.27M
    if (m_type == Type::OBJ) {
1214
        // May or may not be empty
1215
762k
        return;
1216
762k
    }
1217
    // Everything else must either be empty or not
1218
5.51M
    const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
1219
5.51M
    CHECK_NONFATAL(inner_needed != m_inner.empty());
1220
5.51M
}
1221
1222
// NOLINTNEXTLINE(misc-no-recursion)
1223
std::string RPCArg::ToStringObj(const bool oneline) const
1224
787
{
1225
787
    std::string res;
1226
787
    res += "\"";
1227
787
    res += GetFirstName();
1228
787
    if (oneline) {
1229
368
        res += "\":";
1230
419
    } else {
1231
419
        res += "\": ";
1232
419
    }
1233
787
    switch (m_type) {
1234
111
    case Type::STR:
1235
111
        return res + "\"str\"";
1236
259
    case Type::STR_HEX:
1237
259
        return res + "\"hex\"";
1238
187
    case Type::NUM:
1239
187
        return res + "n";
1240
69
    case Type::RANGE:
1241
69
        return res + "n or [n,n]";
1242
98
    case Type::AMOUNT:
1243
98
        return res + "amount";
1244
45
    case Type::BOOL:
1245
45
        return res + "bool";
1246
18
    case Type::ARR:
1247
18
        res += "[";
1248
27
        for (const auto& i : m_inner) {
1249
27
            res += i.ToString(oneline) + ",";
1250
27
        }
1251
18
        return res + "...]";
1252
0
    case Type::OBJ:
1253
0
    case Type::OBJ_NAMED_PARAMS:
1254
0
    case Type::OBJ_USER_KEYS:
1255
        // Currently unused, so avoid writing dead code
1256
0
        NONFATAL_UNREACHABLE();
1257
787
    } // no default case, so the compiler can warn about missing cases
1258
787
    NONFATAL_UNREACHABLE();
1259
787
}
1260
1261
// NOLINTNEXTLINE(misc-no-recursion)
1262
std::string RPCArg::ToString(const bool oneline) const
1263
2.47k
{
1264
2.47k
    if (oneline && !m_opts.oneline_description.empty()) {
1265
86
        if (m_opts.oneline_description[0] == '\"' && m_type != Type::STR_HEX && m_type != Type::STR && gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
1266
0
            throw std::runtime_error{
1267
0
                STR_INTERNAL_BUG(strprintf("non-string RPC arg \"%s\" quotes oneline_description:\n%s",
1268
0
                    m_names, m_opts.oneline_description)
1269
0
                )};
1270
0
        }
1271
86
        return m_opts.oneline_description;
1272
86
    }
1273
1274
2.38k
    switch (m_type) {
1275
417
    case Type::STR_HEX:
1276
1.22k
    case Type::STR: {
1277
1.22k
        return "\"" + GetFirstName() + "\"";
1278
417
    }
1279
397
    case Type::NUM:
1280
406
    case Type::RANGE:
1281
468
    case Type::AMOUNT:
1282
787
    case Type::BOOL: {
1283
787
        return GetFirstName();
1284
468
    }
1285
104
    case Type::OBJ:
1286
131
    case Type::OBJ_NAMED_PARAMS:
1287
165
    case Type::OBJ_USER_KEYS: {
1288
        // NOLINTNEXTLINE(misc-no-recursion)
1289
368
        const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
1290
165
        if (m_type == Type::OBJ) {
1291
104
            return "{" + res + "}";
1292
104
        } else {
1293
61
            return "{" + res + ",...}";
1294
61
        }
1295
165
    }
1296
210
    case Type::ARR: {
1297
210
        std::string res;
1298
259
        for (const auto& i : m_inner) {
1299
259
            res += i.ToString(oneline) + ",";
1300
259
        }
1301
210
        return "[" + res + "...]";
1302
165
    }
1303
2.38k
    } // no default case, so the compiler can warn about missing cases
1304
2.38k
    NONFATAL_UNREACHABLE();
1305
2.38k
}
1306
1307
static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
1308
296
{
1309
296
    if (value.isNum()) {
1310
86
        return {0, value.getInt<int64_t>()};
1311
86
    }
1312
210
    if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
1313
210
        int64_t low = value[0].getInt<int64_t>();
1314
210
        int64_t high = value[1].getInt<int64_t>();
1315
210
        if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
1316
206
        return {low, high};
1317
210
    }
1318
0
    throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1319
210
}
1320
1321
std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1322
296
{
1323
296
    int64_t low, high;
1324
296
    std::tie(low, high) = ParseRange(value);
1325
296
    if (low < 0) {
1326
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
1327
4
    }
1328
292
    if ((high >> 31) != 0) {
1329
6
        throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1330
6
    }
1331
286
    if (high >= low + 1000000) {
1332
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1333
4
    }
1334
282
    return {low, high};
1335
286
}
1336
1337
std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1338
1.62k
{
1339
1.62k
    std::string desc_str;
1340
1.62k
    std::pair<int64_t, int64_t> range = {0, 1000};
1341
1.62k
    if (scanobject.isStr()) {
1342
1.51k
        desc_str = scanobject.get_str();
1343
1.51k
    } else if (scanobject.isObject()) {
1344
106
        const UniValue& desc_uni{scanobject.find_value("desc")};
1345
106
        if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1346
106
        desc_str = desc_uni.get_str();
1347
106
        const UniValue& range_uni{scanobject.find_value("range")};
1348
106
        if (!range_uni.isNull()) {
1349
99
            range = ParseDescriptorRange(range_uni);
1350
99
        }
1351
106
    } else {
1352
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1353
0
    }
1354
1355
1.62k
    std::string error;
1356
1.62k
    auto descs = Parse(desc_str, provider, error);
1357
1.62k
    if (descs.empty()) {
1358
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1359
1
    }
1360
1.62k
    if (!descs.at(0)->IsRange()) {
1361
1.52k
        range.first = 0;
1362
1.52k
        range.second = 0;
1363
1.52k
    }
1364
1.62k
    std::vector<CScript> ret;
1365
21.3k
    for (int i = range.first; i <= range.second; ++i) {
1366
19.7k
        for (const auto& desc : descs) {
1367
19.7k
            std::vector<CScript> scripts;
1368
19.7k
            if (!desc->Expand(i, provider, scripts, provider)) {
1369
0
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1370
0
            }
1371
19.7k
            if (expand_priv) {
1372
110
                desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1373
110
            }
1374
19.7k
            std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1375
19.7k
        }
1376
19.7k
    }
1377
1.62k
    return ret;
1378
1.62k
}
1379
1380
/** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */
1381
[[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1382
11
{
1383
11
    CHECK_NONFATAL(!bilingual_strings.empty());
1384
11
    UniValue result{UniValue::VARR};
1385
11
    for (const auto& s : bilingual_strings) {
1386
11
        result.push_back(s.original);
1387
11
    }
1388
11
    return result;
1389
11
}
1390
1391
void PushWarnings(const UniValue& warnings, UniValue& obj)
1392
826
{
1393
826
    if (warnings.empty()) return;
1394
383
    obj.pushKV("warnings", warnings);
1395
383
}
1396
1397
void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1398
1.07k
{
1399
1.07k
    if (warnings.empty()) return;
1400
11
    obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1401
11
}
1402
1403
51.3k
std::vector<RPCResult> ScriptPubKeyDoc() {
1404
51.3k
    return
1405
51.3k
         {
1406
51.3k
             {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1407
51.3k
             {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1408
51.3k
             {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1409
51.3k
             {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1410
51.3k
             {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
1411
51.3k
         };
1412
51.3k
}
1413
1414
uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit)
1415
19.5k
{
1416
19.5k
    arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))};
1417
19.5k
    return ArithToUint256(target);
1418
19.5k
}
1419
1420
std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary)
1421
32.1k
{
1422
32.1k
    if (fields.empty()) return fields;
1423
32.1k
    std::vector<RPCResult> result;
1424
32.1k
    result.reserve(fields.size());
1425
245k
    for (size_t i = 0; i < fields.size(); ++i) {
1426
213k
        RPCResultOptions opts = fields[i].m_opts;
1427
213k
        if (i == 0) {
1428
32.1k
            opts.print_elision = summary;
1429
181k
        } else {
1430
181k
            opts.print_elision = HelpElisionSkip{};
1431
181k
        }
1432
213k
        result.emplace_back(fields[i], std::move(opts));
1433
213k
    }
1434
32.1k
    return result;
1435
32.1k
}