Coverage Report

Created: 2026-08-25 19:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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
inline 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
4.11k
    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
57
    UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
85
0
    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
//! Parse BIP32 path
160
std::vector<uint32_t> ParsePathBIP32(const std::string& path);
161
162
/**
163
 * Serializing JSON objects depends on the outer type. Only arrays and
164
 * dictionaries can be nested in json. The top-level outer type is "NONE".
165
 */
166
enum class OuterType {
167
    ARR,
168
    OBJ,
169
    NONE, // Only set on first recursion
170
};
171
172
struct RPCArgOptions {
173
    bool skip_type_check{false};
174
    std::string oneline_description{};   //!< Should be empty unless it is supposed to override the auto-generated summary line
175
    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.
176
    bool placeholder{false};             //!< If set, the argument is retained only for compatibility and should generally be omitted.
177
    bool hidden{false};                  //!< For testing only
178
    bool also_positional{false};         //!< If set allows a named-parameter field in an OBJ_NAMED_PARAM options object
179
                                         //!< to have the same name as a top-level parameter. By default the RPC
180
                                         //!< framework disallows this, because if an RPC request passes the value by
181
                                         //!< name, it is assigned to top-level parameter position, not to the options
182
                                         //!< position, defeating the purpose of using OBJ_NAMED_PARAMS instead OBJ for
183
                                         //!< that option. But sometimes it makes sense to allow less-commonly used
184
                                         //!< options to be passed by name only, and more commonly used options to be
185
                                         //!< passed by name or position, so the RPC framework allows this as long as
186
                                         //!< methods set the also_positional flag and read values from both positions.
187
};
188
189
// NOLINTNEXTLINE(misc-no-recursion)
190
struct RPCArg {
191
    enum class Type {
192
        OBJ,
193
        ARR,
194
        STR,
195
        NUM,
196
        BOOL,
197
        OBJ_NAMED_PARAMS, //!< Special type that behaves almost exactly like
198
                          //!< OBJ, defining an options object with a list of
199
                          //!< pre-defined keys. The only difference between OBJ
200
                          //!< and OBJ_NAMED_PARAMS is that OBJ_NAMED_PARMS
201
                          //!< also allows the keys to be passed as top-level
202
                          //!< named parameters, as a more convenient way to pass
203
                          //!< options to the RPC method without nesting them.
204
        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
205
        AMOUNT,        //!< Special type representing a floating point amount (can be either NUM or STR)
206
        STR_HEX,       //!< Special type that is a STR with only hex chars
207
        RANGE,         //!< Special type that is a NUM or [NUM,NUM]
208
    };
209
210
    enum class Optional {
211
        /** Required arg */
212
        NO,
213
        /**
214
         * Optional argument for which the default value is omitted from
215
         * help text for one of two reasons:
216
         * - It's a named argument and has a default value of `null`.
217
         * - Its default value is implicitly clear. That is, elements in an
218
         *    array may not exist by default.
219
         * When possible, the default value should be specified.
220
         */
221
        OMITTED,
222
    };
223
    /** Hint for default value */
224
    using DefaultHint = std::string;
225
    /** Default constant value */
226
    using Default = UniValue;
227
    using Fallback = std::variant<Optional, DefaultHint, Default>;
228
229
    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)
230
    const Type m_type;
231
    const std::vector<RPCArg> m_inner; //!< Only used for arrays or dicts
232
    const Fallback m_fallback;
233
    const std::string m_description;
234
    const RPCArgOptions m_opts;
235
236
    RPCArg(
237
        std::string name,
238
        Type type,
239
        Fallback fallback,
240
        std::string description,
241
        RPCArgOptions opts = {})
242
39.2k
        : m_names{std::move(name)},
243
39.2k
          m_type{type},
244
39.2k
          m_fallback{std::move(fallback)},
245
39.2k
          m_description{std::move(description)},
246
39.2k
          m_opts{std::move(opts)}
