Coverage Report

Created: 2026-08-14 20:23

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
54.4k
{
48
54.4k
    std::vector<std::string> ret;
49
54.4k
    using U = std::underlying_type_t<TxoutType>;
50
652k
    for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
51
598k
        ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
52
598k
    }
53
54.4k
    return Join(ret, ", ");
54
54.4k
}
55
56
void RPCTypeCheckObj(const UniValue& o,
57
    const std::map<std::string, UniValueType>& typesExpected,
58
    bool fAllowNull,
59
    bool fStrict)
60
2.11k
{
61
21.9k
    for (const auto& t : typesExpected) {
62
21.9k
        const UniValue& v = o.find_value(t.first);
63
21.9k
        if (!fAllowNull && v.isNull())
64
11
            throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
65
66
21.9k
        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.9k
    }
69
70
2.07k
    if (fStrict)
71
1.03k
    {
72
1.03k
        for (const std::string& k : o.getKeys())
73
2.22k
        {
74
2.22k
            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.22k
        }
80
1.03k
    }
81
2.07k
}
82
83
int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool)
84
6.73k
{
85
6.73k
    if (!arg.isNull()) {
86
5.27k
        if (arg.isBool()) {
87
3.60k
            if (!allow_bool) {
88
2
                throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed");
89
2
            }
90
3.60k
            return arg.get_bool(); // true = 1
91
3.60k
        } else {
92
1.67k
            return arg.getInt<int>();
93
1.67k
        }
94
5.27k
    }
95
1.46k
    return default_verbosity;
96
6.73k
}
97
98
CAmount AmountFromValue(const UniValue& value, int decimals)
99
52.0k
{
100
52.0k
    if (!value.isNum() && !value.isStr())
101
12
        throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
102
52.0k
    int64_t amount;
103
52.0k
    if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
104
83
        throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
105
51.9k
    if (!MoneyRange(amount))
106
12
        throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
107
51.9k
    return amount;
108
51.9k
}
109
110
CFeeRate ParseFeeRate(const UniValue& json)
111
35.5k
{
112
35.5k
    CAmount val{AmountFromValue(json)};
113
35.5k
    if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted");
114
35.5k
    return CFeeRate{val};
115
35.5k
}
116
117
uint256 ParseHashV(const UniValue& v, std::string_view name)
118
30.2k
{
119
30.2k
    const std::string& strHex(v.get_str());
120
30.2k
    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.56k
{
128
6.56k
    return ParseHashV(o.find_value(strKey), strKey);
129
6.56k
}
130
std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name)
131
1.03k
{
132
1.03k
    std::string strHex;
133
1.03k
    if (v.isStr())
134
1.03k
        strHex = v.get_str();
135
1.03k
    if (!IsHex(strHex))
136
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex));
137
1.03k
    return ParseHex(strHex);
138
1.03k
}
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.37k
{
153
3.37k
    std::string result;
154
3.37k
    result.reserve(s.size() * 2);
155
239k
    for (const char ch: s) {
156
239k
        if (ch == '\'') {
157
1
            result += "'\''";
158
239k
        } else {
159
239k
            result += ch;
160
239k
        }
161
239k
    }
162
3.37k
    return "'" + result + "'";
163
3.37k
}
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.7k
{
172
90.1k
    for (const char ch: s) {
173
90.1k
        if (ch == ' ' || ch == '\'' || ch == '"') {
174
3.37k
            return ShellQuote(s);
175
3.37k
        }
176
90.1k
    }
177
178
10.4k
    return s;
179
13.7k
}
180
181
}
182
183
std::string HelpExampleCli(const std::string& methodname, const std::string& args)
184
729k
{
185
729k
    return "> bitcoin-cli " + methodname + " " + args + "\n";
186
729k
}
187
188
std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
189
5.72k
{
190
5.72k
    std::string result = "> bitcoin-cli -named " + methodname;
191
13.7k
    for (const auto& argpair: args) {
192
13.7k
        const auto& value = argpair.second.isStr()
193
13.7k
                ? argpair.second.get_str()
194
13.7k
                : argpair.second.write();
195
13.7k
        result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
196
13.7k
    }
197
5.72k
    result += "\n";
198
5.72k
    return result;
199
5.72k
}
200
201
std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
202
479k
{
203
479k
    return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
204
479k
        "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
205
479k
}
206
207
std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
208
3.22k
{
209
3.22k
    UniValue params(UniValue::VOBJ);
210
8.80k
    for (const auto& param: args) {
211
8.80k
        params.pushKV(param.first, param.second);
212
8.80k
    }
213
214
3.22k
    return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
215
3.22k
           "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
216
3.22k
}
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
129
    {
285
129
        UniValue obj(UniValue::VOBJ);
286
129
        obj.pushKV("isscript", false);
287
129
        obj.pushKV("iswitness", false);
288
129
        return obj;
289
129
    }
290
291
    UniValue operator()(const ScriptHash& scriptID) const
292
134
    {
293
134
        UniValue obj(UniValue::VOBJ);
294
134
        obj.pushKV("isscript", true);
295
134
        obj.pushKV("iswitness", false);
296
134
        return obj;
297
134
    }
298
299
    UniValue operator()(const WitnessV0KeyHash& id) const
