Coverage Report

Created: 2026-07-23 20:35

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