247
39.2k
    {
248
39.2k
        CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
249
39.2k
    }
250
251
    RPCArg(
252
        std::string name,
253
        Type type,
254
        Fallback fallback,
255
        std::string description,
256
        std::vector<RPCArg> inner,
257
        RPCArgOptions opts = {})
258
9.70k
        : m_names{std::move(name)},
259
9.70k
          m_type{type},
260
9.70k
          m_inner{std::move(inner)},
261
9.70k
          m_fallback{std::move(fallback)},
262
9.70k
          m_description{std::move(description)},
263
9.70k
          m_opts{std::move(opts)}
264
9.70k
    {
265
9.70k
        CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
266
9.70k
    }
267
268
    bool IsOptional() const;
269
270
    /**
271
     * Check whether the request JSON type matches.
272
     * Returns true if type matches, or object describing error(s) if not.
273
     */
274
    UniValue MatchesType(const UniValue& request) const;
275
276
    /** Return the first of all aliases */
277
    std::string GetFirstName() const;
278
279
    /** Return the name, throws when there are aliases */
280
    std::string GetName() const;
281
282
    /**
283
     * Return the type string of the argument.
284
     * Set oneline to allow it to be overridden by a custom oneline type string (m_opts.oneline_description).
285
     */
286
    std::string ToString(bool oneline) const;
287
    /**
288
     * Return the type string of the argument when it is in an object (dict).
289
     * Set oneline to get the oneline representation (less whitespace)
290
     */
291
    std::string ToStringObj(bool oneline) const;
292
    /**
293
     * Return the description string, including the argument type and whether
294
     * the argument is required.
295
     */
296
    std::string ToDescriptionString(bool is_named_arg) const;
297
};
298
299
/// Controls how an RPCResult is rendered in human-readable help text.
300
/// The std::string alternative carries the summary text rendered as "...".
301
struct HelpElisionNone {}; //!< field printed normally
302
struct HelpElisionSkip {}; //!< field hidden from help
303
using HelpElision = std::variant<HelpElisionNone, HelpElisionSkip, std::string>;
304
305
struct RPCResultOptions {
306
    bool skip_type_check{false};
307
    HelpElision print_elision{HelpElisionNone{}};
308
};
309
310
// NOLINTNEXTLINE(misc-no-recursion)
311
struct RPCResult {
312
    enum class Type {
313
        OBJ,
314
        ARR,
315
        STR,
316
        NUM,
317
        BOOL,
318
        NONE,
319
        ANY,        //!< Special type to disable type checks
320
        STR_AMOUNT, //!< Special string to represent a floating point amount
321
        STR_HEX,    //!< Special string with only hex chars
322
        OBJ_DYN,    //!< Special dictionary with keys that are not literals
323
        ARR_FIXED,  //!< Special array that has a fixed number of entries
324
        NUM_TIME,   //!< Special numeric to denote unix epoch time
325
    };
326
327
    const Type m_type;
328
    const std::string m_key_name;         //!< Only used for dicts
329
    const std::vector<RPCResult> m_inner; //!< Only used for arrays or dicts
330
    const bool m_optional;
331
    const RPCResultOptions m_opts;
332
    const std::string m_description;
333
    const std::string m_cond;
334
335
    RPCResult(
336
        std::string cond,
337
        Type type,
338
        std::string m_key_name,
339
        bool optional,
340
        std::string description,
341
        std::vector<RPCResult> inner = {},
342
        RPCResultOptions opts = {})
343
1.73k
        : m_type{type},
344
1.73k
          m_key_name{std::move(m_key_name)},
345
1.73k
          m_inner{std::move(inner)},
346
1.73k
          m_optional{optional},
347
1.73k
          m_opts{std::move(opts)},
348
1.73k
          m_description{std::move(description)},
349
1.73k
          m_cond{std::move(cond)}
350
1.73k
    {
351
1.73k
        CHECK_NONFATAL(!m_cond.empty());
352
1.73k
        CheckInnerDoc();
353
1.73k
    }
354
355
    RPCResult(
356
        std::string cond,
357
        Type type,
358
        std::string m_key_name,
359
        std::string description,
360
        std::vector<RPCResult> inner = {},
361
        RPCResultOptions opts = {})
362
1.73k
        : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
363
364
    RPCResult(
365
        Type type,
366
        std::string m_key_name,
367
        bool optional,
368
        std::string description,
369
        std::vector<RPCResult> inner = {},
370
        RPCResultOptions opts = {})
371
209k
        : m_type{type},
372
209k
          m_key_name{std::move(m_key_name)},
373
209k
          m_inner{std::move(inner)},
374
209k
          m_optional{optional},
375
209k
          m_opts{std::move(opts)},
376
209k
          m_description{std::move(description)},
377
209k
          m_cond{}
378
209k
    {
379
209k
        CheckInnerDoc();
380
209k
    }
381
382
    RPCResult(
383
        Type type,
384
        std::string m_key_name,
385
        std::string description,
386
        std::vector<RPCResult> inner = {},
387
        RPCResultOptions opts = {})
388
138k
        : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
389
390
    /// Copy with replacement options, for stamping new opts onto an existing result.
391
    RPCResult(const RPCResult& other, RPCResultOptions opts)
392
12.0k
        : m_type{other.m_type},
393
12.0k
          m_key_name{other.m_key_name},
394
12.0k
          m_inner{other.m_inner},
395
12.0k
          m_optional{other.m_optional},
396
12.0k
          m_opts{std::move(opts)},
397
12.0k
          m_description{other.m_description},
398
12.0k
          m_cond{other.m_cond} {}
399
400
    /** Append the sections of the result. */
401
    void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, int current_indent = 0) const;