300
511
    {
301
511
        UniValue obj(UniValue::VOBJ);
302
511
        obj.pushKV("isscript", false);
303
511
        obj.pushKV("iswitness", true);
304
511
        obj.pushKV("witness_version", 0);
305
511
        obj.pushKV("witness_program", HexStr(id));
306
511
        return obj;
307
511
    }
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
119
    {
321
119
        UniValue obj(UniValue::VOBJ);
322
119
        obj.pushKV("isscript", true);
323
119
        obj.pushKV("iswitness", true);
324
119
        obj.pushKV("witness_version", 1);
325
119
        obj.pushKV("witness_program", HexStr(tap));
326
119
        return obj;
327
119
    }
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
942
{
349
942
    return std::visit(DescribeAddressVisitor(), dest);
350
942
}
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.06k
{
359
1.06k
    if (sighash.isNull()) {
360
975
        return std::nullopt;
361
975
    }
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.32k
{
393
4.32k
    switch (terr) {
394
4.30k
        case TransactionError::MEMPOOL_REJECTED:
395
4.30k
            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.32k
    }
402
12
    return RPC_TRANSACTION_ERROR;
403
4.32k
}
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.32k
{
412
4.32k
    if (err_string.length() > 0) {
413
4.31k
        return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
414
4.31k
    } else {
415
15
        return JSONRPCError(RPCErrorFromTransactionError(terr), TransactionErrorString(terr).original);
416
15
    }
417
4.32k
}
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.6k
        : 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.7k
    {
440
18.7k
        m_max_pad = std::max(m_max_pad, s.m_left.size());
441
18.7k
        m_sections.push_back(s);
442
18.7k
    }
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.6k
        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.6k
            CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
514
20.6k
            if (s.m_right.empty()) {
515
5.51k
                ret += s.m_left;
516
5.51k
                ret += "\n";
517
5.51k
                continue;
518
5.51k
            }
519
520
15.1k
            std::string left = s.m_left;
521
15.1k
            left.resize(pad, ' ');
522
15.1k
            ret += left;
523
524
            // Properly pad after newlines
525
15.1k
            std::string right;
526
15.1k
            size_t begin = 0;
527
15.1k
            size_t new_line_pos = s.m_right.find_first_of('\n');
528
17.1k
            while (true) {
529
17.1k
                right += s.m_right.substr(begin, new_line_pos - begin);
530
17.1k
                if (new_line_pos == std::string::npos) {
531
15.0k
                    break; //No new line
532
15.0k
                }
533
2.15k
                right += "\n" + std::string(pad, ' ');
534
2.15k
                begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
535
2.15k
                if (begin == std::string::npos) {
536
158
                    break; // Empty line
537
158
                }
538
1.99k
                new_line_pos = s.m_right.find_first_of('\n', begin + 1);
539
1.99k
            }
540
15.1k
            ret += right;
541
15.1k
            ret += "\n";
542
15.1k
        }
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
527k
    : m_name{std::move(name)},
552
527k
      m_fun{std::move(fun)},
553
527k
      m_description{std::move(description)},
554
527k
      m_args{std::move(args)},
555
527k
      m_results{std::move(results)},
556
527k
      m_examples{std::move(examples)}
557
527k
{
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
527k
    enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
562
527k
    std::map<std::string, int> param_names;
563
564
985k
    for (const auto& arg : m_args) {
565
985k
        std::vector<std::string> names = SplitString(arg.m_names, '|');
566
        // Should have unique named arguments
567
996k
        for (const std::string& name : names) {
568
996k
            auto& param_type = param_names[name];
569
996k
            CHECK_NONFATAL(!(param_type & POSITIONAL));
570
996k
            CHECK_NONFATAL(!(param_type & NAMED_ONLY));
571
996k
            param_type |= POSITIONAL;
572
996k
        }
573
985k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
574
115k
            for (const auto& inner : arg.m_inner) {
575
115k
                std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
576
115k
                for (const std::string& inner_name : inner_names) {
577
115k
                    auto& param_type = param_names[inner_name];
578
115k
                    CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
579
115k
                    CHECK_NONFATAL(!(param_type & NAMED));
580
115k
                    CHECK_NONFATAL(!(param_type & NAMED_ONLY));
581
115k
                    param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
582
115k
                }
583
115k
            }
584
19.6k
        }
585
        // Default value type should match argument type only when defined
586
985k
        if (arg.m_fallback.index() == 2) {
587
351k
            const RPCArg::Type type = arg.m_type;
588
351k
            [&]() {
589
351k
                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.14k
                case UniValue::VARR:
594
2.14k
                    CHECK_NONFATAL(type == RPCArg::Type::ARR);
595
2.14k
                    return;
596
127k
                case UniValue::VSTR:
597
127k
                    CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
598
127k
                    return;
599
74.3k
                case UniValue::VNUM:
600
74.3k
                    CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
601
74.3k
                    return;
602
147k
                case UniValue::VBOOL:
603
147k
                    CHECK_NONFATAL(type == RPCArg::Type::BOOL);
604
147k
                    return;
605
0
                case UniValue::VNULL:
606
                    // Null values are accepted in all arguments
607
0
                    return;
608
351k
                } // no default case, so the compiler can warn about missing cases
609
351k
                NONFATAL_UNREACHABLE();
610
351k
            }();
611
351k
        }
612
985k
    }
613
527k
}
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
        Sections sections;
620
1.32k
        r.ToSections(sections);
621
        // A result can be empty via HelpElisionSkip
622
1.32k
        if (sections.m_sections.empty()) continue;
623
624
1.31k
        if (r.m_cond.empty()) {
625
979
            result += "\nResult:\n";
626
979
        } else {
627
337
            result += "\nResult (" + r.m_cond + "):\n";
628
337
        }
629
1.31k
        result += sections.ToString();
630
1.31k
    }
631
1.10k
    return result;
632
1.10k
}
633
634
std::string RPCExamples::ToDescriptionString() const
635
1.10k
{
636
1.10k
    return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
637
1.10k
}
638
639
UniValue RPCMethod::HandleRequest(const JSONRPCRequest& request) const
640
200k
{
641
200k
    if (request.mode == JSONRPCRequest::GET_ARGS) {
642
348
        return GetArgMap();
643
348
    }
644
    /*
645
     * Check if the given request is valid according to this command or if
646
     * the user is asking for help information, and throw help when appropriate.
647
     */
648
200k
    if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
649
1.10k
        throw HelpResult{ToString()};
650
1.10k
    }
