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.h
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
#ifndef BITCOIN_RPC_UTIL_H
6
#define BITCOIN_RPC_UTIL_H
7
8
#include <addresstype.h>
9
#include <consensus/amount.h>
10
#include <policy/feerate.h>
11
#include <pubkey.h>
12
#include <rpc/protocol.h>
13
#include <rpc/request.h>
14
#include <script/script.h>
15
#include <uint256.h>
16
#include <univalue.h>
17
#include <util/check.h>
18
19
#include <cstddef>
20
#include <cstdint>
21
#include <functional>
22
#include <map>
23
#include <optional>
24
#include <stdexcept>
25
#include <string>
26
#include <string_view>
27
#include <type_traits>
28
#include <utility>
29
#include <variant>
30
#include <vector>
31
32
enum class OutputType;
33
struct FlatSigningProvider;
34
struct bilingual_str;
35
class CBlockIndex;
36
37
namespace common {
38
enum class PSBTError;
39
} // namespace common
40
namespace node {
41
enum class TransactionError;
42
} // namespace node
43
44
inline constexpr bool DEFAULT_RPC_DOC_CHECK{
45
#ifdef RPC_DOC_CHECK
46
    true
47
#else
48
    false
49
#endif
50
};
51
52
/**
53
 * String used to describe UNIX epoch time in documentation, factored out to a
54
 * constant for consistency.
55
 */
56
extern const std::string UNIX_EPOCH_TIME;
57
58
/**
59
 * Example bech32 addresses for the RPCExamples help documentation. They are intentionally
60
 * invalid to prevent accidental transactions by users.
61
 */
62
extern const std::string EXAMPLE_ADDRESS[2];
63
64
struct Sections;
65
66
struct HelpResult : std::runtime_error {
67
1.10k
    explicit HelpResult(const std::string& msg) : std::runtime_error{msg} {}
68
};
69
70
/**
71
 * Gets all existing output types formatted for RPC help sections.
72
 *
73
 * @return Comma separated string representing output type names.
74
 */
75
std::string GetAllOutputTypes();
76
77
/** Wrapper for UniValue::VType, which includes typeAny:
78
 * Used to denote don't care type. */
79
struct UniValueType {
80
24.3k
    UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
81
2.53k
    UniValueType() : typeAny(true) {}
82
    bool typeAny;
83
    UniValue::VType type;
84
};
85
86
/*
87
  Check for expected keys/value types in an Object.
88
*/
89
void RPCTypeCheckObj(const UniValue& o,
90
    const std::map<std::string, UniValueType>& typesExpected,
91
    bool fAllowNull = false,
92
    bool fStrict = false);
93
94
/**
95
 * Utilities: convert hex-encoded Values
96
 * (throws error if not hex).
97
 */
98
uint256 ParseHashV(const UniValue& v, std::string_view name);
99
uint256 ParseHashO(const UniValue& o, std::string_view strKey);
100
std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name);
101
std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey);
102
103
/**
104
 * Parses verbosity from provided UniValue.
105
 *
106
 * @param[in] arg The verbosity argument as an int (0, 1, 2,...) or bool if allow_bool is set to true
107
 * @param[in] default_verbosity The value to return if verbosity argument is null
108
 * @param[in] allow_bool If true, allows arg to be a bool and parses it
109
 * @returns An integer describing the verbosity level (e.g. 0, 1, 2, etc.)
110
 * @throws JSONRPCError if allow_bool is false but arg provided is boolean
111
 */
112
int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool);
113
114
/**
115
 * Validate and return a CAmount from a UniValue number or string.
116
 *
117
 * @param[in] value     UniValue number or string to parse.
118
 * @param[in] decimals  Number of significant digits (default: 8).
119
 * @returns a CAmount if the various checks pass.
120
 */
121
CAmount AmountFromValue(const UniValue& value, int decimals = 8);
122
/**
123
 * Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
124
 * Reject negative values or rates larger than 1BTC/kvB.
125
 */