402
    /** Return the type string of the result when it is in an object (dict). */
403
    std::string ToStringObj() const;
404
    /** Return the description string, including the result type. */
405
    std::string ToDescriptionString() const;
406
    /** Check whether the result JSON type matches.
407
     * Returns true if type matches, or object describing error(s) if not.
408
     */
409
    UniValue MatchesType(const UniValue& result) const;
410
411
private:
412
    void CheckInnerDoc() const;
413
};
414
415
/// Stamp elision onto an entire vector of RPCResult fields at once.
416
/// Merges into existing m_opts so that flags like skip_type_check are preserved.
417
std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary = "");
418
419
struct RPCResults {
420
    const std::vector<RPCResult> m_results;
421
422
    RPCResults(RPCResult result)
423
17.4k
        : m_results{{result}}
424
17.4k
    {
425
17.4k
    }
426
427
    RPCResults(std::initializer_list<RPCResult> results)
428
995
        : m_results{results}
429
995
    {
430
995
    }
431
432
    /**
433
     * Return the description string.
434
     */
435
    std::string ToDescriptionString() const;
436
};
437
438
struct RPCExamples {
439
    const std::string m_examples;
440
    explicit RPCExamples(
441
        std::string examples)
442
18.4k
        : m_examples(std::move(examples))
443
18.4k
    {
444
18.4k
    }
445
    std::string ToDescriptionString() const;
446
};
447
448
class RPCMethod
449
{
450
public:
451
    RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
452
    using RPCMethodImpl = std::function<UniValue(const RPCMethod&, const JSONRPCRequest&)>;
453
    RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
454
455
    UniValue HandleRequest(const JSONRPCRequest& request) const;
456
    /**
457
     * @brief Helper to get a required or default-valued request argument.
458
     *
459
     * Use this function when the argument is required or when it has a default value. If the
460
     * argument is optional and may not be provided, use MaybeArg instead.
461
     *
462
     * This function only works during m_fun(), i.e., it should only be used in
463
     * RPC method implementations. It internally checks whether the user-passed
464
     * argument isNull() and parses (from JSON) and returns the user-passed argument,
465
     * or the default value derived from the RPCArg documentation.
466
     *
467
     * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
468
     *
469
     * @return The value of the RPC argument (or the default value) cast to type R.
470
     *
471
     * @see MaybeArg for handling optional arguments without default values.
472
     */
473
    template <typename R>
474
    auto Arg(std::string_view key) const
475
1.16k
    {
476
1.16k
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
1.16k
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
901
            return ArgValue<R>(i);
481
901
        } else {
482
            // Return everything else by reference.
483
268
            return ArgValue<const R&>(i);
484
268
        }
485
1.16k
    }