651
199k
    UniValue arg_mismatch{UniValue::VOBJ};
652
586k
    for (size_t i{0}; i < m_args.size(); ++i) {
653
387k
        const auto& arg{m_args.at(i)};
654
387k
        UniValue match{arg.MatchesType(request.params[i])};
655
387k
        if (!match.isTrue()) {
656
31
            arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match));
657
31
        }
658
387k
    }
659
199k
    if (!arg_mismatch.empty()) {
660
29
        throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
661
29
    }
662
199k
    CHECK_NONFATAL(m_req == nullptr);
663
199k
    m_req = &request;
664
199k
    UniValue ret = m_fun(*this, request);
665
199k
    m_req = nullptr;
666
199k
    if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
667
193k
        UniValue mismatch{UniValue::VARR};
668
207k
        for (const auto& res : m_results.m_results) {
669
207k
            UniValue match{res.MatchesType(ret)};
670
207k
            if (match.isTrue()) {
671
193k
                mismatch.setNull();
672
193k
                break;
673
193k
            }
674
14.2k
            mismatch.push_back(std::move(match));
675
14.2k
        }
676
193k
        if (!mismatch.isNull()) {
677
0
            std::string explain{
678
0
                mismatch.empty() ? "no possible results defined" :
679
0
                mismatch.size() == 1 ? mismatch[0].write(4) :
680
0
                mismatch.write(4)};
681
0
            throw std::runtime_error{
682
0
                STR_INTERNAL_BUG(strprintf("RPC call \"%s\" returned incorrect type:\n%s", m_name, explain)),
683
0
            };
684
0
        }
685
193k
    }
686
199k
    return ret;
687
199k
}
688
689
using CheckFn = void(const RPCArg&);
690
static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
691
47.9k
{
692
47.9k
    CHECK_NONFATAL(i < params.size());
693
47.9k
    const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
694
47.9k
    const RPCArg& param{params.at(i)};
695
47.9k
    if (check) check(param);
696
697
47.9k
    if (!arg.isNull()) return &arg;
698
20.4k
    if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
699
18.0k
    return &std::get<RPCArg::Default>(param.m_fallback);
700
20.4k
}
701
702
static void CheckRequiredOrDefault(const RPCArg& param)
703
43.7k
{
704
    // Must use `Arg<Type>(key)` to get the argument or its default value.
705
43.7k
    const bool required{
706
43.7k
        std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
707
43.7k
    };
708
43.7k
    CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
709
43.7k
}
710
711
#define TMPL_INST(check_param, ret_type, return_code)       \
712
    template <>                                             \
713
    ret_type RPCMethod::ArgValue<ret_type>(size_t i) const \
714
47.9k
    {                                                       \
715
47.9k
        const UniValue* maybe_arg{                          \
716
47.9k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
47.9k
        };                                                  \
718
47.9k
        return return_code                                  \
719
47.9k
    }                                                       \
UniValue const* RPCMethod::ArgValue<UniValue const*>(unsigned long) const
Line
Count
Source
714
1.32k
    {                                                       \
715
1.32k
        const UniValue* maybe_arg{                          \
716
1.32k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
1.32k
        };                                                  \
718
1.32k
        return return_code                                  \
719
1.32k
    }                                                       \
std::optional<double> RPCMethod::ArgValue<std::optional<double>>(unsigned long) const
Line
Count
Source
714
723
    {                                                       \
715
723
        const UniValue* maybe_arg{                          \
716
723
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
723
        };                                                  \
718
1.44k
        return return_code                                  \
719
723
    }                                                       \
std::optional<bool> RPCMethod::ArgValue<std::optional<bool>>(unsigned long) const
Line
Count
Source
714
771
    {                                                       \
715
771
        const UniValue* maybe_arg{                          \
716
771
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
771
        };                                                  \
718
1.54k
        return return_code                                  \
719
771
    }                                                       \
std::optional<long> RPCMethod::ArgValue<std::optional<long>>(unsigned long) const
Line
Count
Source
714
110
    {                                                       \
715
110
        const UniValue* maybe_arg{                          \
716
110
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
110
        };                                                  \
718
220
        return return_code                                  \
719
110
    }                                                       \
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
714
1.24k
    {                                                       \
715
1.24k
        const UniValue* maybe_arg{                          \
716
1.24k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
1.24k
        };                                                  \
718
2.49k
        return return_code                                  \
719
1.24k
    }                                                       \
UniValue const& RPCMethod::ArgValue<UniValue const&>(unsigned long) const
Line
Count
Source
714
35.5k
    {                                                       \
715
35.5k
        const UniValue* maybe_arg{                          \
716
35.5k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
35.5k
        };                                                  \
718
35.5k
        return return_code                                  \
719
35.5k
    }                                                       \
bool RPCMethod::ArgValue<bool>(unsigned long) const
Line
Count
Source
714
858
    {                                                       \
715
858
        const UniValue* maybe_arg{                          \
716
858
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
858
        };                                                  \
718
858
        return return_code                                  \
719
858
    }                                                       \
int RPCMethod::ArgValue<int>(unsigned long) const
Line
Count
Source
714
1.42k
    {                                                       \
715
1.42k
        const UniValue* maybe_arg{                          \
716
1.42k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
1.42k
        };                                                  \
718
1.42k
        return return_code                                  \
719
1.42k
    }                                                       \
unsigned long RPCMethod::ArgValue<unsigned long>(unsigned long) const
Line
Count
Source
714
830
    {                                                       \
715
830
        const UniValue* maybe_arg{                          \
716
830
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
830
        };                                                  \
718
830
        return return_code                                  \
719
830
    }                                                       \