126
CFeeRate ParseFeeRate(const UniValue& json);
127
128
using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
129
std::string HelpExampleCli(const std::string& methodname, const std::string& args);
130
std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
131
std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
132
std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
133
134
CPubKey HexToPubKey(const std::string& hex_in);
135
CTxDestination AddAndGetMultisigDestination(int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
136
137
UniValue DescribeAddress(const CTxDestination& dest);
138
139
/** Parse a sighash string representation and raise an RPC error if it is invalid. */
140
std::optional<int> ParseSighashString(const UniValue& sighash);
141
142
//! Parse a confirm target option and raise an RPC error if it is invalid.
143
unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
144
145
RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr);
146
UniValue JSONRPCPSBTError(common::PSBTError err);
147
UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
148
149
//! Parse a JSON range specified as int64, or [int64, int64]
150
std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
151
152
/** Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range of 1000. */
153
std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, bool expand_priv = false);
154
155
//! Parse BIP32 path
156
std::vector<uint32_t> ParsePathBIP32(const std::string& path);
157
158
/**
159
 * Serializing JSON objects depends on the outer type. Only arrays and
160
 * dictionaries can be nested in json. The top-level outer type is "NONE".
161
 */
162
enum class OuterType {
163
    ARR,
164
    OBJ,
165
    NONE, // Only set on first recursion
166
};
167
168
struct RPCArgOptions {
169
    bool skip_type_check{false};
170
    std::string oneline_description{};   //!< Should be empty unless it is supposed to override the auto-generated summary line
171
    std::vector<std::string> type_str{}; //!< Should be empty unless it is supposed to override the auto-generated type strings. Vector length is either 0 or 2, m_opts.type_str.at(0) will override the type of the value in a key-value pair, m_opts.type_str.at(1) will override the type in the argument description.
172
    bool placeholder{false};             //!< If set, the argument is retained only for compatibility and should generally be omitted.
173
    bool hidden{false};                  //!< For testing only
174
    bool also_positional{false};         //!< If set allows a named-parameter field in an OBJ_NAMED_PARAM options object
175
                                         //!< to have the same name as a top-level parameter. By default the RPC
176
                                         //!< framework disallows this, because if an RPC request passes the value by
177
                                         //!< name, it is assigned to top-level parameter position, not to the options
178
                                         //!< position, defeating the purpose of using OBJ_NAMED_PARAMS instead OBJ for
179
                                         //!< that option. But sometimes it makes sense to allow less-commonly used
180
                                         //!< options to be passed by name only, and more commonly used options to be
181
                                         //!< passed by name or position, so the RPC framework allows this as long as
182
                                         //!< methods set the also_positional flag and read values from both positions.
183
};
184
185
// NOLINTNEXTLINE(misc-no-recursion)
186
struct RPCArg {
187
    enum class Type {
188
        OBJ,
189
        ARR,
190
        STR,
191
        NUM,
192
        BOOL,
193
        OBJ_NAMED_PARAMS, //!< Special type that behaves almost exactly like
194
                          //!< OBJ, defining an options object with a list of
195
                          //!< pre-defined keys. The only difference between OBJ
196
                          //!< and OBJ_NAMED_PARAMS is that OBJ_NAMED_PARMS
197
                          //!< also allows the keys to be passed as top-level
198
                          //!< named parameters, as a more convenient way to pass
199
                          //!< options to the RPC method without nesting them.
200
        OBJ_USER_KEYS, //!< Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e.g. an options object where the keys are predefined
201
        AMOUNT,        //!< Special type representing a floating point amount (can be either NUM or STR)
202
        STR_HEX,       //!< Special type that is a STR with only hex chars
203
        RANGE,         //!< Special type that is a NUM or [NUM,NUM]
204
    };
205
206
    enum class Optional {
207
        /** Required arg */
208
        NO,
209
        /**
210
         * Optional argument for which the default value is omitted from
211
         * help text for one of two reasons:
212
         * - It's a named argument and has a default value of `null`.
213
         * - Its default value is implicitly clear. That is, elements in an
214
         *    array may not exist by default.
215
         * When possible, the default value should be specified.
216
         */
217
        OMITTED,
218
    };
219
    /** Hint for default value */
220
    using DefaultHint = std::string;
221
    /** Default constant value */
222
    using Default = UniValue;
223
    using Fallback = std::variant<Optional, DefaultHint, Default>;
224
225
    const std::string m_names; //!< The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for named request arguments)
226
    const Type m_type;
227
    const std::vector<RPCArg> m_inner; //!< Only used for arrays or dicts
228
    const Fallback m_fallback;
229
    const std::string m_description;
230
    const RPCArgOptions m_opts;
231
232
    RPCArg(
233
        std::string name,
234
        Type type,
235
        Fallback fallback,
236
        std::string description,
237
        RPCArgOptions opts = {})
238
1.25M
        : m_names{std::move(name)},
239
1.25M
          m_type{type},
240
1.25M
          m_fallback{std::move(fallback)},
241
1.25M
          m_description{std::move(description)},
242
1.25M
          m_opts{std::move(opts)}
243
1.25M
    {
244
1.25M
        CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
245
1.25M
    }
246
247
    RPCArg(
248
        std::string name,
249
        Type type,
250
        Fallback fallback,
251
        std::string description,
252
        std::vector<RPCArg> inner,
253
        RPCArgOptions opts = {})
254
182k
        : m_names{std::move(name)},
255
182k
          m_type{type},
256
182k
          m_inner{std::move(inner)},
257
182k
          m_fallback{std::move(fallback)},
258
182k
          m_description{std::move(description)},
259
182k
          m_opts{std::move(opts)}
260
182k
    {
261
182k
        CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
262
182k
    }
263
264
    bool IsOptional() const;
265
266
    /**
267
     * Check whether the request JSON type matches.
268
     * Returns true if type matches, or object describing error(s) if not.
269
     */
270
    UniValue MatchesType(const UniValue& request) const;
271
272
    /** Return the first of all aliases */
273
    std::string GetFirstName() const;
274
275
    /** Return the name, throws when there are aliases */
276
    std::string GetName() const;
277
278
    /**
279
     * Return the type string of the argument.
280
     * Set oneline to allow it to be overridden by a custom oneline type string (m_opts.oneline_description).
281
     */
282
    std::string ToString(bool oneline) const;
283
    /**
284
     * Return the type string of the argument when it is in an object (dict).
285
     * Set oneline to get the oneline representation (less whitespace)
286
     */
287
    std::string ToStringObj(bool oneline) const;
288
    /**
289
     * Return the description string, including the argument type and whether
290
     * the argument is required.
291
     */
292
    std::string ToDescriptionString(bool is_named_arg) const;
293
};
294
295
/// Controls how an RPCResult is rendered in human-readable help text.
296
/// The std::string alternative carries the summary text rendered as "...".
297
struct HelpElisionNone {}; //!< field printed normally
298
struct HelpElisionSkip {}; //!< field hidden from help
299
using HelpElision = std::variant<HelpElisionNone, HelpElisionSkip, std::string>;
300
301
struct RPCResultOptions {
302
    bool skip_type_check{false};
303
    HelpElision print_elision{HelpElisionNone{}};
304
};
305
306
// NOLINTNEXTLINE(misc-no-recursion)
307
struct RPCResult {
308
    enum class Type {
309
        OBJ,
310
        ARR,
311
        STR,
312
        NUM,
313
        BOOL,
314
        NONE,
315
        ANY,        //!< Special type to disable type checks
316
        STR_AMOUNT, //!< Special string to represent a floating point amount
317
        STR_HEX,    //!< Special string with only hex chars
318
        OBJ_DYN,    //!< Special dictionary with keys that are not literals
319
        ARR_FIXED,  //!< Special array that has a fixed number of entries
320
        NUM_TIME,   //!< Special numeric to denote unix epoch time
321
    };
322
323
    const Type m_type;
324
    const std::string m_key_name;         //!< Only used for dicts
325
    const std::vector<RPCResult> m_inner; //!< Only used for arrays or dicts
326
    const bool m_optional;
327
    const RPCResultOptions m_opts;
328
    const std::string m_description;
329
    const std::string m_cond;
330
331
    RPCResult(
332
        std::string cond,
333
        Type type,
334
        std::string m_key_name,
335
        bool optional,
336
        std::string description,
337
        std::vector<RPCResult> inner = {},
338
        RPCResultOptions opts = {})
339
194k
        : m_type{type},
340
194k
          m_key_name{std::move(m_key_name)},
341
194k
          m_inner{std::move(inner)},
342
194k
          m_optional{optional},
343
194k
          m_opts{std::move(opts)},
344
194k
          m_description{std::move(description)},
345
194k
          m_cond{std::move(cond)}
346
194k
    {
347
194k
        CHECK_NONFATAL(!m_cond.empty());
348
194k
        CheckInnerDoc();
349
194k
    }
350
351
    RPCResult(
352
        std::string cond,
353
        Type type,
354
        std::string m_key_name,
355
        std::string description,
356
        std::vector<RPCResult> inner = {},
357
        RPCResultOptions opts = {})
358
194k
        : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
359
360
    RPCResult(
361
        Type type,
362
        std::string m_key_name,
363
        bool optional,
364
        std::string description,
365
        std::vector<RPCResult> inner = {},
366
        RPCResultOptions opts = {})
367
6.84M
        : m_type{type},
368
6.84M
          m_key_name{std::move(m_key_name)},
369
6.84M
          m_inner{std::move(inner)},
370
6.84M
          m_optional{optional},
371
6.84M
          m_opts{std::move(opts)},
372
6.84M
          m_description{std::move(description)},
373
6.84M
          m_cond{}
374
6.84M
    {
375
6.84M
        CheckInnerDoc();
376
6.84M
    }
377
378
    RPCResult(
379
        Type type,
380
        std::string m_key_name,
381
        std::string description,
382
        std::vector<RPCResult> inner = {},
383
        RPCResultOptions opts = {})
384
5.58M
        : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
385
386
    /// Copy with replacement options, for stamping new opts onto an existing result.
387
    RPCResult(const RPCResult& other, RPCResultOptions opts)
388
680k
        : m_type{other.m_type},
389
680k
          m_key_name{other.m_key_name},
390
680k
          m_inner{other.m_inner},
391
680k
          m_optional{other.m_optional},
392
680k
          m_opts{std::move(opts)},
393
680k
          m_description{other.m_description},
394
680k
          m_cond{other.m_cond} {}
395
396
    /** Append the sections of the result. */
397
    void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, int current_indent = 0) const;