_ZNK9RPCMethod3ArgIbEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
475
3
    {
476
3
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
3
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
3
            return ArgValue<R>(i);
481
        } else {
482
            // Return everything else by reference.
483
            return ArgValue<const R&>(i);
484
        }
485
3
    }
_ZNK9RPCMethod3ArgIiEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
475
27
    {
476
27
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
27
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
27
            return ArgValue<R>(i);
481
        } else {
482
            // Return everything else by reference.
483
            return ArgValue<const R&>(i);
484
        }
485
27
    }
_ZNK9RPCMethod3ArgIjEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
475
166
    {
476
166
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
166
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
166
            return ArgValue<R>(i);
481
        } else {
482
            // Return everything else by reference.
483
            return ArgValue<const R&>(i);
484
        }
485
166
    }
_ZNK9RPCMethod3ArgISt17basic_string_viewIcSt11char_traitsIcEEEEDaS4_
Line
Count
Source
475
705
    {
476
705
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
705
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
705
            return ArgValue<R>(i);
481
        } else {
482
            // Return everything else by reference.
483
            return ArgValue<const R&>(i);
484
        }
485
705
    }
_ZNK9RPCMethod3ArgI8UniValueEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
475
268
    {
476
268
        auto i{GetParamIndex(key)};
477
        // Return argument (required or with default value).
478
        if constexpr (std::is_trivially_copyable_v<R>) {
479
            // Return trivially copyable types by value.
480
            return ArgValue<R>(i);
481
268
        } else {
482
            // Return everything else by reference.
483
268
            return ArgValue<const R&>(i);
484
268
        }
485
268
    }
Unexecuted instantiation: _ZNK9RPCMethod3ArgImEEDaSt17basic_string_viewIcSt11char_traitsIcEE
486
    /**
487
     * @brief Helper to get an optional request argument.
488
     *
489
     * Use this function when the argument is optional and does not have a default value. If the
490
     * argument is required or has a default value, use Arg instead.
491
     *
492
     * This function only works during m_fun(), i.e., it should only be used in
493
     * RPC method implementations. It internally checks whether the user-passed
494
     * argument isNull() and parses (from JSON) and returns the user-passed argument,
495
     * or a falsy value if no argument was passed.
496
     *
497
     * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
498
     *
499
     * @return For trivially copyable types, a std::optional<R> is returned.
500
     *         For other types, a R* pointer to the argument is returned. If the
501
     *         argument is not provided, std::nullopt or a null pointer is returned.
502
     *
503
     * @see Arg for handling arguments that are required or have a default value.
504
     */
505
    template <typename R>
506
    auto MaybeArg(std::string_view key) const
507
149
    {
508
149
        auto i{GetParamIndex(key)};
509
        // Return optional argument (without default).
510
149
        if constexpr (std::is_trivially_copyable_v<R>) {
511
            // Return trivially copyable types by value, wrapped in optional.
512
104
            return ArgValue<std::optional<R>>(i);
513
104
        } else {
514
            // Return other types by pointer.
515
45
            return ArgValue<const R*>(i);
516
45
        }
517
149
    }