unsigned int RPCMethod::ArgValue<unsigned int>(unsigned long) const
Line
Count
Source
714
991
    {                                                       \
715
991
        const UniValue* maybe_arg{                          \
716
991
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
991
        };                                                  \
718
991
        return return_code                                  \
719
991
    }                                                       \
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
714
4.11k
    {                                                       \
715
4.11k
        const UniValue* maybe_arg{                          \
716
4.11k
            DetailMaybeArg(check_param, m_args, m_req, i),  \
717
4.11k
        };                                                  \
718
4.11k
        return return_code                                  \
719
4.11k
    }                                                       \
720
    void force_semicolon(ret_type)
721
722
// Optional arg (without default). Can also be called on required args, if needed.
723
TMPL_INST(nullptr, const UniValue*, maybe_arg;);
724
TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
725
TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
726
TMPL_INST(nullptr, std::optional<int64_t>, maybe_arg ? std::optional{maybe_arg->getInt<int64_t>()} : std::nullopt;);
727
TMPL_INST(nullptr, std::optional<std::string_view>, maybe_arg ? std::optional<std::string_view>{maybe_arg->get_str()} : std::nullopt;);
728
729
// Required arg or optional arg with default value.
730
TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg););
731
TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
732
TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
733
TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
734
TMPL_INST(CheckRequiredOrDefault, uint32_t, CHECK_NONFATAL(maybe_arg)->getInt<uint32_t>(););
735
TMPL_INST(CheckRequiredOrDefault, std::string_view, CHECK_NONFATAL(maybe_arg)->get_str(););
736
737
bool RPCMethod::IsValidNumArgs(size_t num_args) const
738
199k
{
739
199k
    size_t num_required_args = 0;
740
418k
    for (size_t n = m_args.size(); n > 0; --n) {
741
347k
        if (!m_args.at(n - 1).IsOptional()) {
742
127k
            num_required_args = n;
743
127k
            break;
744
127k
        }
745
347k
    }
746
199k
    return num_required_args <= num_args && num_args <= m_args.size();
747
199k
}
748
749
std::vector<std::pair<std::string, bool>> RPCMethod::GetArgNames() const
750
163k
{
751
163k
    std::vector<std::pair<std::string, bool>> ret;
752
163k
    ret.reserve(m_args.size());
753
297k
    for (const auto& arg : m_args) {
754
297k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
755
47.9k
            for (const auto& inner : arg.m_inner) {
756
47.9k
                ret.emplace_back(inner.m_names, /*named_only=*/true);
757
47.9k
            }
758
8.90k
        }
759
297k
        ret.emplace_back(arg.m_names, /*named_only=*/false);
760
297k
    }
761
163k
    return ret;
762
163k
}
763
764
size_t RPCMethod::GetParamIndex(std::string_view key) const
765
47.9k
{
766
47.9k
    auto it{std::find_if(
767
99.2k
        m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;}
768
47.9k
    )};
769
770
47.9k
    CHECK_NONFATAL(it != m_args.end());  // TODO: ideally this is checked at compile time
771
47.9k
    return std::distance(m_args.begin(), it);
772
47.9k
}
773
774
std::string RPCMethod::ToString() const
775
1.10k
{
776
1.10k
    std::string ret;
777
778
    // Oneline summary
779
1.10k
    ret += m_name;
780
1.10k
    bool was_optional{false};
781
1.93k
    for (const auto& arg : m_args) {
782
1.93k
        if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
783
1.92k
        const bool optional = arg.IsOptional();
784
1.92k
        ret += " ";
785
1.92k
        if (optional) {
786
1.08k
            if (!was_optional) ret += "( ";
787
1.08k
            was_optional = true;
788
1.08k
        } else {
789
846
            if (was_optional) ret += ") ";
790
846
            was_optional = false;
791
846
        }
792
1.92k
        ret += arg.ToString(/*oneline=*/true);
793
1.92k
    }
794
1.10k
    if (was_optional) ret += " )";
795
796
    // Description
797
1.10k
    CHECK_NONFATAL(!m_description.starts_with('\n'));  // Historically \n was required, but reject it for new code.
798
1.10k
    ret += "\n\n" + TrimString(m_description) + "\n";
799
800
    // Arguments
801
1.10k
    Sections sections;
802
1.10k
    Sections named_only_sections;
803
3.03k
    for (size_t i{0}; i < m_args.size(); ++i) {
804
1.93k
        const auto& arg = m_args.at(i);
805
1.93k
        if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
806
807
        // Push named argument name and description
808
1.92k
        sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
809
1.92k
        sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
810
811
        // Recursively push nested args
812
1.92k
        sections.Push(arg);
813
814
        // Push named-only argument sections
815
1.92k
        if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
816
351
            for (const auto& arg_inner : arg.m_inner) {
817
351
                named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
818
351
                named_only_sections.Push(arg_inner);
819
351
            }
820
66
        }
821
1.92k
    }
822
823
1.10k
    if (!sections.m_sections.empty()) ret += "\nArguments:\n";
824
1.10k
    ret += sections.ToString();
825
1.10k
    if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
826
1.10k
    ret += named_only_sections.ToString();
827
828
    // Result
829
1.10k
    ret += m_results.ToDescriptionString();
830
831
    // Examples
832
1.10k
    ret += m_examples.ToDescriptionString();
833
834
1.10k
    return ret;
835
1.10k
}
836
837
UniValue RPCMethod::GetArgMap() const
838
348
{
839
348
    UniValue arr{UniValue::VARR};
840
841
896
    auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
842
896
        UniValue map{UniValue::VARR};
843
896
        map.push_back(rpc_name);
844
896
        map.push_back(pos);
845
896
        map.push_back(arg_name);
846
896
        map.push_back(type == RPCArg::Type::STR ||
847
896
                      type == RPCArg::Type::STR_HEX);
848
896
        arr.push_back(std::move(map));
849
896
    };