398
    /** Check whether the result JSON type matches.
399
     * Returns true if type matches, or object describing error(s) if not.
400
     */
401
    UniValue MatchesType(const UniValue& result) const;
402
403
private:
404
    void CheckInnerDoc() const;
405
};
406
407
/// Stamp elision onto an entire vector of RPCResult fields at once.
408
/// Merges into existing m_opts so that flags like skip_type_check are preserved.
409
std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary = "");
410
411
struct RPCResults {
412
    const std::vector<RPCResult> m_results;
413
414
    RPCResults(RPCResult result)
415
495k
        : m_results{{result}}
416
495k
    {
417
495k
    }
418
419
    RPCResults(std::initializer_list<RPCResult> results)
420
86.1k
        : m_results{results}
421
86.1k
    {
422
86.1k
    }
423
424
    /**
425
     * Return the description string.
426
     */
427
    std::string ToDescriptionString() const;
428
};
429
430
struct RPCExamples {
431
    const std::string m_examples;
432
    explicit RPCExamples(
433
        std::string examples)
434
581k
        : m_examples(std::move(examples))
435
581k
    {
436
581k
    }
437
    std::string ToDescriptionString() const;
438
};
439
440
class RPCMethod
441
{
442
public:
443
    RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
444
    using RPCMethodImpl = std::function<UniValue(const RPCMethod&, const JSONRPCRequest&)>;
445
    RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
446
447
    UniValue HandleRequest(const JSONRPCRequest& request) const;
448
    /**
449
     * @brief Helper to get a required or default-valued request argument.
450
     *
451
     * Use this function when the argument is required or when it has a default value. If the
452
     * argument is optional and may not be provided, use MaybeArg instead.
453
     *
454
     * This function only works during m_fun(), i.e., it should only be used in
455
     * RPC method implementations. It internally checks whether the user-passed
456
     * argument isNull() and parses (from JSON) and returns the user-passed argument,
457
     * or the default value derived from the RPCArg documentation.
458
     *
459
     * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
460
     *
461
     * @param key The first name of the argument. Aliases are not supported.
462
     * @return The value of the RPC argument (or the default value) cast to type R.
463
     *
464
     * @see MaybeArg for handling optional arguments without default values.
465
     */
466
    template <typename R>
467
    auto Arg(std::string_view key) const
468
172k
    {
469
172k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
172k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
88.0k
            return ArgValue<R>(i);
474
88.0k
        } else {
475
            // Return everything else by reference.
476
84.2k
            return ArgValue<const R&>(i);
477
84.2k
        }
478
172k
    }
