Coverage Report

Created: 2026-11-13 17:38

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