850
851
1.03k
    for (int i{0}; i < int(m_args.size()); ++i) {
852
690
        const auto& arg = m_args.at(i);
853
690
        std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
854
694
        for (const auto& arg_name : arg_names) {
855
694
            push_back_arg_info(m_name, i, arg_name, arg.m_type);
856
694
            if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
857
202
                for (const auto& inner : arg.m_inner) {
858
202
                    std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
859
202
                    for (const std::string& inner_name : inner_names) {
860
202
                        push_back_arg_info(m_name, i, inner_name, inner.m_type);
861
202
                    }
862
202
                }
863
28
            }
864
694
        }
865
690
    }
866
348
    return arr;
867
348
}
868
869
static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
870
203k
{
871
203k
    using Type = RPCArg::Type;
872
203k
    switch (type) {
873
70.6k
    case Type::STR_HEX:
874
121k
    case Type::STR: {
875
121k
        return UniValue::VSTR;
876
70.6k
    }
877
46.7k
    case Type::NUM: {
878
46.7k
        return UniValue::VNUM;
879
70.6k
    }
880
22.3k
    case Type::AMOUNT: {
881
        // VNUM or VSTR, checked inside AmountFromValue()
882
22.3k
        return std::nullopt;
883
70.6k
    }
884
80
    case Type::RANGE: {
885
        // VNUM or VARR, checked inside ParseRange()
886
80
        return std::nullopt;
887
70.6k
    }
888
3.56k
    case Type::BOOL: {
889
3.56k
        return UniValue::VBOOL;
890
70.6k
    }
891
2.41k
    case Type::OBJ:
892
3.29k
    case Type::OBJ_NAMED_PARAMS:
893
3.38k
    case Type::OBJ_USER_KEYS: {
894
3.38k
        return UniValue::VOBJ;
895
3.29k
    }
896
5.65k
    case Type::ARR: {
897
5.65k
        return UniValue::VARR;
898
3.29k
    }
899
203k
    } // no default case, so the compiler can warn about missing cases
900
203k
    NONFATAL_UNREACHABLE();
901
203k
}
902
903
UniValue RPCArg::MatchesType(const UniValue& request) const
904
387k
{
905
387k
    if (m_opts.skip_type_check) return true;
906
378k
    if (IsOptional() && request.isNull()) return true;
907
203k
    const auto exp_type{ExpectedType(m_type)};
908
203k
    if (!exp_type) return true; // nothing to check
909
910
180k
    if (*exp_type != request.getType()) {
911
31
        return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type));
912
31
    }
913
180k
    return true;
914
180k
}
915
916
std::string RPCArg::GetFirstName() const
917
5.73k
{
918
5.73k
    return m_names.substr(0, m_names.find('|'));
919
5.73k
}
920
921
std::string RPCArg::GetName() const
922
99.3k
{
923
99.3k
    CHECK_NONFATAL(std::string::npos == m_names.find('|'));
924
99.3k
    return m_names;
925
99.3k
}
926
927
bool RPCArg::IsOptional() const
928
727k
{
929
727k
    if (m_fallback.index() != 0) {
930
403k
        return true;
931
403k
    } else {
932
324k
        return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
933
324k
    }
934
727k
}
935
936
std::string RPCArg::ToDescriptionString(bool is_named_arg) const
937
3.19k
{
938
3.19k
    std::string ret;
939
3.19k
    ret += "(";
940
3.19k
    if (m_opts.type_str.size() != 0) {
941
32
        ret += m_opts.type_str.at(1);
942
3.15k
    } else {
943
3.15k
        switch (m_type) {
944
486
        case Type::STR_HEX:
945
1.31k
        case Type::STR: {
946
1.31k
            ret += "string";
947
1.31k
            break;
948
486
        }
949
559
        case Type::NUM: {
950
559
            ret += "numeric";
951
559
            break;
952
486
        }
953
147
        case Type::AMOUNT: {
954
147
            ret += "numeric or string";
955
147
            break;
956
486
        }
957
60
        case Type::RANGE: {
958
60
            ret += "numeric or array";
959
60
            break;
960
486
        }
961
478
        case Type::BOOL: {
962
478
            ret += "boolean";
963
478
            break;
964
486
        }
965
164
        case Type::OBJ:
966
230
        case Type::OBJ_NAMED_PARAMS:
967
270
        case Type::OBJ_USER_KEYS: {
968
270
            ret += "json object";
969
270
            break;
970
230
        }
971
332
        case Type::ARR: {
972
332
            ret += "json array";
973
332
            break;
974
230
        }
975
3.15k
        } // no default case, so the compiler can warn about missing cases
976
3.15k
    }
977
3.19k
    if (m_fallback.index() == 1) {
978
383
        ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
979
2.80k
    } else if (m_fallback.index() == 2) {
980
898
        ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
981
1.91k
    } else {
982
1.91k
        switch (std::get<RPCArg::Optional>(m_fallback)) {
983
775
        case RPCArg::Optional::OMITTED: {
984
775
            if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
985
            // nothing to do. Element is treated as if not present and has no default value
986
775
            break;
987
0
        }
988
1.13k
        case RPCArg::Optional::NO: {
989
1.13k
            ret += ", required";
990
1.13k
            break;
991
0
        }
992
1.91k
        } // no default case, so the compiler can warn about missing cases
993
1.91k
    }
994
3.19k
    ret += ")";
995
3.19k
    if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
996
3.19k
    ret += m_description.empty() ? "" : " " + m_description;
997
3.19k
    return ret;
998
3.19k
}
999
1000
// NOLINTNEXTLINE(misc-no-recursion)
1001
void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1002
13.0k
{
1003
    // Indentation
1004
13.0k
    const std::string indent(current_indent, ' ');
1005
13.0k
    const std::string indent_next(current_indent + 2, ' ');
1006
1007
    // Elements in a JSON structure (dictionary or array) are separated by a comma
1008
13.0k
    const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1009
1010
    // The key name if recursed into a dictionary
1011
13.0k
    const std::string maybe_key{
1012
13.0k
        outer_type == OuterType::OBJ ?
1013
10.4k
            "\"" + this->m_key_name + "\" : " :
1014
13.0k
            ""};
1015
1016
    // Format description with type
1017
13.0k
    const auto Description = [&](const std::string& type) {
1018
11.9k
        return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
1019
11.9k
               (this->m_description.empty() ? "" : " " + this->m_description);
1020
11.9k
    };
1021
1022
    // Ensure at least one visible field exists when elision is used
1023
13.0k
    const auto elision_has_description{[](const std::vector<RPCResult>& inner) {
1024
3.03k
        return std::ranges::any_of(inner, [](const auto& res) {
1025
3.03k
            return !std::holds_alternative<HelpElisionSkip>(res.m_opts.print_elision);
1026
3.03k
        });
1027
2.97k
    }};
1028
1029
13.0k
    if (const auto* text = std::get_if<std::string>(&m_opts.print_elision)) {
1030
95
        sections.PushSection({indent + "..." + maybe_separator, *text});
1031
95
        return;
1032
95
    }
1033
12.9k
    if (std::holds_alternative<HelpElisionSkip>(m_opts.print_elision)) {
1034
1.00k
        return;
1035
1.00k
    }
1036
1037
11.9k
    switch (m_type) {
1038
36
    case Type::ANY: {
1039
36
        sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("any")});
1040
36
        return;
1041
0
    }