auto RPCMethod::Arg<int>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
4.66k
    {
469
4.66k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
4.66k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
4.66k
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
4.66k
    }
auto RPCMethod::Arg<std::basic_string_view<char, std::char_traits<char>>>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
4.22k
    {
469
4.22k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
4.22k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
4.22k
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
4.22k
    }
auto RPCMethod::Arg<unsigned long>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
2.97k
    {
469
2.97k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
2.97k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
2.97k
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
2.97k
    }
auto RPCMethod::Arg<bool>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
74.4k
    {
469
74.4k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
74.4k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
74.4k
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
74.4k
    }
auto RPCMethod::Arg<double>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
128
    {
469
128
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
128
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
128
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
128
    }
auto RPCMethod::Arg<UniValue>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
84.2k
    {
469
84.2k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
            return ArgValue<R>(i);
474
84.2k
        } else {
475
            // Return everything else by reference.
476
84.2k
            return ArgValue<const R&>(i);
477
84.2k
        }
478
84.2k
    }
auto RPCMethod::Arg<long>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
31
    {
469
31
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
31
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
31
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
31
    }
auto RPCMethod::Arg<unsigned int>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
468
1.54k
    {
469
1.54k
        auto i{GetParamIndex(key)};
470
        // Return argument (required or with default value).
471
1.54k
        if constexpr (std::is_trivially_copyable_v<R>) {
472
            // Return trivially copyable types by value.
473
1.54k
            return ArgValue<R>(i);
474
        } else {
475
            // Return everything else by reference.
476
            return ArgValue<const R&>(i);
477
        }
478
1.54k
    }