_ZNK9RPCMethod8MaybeArgISt17basic_string_viewIcSt11char_traitsIcEEEEDaS4_
Line
Count
Source
507
63
    {
508
63
        auto i{GetParamIndex(key)};
509
        // Return optional argument (without default).
510
63
        if constexpr (std::is_trivially_copyable_v<R>) {
511
            // Return trivially copyable types by value, wrapped in optional.
512
63
            return ArgValue<std::optional<R>>(i);
513
        } else {
514
            // Return other types by pointer.
515
            return ArgValue<const R*>(i);
516
        }
517
63
    }
Unexecuted instantiation: _ZNK9RPCMethod8MaybeArgIbEEDaSt17basic_string_viewIcSt11char_traitsIcEE
_ZNK9RPCMethod8MaybeArgI8UniValueEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
507
45
    {
508
45
        auto i{GetParamIndex(key)};
509
        // Return optional argument (without default).
510
        if constexpr (std::is_trivially_copyable_v<R>) {
511
            // Return trivially copyable types by value, wrapped in optional.
512
            return ArgValue<std::optional<R>>(i);
513
45
        } else {
514
            // Return other types by pointer.
515
45
            return ArgValue<const R*>(i);
516
45
        }
517
45
    }
_ZNK9RPCMethod8MaybeArgIdEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
507
13
    {
508
13
        auto i{GetParamIndex(key)};
509
        // Return optional argument (without default).
510
13
        if constexpr (std::is_trivially_copyable_v<R>) {
511
            // Return trivially copyable types by value, wrapped in optional.
512
13
            return ArgValue<std::optional<R>>(i);
513
        } else {
514
            // Return other types by pointer.
515
            return ArgValue<const R*>(i);
516
        }
517
13
    }
_ZNK9RPCMethod8MaybeArgIlEEDaSt17basic_string_viewIcSt11char_traitsIcEE
Line
Count
Source
507
28
    {
508
28
        auto i{GetParamIndex(key)};
509
        // Return optional argument (without default).
510
28
        if constexpr (std::is_trivially_copyable_v<R>) {
511
            // Return trivially copyable types by value, wrapped in optional.
512
28
            return ArgValue<std::optional<R>>(i);
513
        } else {
514
            // Return other types by pointer.
515
            return ArgValue<const R*>(i);
516
        }
517
28
    }
518
    std::string ToString() const;
519
    /** Return the named args that need to be converted from string to another JSON type */
520
    UniValue GetArgMap() const;
521
    /** If the supplied number of args is neither too small nor too high */
522
    bool IsValidNumArgs(size_t num_args) const;
523
    //! Return list of arguments and whether they are named-only.
524
    std::vector<std::pair<std::string, bool>> GetArgNames() const;
525
499
    const std::string& GetDescription() const { return m_description; }
526
499
    const std::vector<RPCArg>& GetArgs() const { return m_args; }
527
499
    const RPCResults& GetResults() const { return m_results; }
528
529
    const std::string m_name;
530
531
private:
532
    const RPCMethodImpl m_fun;
533
    const std::string m_description;
534
    const std::vector<RPCArg> m_args;
535
    const RPCResults m_results;
536
    const RPCExamples m_examples;
537
    mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
538
    template <typename R>
539
    R ArgValue(size_t i) const;
540
    //! Return positional index of a parameter using its name as key.
541
    size_t GetParamIndex(std::string_view key) const;
542
};
543
544
/**
545
 * Push warning messages to an RPC "warnings" field as a JSON array of strings.
546
 *
547
 * @param[in] warnings  Warning messages to push.
548
 * @param[out] obj      UniValue object to push the warnings array object to.
549
 */
550
void PushWarnings(const UniValue& warnings, UniValue& obj);
551
void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
552
553
std::vector<RPCResult> ScriptPubKeyDoc();
554
555
/***
556
 * Get the target for a given block index.
557
 *
558
 * @param[in] blockindex    the block
559
 * @param[in] pow_limit     PoW limit (consensus parameter)
560
 *
561
 * @return  the target
562
 */
563
uint256 GetTarget(const CBlockIndex& blockindex, uint256 pow_limit);
564
565
#endif // BITCOIN_RPC_UTIL_H