1042
139
    case Type::NONE: {
1043
139
        sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
1044
139
        return;
1045
0
    }
1046
2.07k
    case Type::STR: {
1047
2.07k
        sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
1048
2.07k
        return;
1049
0
    }
1050
547
    case Type::STR_AMOUNT: {
1051
547
        sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1052
547
        return;
1053
0
    }
1054
1.92k
    case Type::STR_HEX: {
1055
1.92k
        sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
1056
1.92k
        return;
1057
0
    }
1058
3.10k
    case Type::NUM: {
1059
3.10k
        sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
1060
3.10k
        return;
1061
0
    }
1062
357
    case Type::NUM_TIME: {
1063
357
        sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
1064
357
        return;
1065
0
    }
1066
728
    case Type::BOOL: {
1067
728
        sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
1068
728
        return;
1069
0
    }
1070
17
    case Type::ARR_FIXED:
1071
1.12k
    case Type::ARR: {
1072
1.12k
        sections.PushSection({indent + maybe_key + "[", Description("json array")});
1073
1.18k
        for (const auto& i : m_inner) {
1074
1.18k
            i.ToSections(sections, OuterType::ARR, current_indent + 2);
1075
1.18k
        }
1076
1.12k
        CHECK_NONFATAL(!m_inner.empty());
1077
1.12k
        CHECK_NONFATAL(elision_has_description(m_inner));
1078
1.12k
        if (m_type == Type::ARR && !std::holds_alternative<std::string>(m_inner.back().m_opts.print_elision)) {
1079
1.10k
            sections.PushSection({indent_next + "...", ""});
1080
1.10k
        } else {
1081
            // Remove final comma, which would be invalid JSON
1082
20
            sections.m_sections.back().m_left.pop_back();
1083
20
        }
1084
1.12k
        sections.PushSection({indent + "]" + maybe_separator, ""});
1085
1.12k
        return;
1086
17
    }
1087
213
    case Type::OBJ_DYN:
1088
1.87k
    case Type::OBJ: {
1089
1.87k
        if (m_inner.empty()) {
1090
18
            sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
1091
18
            return;
1092
18
        }
1093
1.85k
        CHECK_NONFATAL(elision_has_description(m_inner));
1094
1.85k
        sections.PushSection({indent + maybe_key + "{", Description("json object")});
1095
10.4k
        for (const auto& i : m_inner) {
1096
10.4k
            i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1097
10.4k
        }
1098
1.85k
        if (m_type == Type::OBJ_DYN) {
1099
            // If the dictionary keys are dynamic, use three dots for continuation
1100
213
            sections.PushSection({indent_next + "...", ""});
1101
1.64k
        } else {
1102
            // Remove final comma, which would be invalid JSON
1103
1.64k
            sections.m_sections.back().m_left.pop_back();
1104
1.64k
        }
1105
1.85k
        sections.PushSection({indent + "}" + maybe_separator, ""});
1106
1.85k
        return;
1107
1.87k
    }
1108
11.9k
    } // no default case, so the compiler can warn about missing cases
1109
11.9k
    NONFATAL_UNREACHABLE();