479
    /**
480
     * @brief Helper to get an optional request argument.
481
     *
482
     * Use this function when the argument is optional and does not have a default value. If the
483
     * argument is required or has a default value, use Arg instead.
484
     *
485
     * This function only works during m_fun(), i.e., it should only be used in
486
     * RPC method implementations. It internally checks whether the user-passed
487
     * argument isNull() and parses (from JSON) and returns the user-passed argument,
488
     * or a falsy value if no argument was passed.
489
     *
490
     * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
491
     *
492
     * @param key The first name of the argument. Aliases are not supported.
493
     * @return For trivially copyable types, a std::optional<R> is returned.
494
     *         For other types, a R* pointer to the argument is returned. If the
495
     *         argument is not provided, std::nullopt or a null pointer is returned.
496
     *
497
     * @see Arg for handling arguments that are required or have a default value.
498
     */
499
    template <typename R>
500
    auto MaybeArg(std::string_view key) const
501
9.06k
    {
502
9.06k
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
9.06k
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
7.71k
            return ArgValue<std::optional<R>>(i);
507
7.71k
        } else {
508
            // Return other types by pointer.
509
1.35k
            return ArgValue<const R*>(i);
510
1.35k
        }
511
9.06k
    }
auto RPCMethod::MaybeArg<double>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
501
723
    {
502
723
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
723
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
723
            return ArgValue<std::optional<R>>(i);
507
        } else {
508
            // Return other types by pointer.
509
            return ArgValue<const R*>(i);
510
        }
