Coverage Report

Created: 2026-07-14 18:13

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