1110
11.9k
}
1111
1112
static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1113
5.41M
{
1114
5.41M
    using Type = RPCResult::Type;
1115
5.41M
    switch (type) {
1116
126
    case Type::ANY: {
1117
126
        return std::nullopt;
1118
0
    }
1119
17.8k
    case Type::NONE: {
1120
17.8k
        return UniValue::VNULL;
1121
0
    }
1122
646k
    case Type::STR:
1123
2.21M
    case Type::STR_HEX: {
1124
2.21M
        return UniValue::VSTR;
1125
646k
    }
1126
1.54M
    case Type::NUM:
1127
1.79M
    case Type::STR_AMOUNT:
1128
2.02M
    case Type::NUM_TIME: {
1129
2.02M
        return UniValue::VNUM;
1130
1.79M
    }
1131
382k
    case Type::BOOL: {
1132
382k
        return UniValue::VBOOL;
1133
1.79M
    }
1134
1.50k
    case Type::ARR_FIXED:
1135
264k
    case Type::ARR: {
1136
264k
        return UniValue::VARR;
1137
1.50k
    }
1138
37.0k
    case Type::OBJ_DYN:
1139
516k
    case Type::OBJ: {
1140
516k
        return UniValue::VOBJ;
1141
37.0k
    }
1142
5.41M
    } // no default case, so the compiler can warn about missing cases
1143
5.41M
    NONFATAL_UNREACHABLE();
1144
5.41M
}
1145
1146
// NOLINTNEXTLINE(misc-no-recursion)
1147
UniValue RPCResult::MatchesType(const UniValue& result) const
1148
5.41M
{
1149
5.41M
    if (m_opts.skip_type_check) {
1150
451
        return true;
1151
451
    }
1152
1153
5.41M
    const auto exp_type = ExpectedType(m_type);
1154
5.41M
    if (!exp_type) return true; // can be any type, so nothing to check
1155
1156
5.41M
    if (*exp_type != result.getType()) {
1157
14.2k
        return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1158
14.2k
    }
1159
1160
5.39M
    if (UniValue::VARR == result.getType()) {
1161
263k
        UniValue errors(UniValue::VOBJ);
1162
1.36M
        for (size_t i{0}; i < result.get_array().size(); ++i) {
1163
            // If there are more results than documented, reuse the last doc_inner.
1164
1.10M
            const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
1165
1.10M
            UniValue match{doc_inner.MatchesType(result.get_array()[i])};
1166
1.10M
            if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
1167
1.10M
        }
1168
263k
        if (errors.empty()) return true; // empty result array is valid
1169
403
        return errors;
1170
263k
    }
1171
1172
5.13M
    if (UniValue::VOBJ == result.getType()) {
1173
515k
        UniValue errors(UniValue::VOBJ);
1174
515k
        if (m_type == Type::OBJ_DYN) {
1175
37.0k
            const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first
1176
360k
            for (size_t i{0}; i < result.get_obj().size(); ++i) {
1177
323k
                UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
1178
323k
                if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match));
1179
323k
            }
1180
37.0k
            if (errors.empty()) return true; // empty result obj is valid
1181
5
            return errors;
1182
37.0k
        }
1183
478k
        std::set<std::string> doc_keys;
1184
4.09M
        for (const auto& doc_entry : m_inner) {
1185
4.09M
            doc_keys.insert(doc_entry.m_key_name);
1186
4.09M
        }
1187
478k
        std::map<std::string, UniValue> result_obj;
1188
478k
        result.getObjMap(result_obj);
1189
3.78M
        for (const auto& result_entry : result_obj) {
1190
3.78M
            if (!doc_keys.contains(result_entry.first)) {
1191
30
                errors.pushKV(result_entry.first, "key returned that was not in doc");
1192
30
            }
1193
3.78M
        }
1194
1195
4.09M
        for (const auto& doc_entry : m_inner) {
1196
4.09M
            const auto result_it{result_obj.find(doc_entry.m_key_name)};
1197
4.09M
            if (result_it == result_obj.end()) {
1198
312k
                if (!doc_entry.m_optional) {
1199
0
                    errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc");
1200
0
                }
1201
312k
                continue;
1202
312k
            }
1203
3.78M
            UniValue match{doc_entry.MatchesType(result_it->second)};
1204
3.78M
            if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match));
1205
3.78M
        }
1206
478k
        if (errors.empty()) return true;
1207
388
        return errors;
1208
478k
    }
1209
1210
4.61M
    return true;
1211
5.13M
}
1212
1213
void RPCResult::CheckInnerDoc() const
1214
6.48M
{
1215
6.48M
    if (m_type == Type::OBJ) {
1216
        // May or may not be empty
1217
765k
        return;
1218
765k
    }
1219
    // Everything else must either be empty or not
1220
5.72M
    const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
1221
5.72M
    CHECK_NONFATAL(inner_needed != m_inner.empty());
1222
5.72M
}
1223
1224
// NOLINTNEXTLINE(misc-no-recursion)
1225
std::string RPCArg::ToStringObj(const bool oneline) const
1226
787
{
1227
787
    std::string res;
1228
787
    res += "\"";
1229
787
    res += GetFirstName();
1230
787
    if (oneline) {
1231
368
        res += "\":";
1232
419
    } else {
1233
419
        res += "\": ";
1234
419
    }
1235
787
    switch (m_type) {
1236
111
    case Type::STR:
1237
111
        return res + "\"str\"";
1238
259
    case Type::STR_HEX:
1239
259
        return res + "\"hex\"";
1240
187
    case Type::NUM:
1241
187
        return res + "n";
1242
69
    case Type::RANGE:
1243
69
        return res + "n or [n,n]";
1244
98
    case Type::AMOUNT:
1245
98
        return res + "amount";
1246
45
    case Type::BOOL:
1247
45
        return res + "bool";
1248
18
    case Type::ARR:
1249
18
        res += "[";
1250
27
        for (const auto& i : m_inner) {
1251
27
            res += i.ToString(oneline) + ",";
1252
27
        }
1253
18
        return res + "...]";
1254
0
    case Type::OBJ:
1255
0
    case Type::OBJ_NAMED_PARAMS:
1256
0
    case Type::OBJ_USER_KEYS:
1257
        // Currently unused, so avoid writing dead code
1258
0
        NONFATAL_UNREACHABLE();
1259
787
    } // no default case, so the compiler can warn about missing cases
1260
787
    NONFATAL_UNREACHABLE();
1261
787
}
1262
1263
// NOLINTNEXTLINE(misc-no-recursion)
1264
std::string RPCArg::ToString(const bool oneline) const
1265
2.47k
{
1266
2.47k
    if (oneline && !m_opts.oneline_description.empty()) {
1267
86
        if (m_opts.oneline_description[0] == '\"' && m_type != Type::STR_HEX && m_type != Type::STR && gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
1268
0
            throw std::runtime_error{
1269
0
                STR_INTERNAL_BUG(strprintf("non-string RPC arg \"%s\" quotes oneline_description:\n%s",
1270
0
                    m_names, m_opts.oneline_description)
1271
0
                )};
1272
0
        }
1273
86
        return m_opts.oneline_description;
1274
86
    }
1275
1276
2.38k
    switch (m_type) {
1277
417
    case Type::STR_HEX:
1278
1.22k
    case Type::STR: {
1279
1.22k
        return "\"" + GetFirstName() + "\"";
1280
417
    }
1281
397
    case Type::NUM:
1282
406
    case Type::RANGE:
1283
468
    case Type::AMOUNT:
1284
787
    case Type::BOOL: {
1285
787
        return GetFirstName();
1286
468
    }
1287
104
    case Type::OBJ:
1288
131
    case Type::OBJ_NAMED_PARAMS:
1289
165
    case Type::OBJ_USER_KEYS: {
1290
        // NOLINTNEXTLINE(misc-no-recursion)
1291
368
        const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
1292
165
        if (m_type == Type::OBJ) {
1293
104
            return "{" + res + "}";
1294
104
        } else {
1295
61
            return "{" + res + ",...}";
1296
61
        }
1297
165
    }
1298
210
    case Type::ARR: {
1299
210
        std::string res;
1300
259
        for (const auto& i : m_inner) {
1301
259
            res += i.ToString(oneline) + ",";
1302
259
        }
1303
210
        return "[" + res + "...]";
1304
165
    }
1305
2.38k
    } // no default case, so the compiler can warn about missing cases
1306
2.38k
    NONFATAL_UNREACHABLE();
1307
2.38k
}
1308
1309
static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
1310
299
{
1311
299
    if (value.isNum()) {
1312
86
        return {0, value.getInt<int64_t>()};
1313
86
    }
1314
213
    if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
1315
213
        int64_t low = value[0].getInt<int64_t>();
1316
213
        int64_t high = value[1].getInt<int64_t>();
1317
213
        if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
1318
209
        return {low, high};
1319
213
    }