511
723
    }
auto RPCMethod::MaybeArg<std::basic_string_view<char, std::char_traits<char>>>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
501
6.06k
    {
502
6.06k
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
6.06k
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
6.06k
            return ArgValue<std::optional<R>>(i);
507
        } else {
508
            // Return other types by pointer.
509
            return ArgValue<const R*>(i);
510
        }
511
6.06k
    }
auto RPCMethod::MaybeArg<UniValue>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
501
1.35k
    {
502
1.35k
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
            return ArgValue<std::optional<R>>(i);
507
1.35k
        } else {
508
            // Return other types by pointer.
509
1.35k
            return ArgValue<const R*>(i);
510
1.35k
        }
511
1.35k
    }
auto RPCMethod::MaybeArg<bool>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
501
822
    {
502
822
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
822
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
822
            return ArgValue<std::optional<R>>(i);
507
        } else {
508
            // Return other types by pointer.
509
            return ArgValue<const R*>(i);
510
        }
511
822
    }
auto RPCMethod::MaybeArg<long>(std::basic_string_view<char, std::char_traits<char>>) const
Line
Count
Source
501
106
    {
502
106
        auto i{GetParamIndex(key)};
503
        // Return optional argument (without default).
504
106
        if constexpr (std::is_trivially_copyable_v<R>) {
505
            // Return trivially copyable types by value, wrapped in optional.
506
106
            return ArgValue<std::optional<R>>(i);
507
        } else {
508
            // Return other types by pointer.
509
            return ArgValue<const R*>(i);
510
        }
511
106
    }
512
    std::string ToString() const;
513
    /** Return the named args that need to be converted from string to another JSON type */
514
    UniValue GetArgMap() const;
515
    /** If the supplied number of args is neither too small nor too high */
516
    bool IsValidNumArgs(size_t num_args) const;
517
    //! Return list of arguments and whether they are named-only.
518
    std::vector<std::pair<std::string, bool>> GetArgNames() const;
519
316
    const std::string& GetDescription() const { return m_description; }
520
316
    const std::vector<RPCArg>& GetArgs() const { return m_args; }
521
316
    const RPCResults& GetResults() const { return m_results; }
522
523
    const std::string m_name;
524
525
private:
526
    const RPCMethodImpl m_fun;
527
    const std::string m_description;
528
    const std::vector<RPCArg> m_args;
529
    const RPCResults m_results;
530
    const RPCExamples m_examples;
531
    mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
532
    template <typename R>
533
    R ArgValue(size_t i) const;
534
    //! Return positional index of a parameter using its first name as key.
535
    size_t GetParamIndex(std::string_view key) const;
536
};
537
538
/**
539
 * Push warning messages to an RPC "warnings" field as a JSON array of strings.
540
 *
541
 * @param[in] warnings  Warning messages to push.
542
 * @param[out] obj      UniValue object to push the warnings array object to.
543
 */
544
void PushWarnings(const UniValue& warnings, UniValue& obj);
545
void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
546
547
std::vector<RPCResult> ScriptPubKeyDoc();
548
549
/***
550
 * Get the target for a given block index.
551
 *
552
 * @param[in] blockindex    the block
553
 * @param[in] pow_limit     PoW limit (consensus parameter)
554
 *
555
 * @return  the target
556
 */
557
uint256 GetTarget(const CBlockIndex& blockindex, uint256 pow_limit);
558
559
#endif // BITCOIN_RPC_UTIL_H