1320
0
    throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1321
213
}
1322
1323
std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1324
299
{
1325
299
    int64_t low, high;
1326
299
    std::tie(low, high) = ParseRange(value);
1327
299
    if (low < 0) {
1328
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
1329
4
    }
1330
295
    if ((high >> 31) != 0) {
1331
6
        throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1332
6
    }
1333
289
    if (high >= low + 1000000) {
1334
4
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1335
4
    }
1336
285
    return {low, high};
1337
289
}
1338
1339
std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1340
1.62k
{
1341
1.62k
    std::string desc_str;
1342
1.62k
    std::pair<int64_t, int64_t> range = {0, 1000};
1343
1.62k
    if (scanobject.isStr()) {
1344
1.51k
        desc_str = scanobject.get_str();
1345
1.51k
    } else if (scanobject.isObject()) {
1346
109
        const UniValue& desc_uni{scanobject.find_value("desc")};
1347
109
        if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
1348
109
        desc_str = desc_uni.get_str();
1349
109
        const UniValue& range_uni{scanobject.find_value("range")};
1350
109
        if (!range_uni.isNull()) {
1351
100
            range = ParseDescriptorRange(range_uni);
1352
100
        }
1353
109
    } else {
1354
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1355
0
    }
1356
1357
1.62k
    std::string error;
1358
1.62k
    auto descs = Parse(desc_str, provider, error);
1359
1.62k
    if (descs.empty()) {
1360
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1361
1
    }
1362
1.62k
    if (!descs.at(0)->IsRange()) {
1363
1.52k
        range.first = 0;
1364
1.52k
        range.second = 0;
1365
1.52k
    }
1366
1.62k
    std::vector<CScript> ret;
1367
23.3k
    for (int64_t i = range.first; i <= range.second; ++i) {
1368
21.7k
        for (const auto& desc : descs) {
1369
21.7k
            std::vector<CScript> scripts;
1370
21.7k
            if (!desc->Expand(i, provider, scripts, provider)) {
1371
0
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1372
0
            }
1373
21.7k
            if (expand_priv) {
1374
2.11k
                desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1375
2.11k
            }
1376
21.7k
            std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1377
21.7k
        }
1378
21.7k
    }
1379
1.62k
    return ret;
1380
1.62k
}
1381
1382
/** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */
1383
[[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1384
11
{
1385
11
    CHECK_NONFATAL(!bilingual_strings.empty());
1386
11
    UniValue result{UniValue::VARR};
1387
11
    for (const auto& s : bilingual_strings) {
1388
11
        result.push_back(s.original);
1389
11
    }
1390
11
    return result;
1391
11
}
1392
1393
void PushWarnings(const UniValue& warnings, UniValue& obj)
1394
837
{
1395
837
    if (warnings.empty()) return;
1396
387
    obj.pushKV("warnings", warnings);
1397
387
}
1398
1399
void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1400
1.08k
{
1401
1.08k
    if (warnings.empty()) return;
1402
11
    obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1403
11
}
1404
1405
51.9k
std::vector<RPCResult> ScriptPubKeyDoc() {
1406
51.9k
    return
1407
51.9k
         {
1408
51.9k
             {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1409
51.9k
             {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1410
51.9k
             {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1411
51.9k
             {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1412
51.9k
             {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
1413
51.9k
         };
1414
51.9k
}
1415
1416
uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit)
1417
19.9k
{
1418
19.9k
    arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))};
1419
19.9k
    return ArithToUint256(target);
1420
19.9k
}
1421
1422
std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary)
1423
32.5k
{
1424
32.5k
    if (fields.empty()) return fields;
1425
32.5k
    std::vector<RPCResult> result;
1426
32.5k
    result.reserve(fields.size());
1427
254k
    for (size_t i = 0; i < fields.size(); ++i) {
1428
222k
        RPCResultOptions opts = fields[i].m_opts;
1429
222k
        if (i == 0) {
1430
32.5k
            opts.print_elision = summary;
1431
189k
        } else {
1432
189k
            opts.print_elision = HelpElisionSkip{};
1433
189k
        }
1434
222k
        result.emplace_back(fields[i], std::move(opts));
1435
222k
    }
1436
32.5k
    return result;
1437
32.5k
}