LCOV - code coverage report
Current view: top level - src/rpc - util.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 100.0 % 63 63
Test Date: 2024-07-04 05:05:02 Functions: 100.0 % 15 15
Branches: 35.2 % 219 77

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2017-2022 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                 :             : /**
      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   [ +  -  +  - ]:        3223 :     UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
           [ +  -  +  -  
          +  -  +  -  +  
           - ][ #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
           # ][ +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
           - ][ +  -  +  
             -  +  -  +  
                      - ]
      81   [ +  -  +  -  :        1508 :     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                 :             :  * Validate and return a CAmount from a UniValue number or string.
     105                 :             :  *
     106                 :             :  * @param[in] value     UniValue number or string to parse.
     107                 :             :  * @param[in] decimals  Number of significant digits (default: 8).
     108                 :             :  * @returns a CAmount if the various checks pass.
     109                 :             :  */
     110                 :             : CAmount AmountFromValue(const UniValue& value, int decimals = 8);
     111                 :             : /**
     112                 :             :  * Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
     113                 :             :  * Reject negative values or rates larger than 1BTC/kvB.
     114                 :             :  */
     115                 :             : CFeeRate ParseFeeRate(const UniValue& json);
     116                 :             : 
     117                 :             : using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
     118                 :             : std::string HelpExampleCli(const std::string& methodname, const std::string& args);
     119                 :             : std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
     120                 :             : std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
     121                 :             : std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
     122                 :             : 
     123                 :             : CPubKey HexToPubKey(const std::string& hex_in);
     124                 :             : CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
     125                 :             : CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
     126                 :             : 
     127                 :             : UniValue DescribeAddress(const CTxDestination& dest);
     128                 :             : 
     129                 :             : /** Parse a sighash string representation and raise an RPC error if it is invalid. */
     130                 :             : int ParseSighashString(const UniValue& sighash);
     131                 :             : 
     132                 :             : //! Parse a confirm target option and raise an RPC error if it is invalid.
     133                 :             : unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
     134                 :             : 
     135                 :             : RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr);
     136                 :             : UniValue JSONRPCPSBTError(common::PSBTError err);
     137                 :             : UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
     138                 :             : 
     139                 :             : //! Parse a JSON range specified as int64, or [int64, int64]
     140                 :             : std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
     141                 :             : 
     142                 :             : /** Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range of 1000. */
     143                 :             : std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false);
     144                 :             : 
     145                 :             : /**
     146                 :             :  * Serializing JSON objects depends on the outer type. Only arrays and
     147                 :             :  * dictionaries can be nested in json. The top-level outer type is "NONE".
     148                 :             :  */
     149                 :             : enum class OuterType {
     150                 :             :     ARR,
     151                 :             :     OBJ,
     152                 :             :     NONE, // Only set on first recursion
     153                 :             : };
     154                 :             : 
     155                 :     1433375 : struct RPCArgOptions {
     156                 :             :     bool skip_type_check{false};
     157                 :             :     std::string oneline_description{};   //!< Should be empty unless it is supposed to override the auto-generated summary line
     158                 :             :     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.
     159                 :             :     bool hidden{false};                  //!< For testing only
     160                 :             :     bool also_positional{false};         //!< If set allows a named-parameter field in an OBJ_NAMED_PARAM options object
     161                 :             :                                          //!< to have the same name as a top-level parameter. By default the RPC
     162                 :             :                                          //!< framework disallows this, because if an RPC request passes the value by
     163                 :             :                                          //!< name, it is assigned to top-level parameter position, not to the options
     164                 :             :                                          //!< position, defeating the purpose of using OBJ_NAMED_PARAMS instead OBJ for
     165                 :             :                                          //!< that option. But sometimes it makes sense to allow less-commonly used
     166                 :             :                                          //!< options to be passed by name only, and more commonly used options to be
     167                 :             :                                          //!< passed by name or position, so the RPC framework allows this as long as
     168                 :             :                                          //!< methods set the also_positional flag and read values from both positions.
     169                 :             : };
     170                 :             : 
     171                 :             : // NOLINTNEXTLINE(misc-no-recursion)
     172                 :             : struct RPCArg {
     173                 :             :     enum class Type {
     174                 :             :         OBJ,
     175                 :             :         ARR,
     176                 :             :         STR,
     177                 :             :         NUM,
     178                 :             :         BOOL,
     179                 :             :         OBJ_NAMED_PARAMS, //!< Special type that behaves almost exactly like
     180                 :             :                           //!< OBJ, defining an options object with a list of
     181                 :             :                           //!< pre-defined keys. The only difference between OBJ
     182                 :             :                           //!< and OBJ_NAMED_PARAMS is that OBJ_NAMED_PARMS
     183                 :             :                           //!< also allows the keys to be passed as top-level
     184                 :             :                           //!< named parameters, as a more convenient way to pass
     185                 :             :                           //!< options to the RPC method without nesting them.
     186                 :             :         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
     187                 :             :         AMOUNT,        //!< Special type representing a floating point amount (can be either NUM or STR)
     188                 :             :         STR_HEX,       //!< Special type that is a STR with only hex chars
     189                 :             :         RANGE,         //!< Special type that is a NUM or [NUM,NUM]
     190                 :             :     };
     191                 :             : 
     192                 :             :     enum class Optional {
     193                 :             :         /** Required arg */
     194                 :             :         NO,
     195                 :             :         /**
     196                 :             :          * Optional argument for which the default value is omitted from
     197                 :             :          * help text for one of two reasons:
     198                 :             :          * - It's a named argument and has a default value of `null`.
     199                 :             :          * - Its default value is implicitly clear. That is, elements in an
     200                 :             :          *    array may not exist by default.
     201                 :             :          * When possible, the default value should be specified.
     202                 :             :          */
     203                 :             :         OMITTED,
     204                 :             :     };
     205                 :             :     /** Hint for default value */
     206                 :             :     using DefaultHint = std::string;
     207                 :             :     /** Default constant value */
     208                 :             :     using Default = UniValue;
     209                 :             :     using Fallback = std::variant<Optional, DefaultHint, Default>;
     210                 :             : 
     211                 :             :     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)
     212                 :             :     const Type m_type;
     213                 :             :     const std::vector<RPCArg> m_inner; //!< Only used for arrays or dicts
     214                 :             :     const Fallback m_fallback;
     215                 :             :     const std::string m_description;
     216                 :             :     const RPCArgOptions m_opts;
     217                 :             : 
     218                 :     1245542 :     RPCArg(
     219                 :             :         std::string name,
     220                 :             :         Type type,
     221                 :             :         Fallback fallback,
     222                 :             :         std::string description,
     223                 :             :         RPCArgOptions opts = {})
     224                 :     1245542 :         : m_names{std::move(name)},
     225                 :     1245542 :           m_type{std::move(type)},
     226                 :     1245542 :           m_fallback{std::move(fallback)},
     227                 :     1245542 :           m_description{std::move(description)},
     228                 :     2491084 :           m_opts{std::move(opts)}
     229                 :             :     {
     230   [ +  -  -  +  :     1245542 :         CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
                   +  - ]
     231                 :     1245542 :     }
     232                 :             : 
     233                 :      195902 :     RPCArg(
     234                 :             :         std::string name,
     235                 :             :         Type type,
     236                 :             :         Fallback fallback,
     237                 :             :         std::string description,
     238                 :             :         std::vector<RPCArg> inner,
     239                 :             :         RPCArgOptions opts = {})
     240                 :      195902 :         : m_names{std::move(name)},
     241                 :      195902 :           m_type{std::move(type)},
     242                 :      195902 :           m_inner{std::move(inner)},
     243                 :      195902 :           m_fallback{std::move(fallback)},
     244                 :      195902 :           m_description{std::move(description)},
     245                 :      195902 :           m_opts{std::move(opts)}
     246                 :             :     {
     247   [ +  +  -  +  :      391804 :         CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
                      - ]
     248                 :      195902 :     }
     249                 :             : 
     250                 :             :     bool IsOptional() const;
     251                 :             : 
     252                 :             :     /**
     253                 :             :      * Check whether the request JSON type matches.
     254                 :             :      * Returns true if type matches, or object describing error(s) if not.
     255                 :             :      */
     256                 :             :     UniValue MatchesType(const UniValue& request) const;
     257                 :             : 
     258                 :             :     /** Return the first of all aliases */
     259                 :             :     std::string GetFirstName() const;
     260                 :             : 
     261                 :             :     /** Return the name, throws when there are aliases */
     262                 :             :     std::string GetName() const;
     263                 :             : 
     264                 :             :     /**
     265                 :             :      * Return the type string of the argument.
     266                 :             :      * Set oneline to allow it to be overridden by a custom oneline type string (m_opts.oneline_description).
     267                 :             :      */
     268                 :             :     std::string ToString(bool oneline) const;
     269                 :             :     /**
     270                 :             :      * Return the type string of the argument when it is in an object (dict).
     271                 :             :      * Set oneline to get the oneline representation (less whitespace)
     272                 :             :      */
     273                 :             :     std::string ToStringObj(bool oneline) const;
     274                 :             :     /**
     275                 :             :      * Return the description string, including the argument type and whether
     276                 :             :      * the argument is required.
     277                 :             :      */
     278                 :             :     std::string ToDescriptionString(bool is_named_arg) const;
     279                 :             : };
     280                 :             : 
     281                 :             : // NOLINTNEXTLINE(misc-no-recursion)
     282                 :             : struct RPCResult {
     283                 :             :     enum class Type {
     284                 :             :         OBJ,
     285                 :             :         ARR,
     286                 :             :         STR,
     287                 :             :         NUM,
     288                 :             :         BOOL,
     289                 :             :         NONE,
     290                 :             :         ANY,        //!< Special type to disable type checks (for testing only)
     291                 :             :         STR_AMOUNT, //!< Special string to represent a floating point amount
     292                 :             :         STR_HEX,    //!< Special string with only hex chars
     293                 :             :         OBJ_DYN,    //!< Special dictionary with keys that are not literals
     294                 :             :         ARR_FIXED,  //!< Special array that has a fixed number of entries
     295                 :             :         NUM_TIME,   //!< Special numeric to denote unix epoch time
     296                 :             :         ELISION,    //!< Special type to denote elision (...)
     297                 :             :     };
     298                 :             : 
     299                 :             :     const Type m_type;
     300                 :             :     const std::string m_key_name;         //!< Only used for dicts
     301                 :             :     const std::vector<RPCResult> m_inner; //!< Only used for arrays or dicts
     302                 :             :     const bool m_optional;
     303                 :             :     const bool m_skip_type_check;
     304                 :             :     const std::string m_description;
     305                 :             :     const std::string m_cond;
     306                 :             : 
     307                 :      152303 :     RPCResult(
     308                 :             :         std::string cond,
     309                 :             :         Type type,
     310                 :             :         std::string m_key_name,
     311                 :             :         bool optional,
     312                 :             :         std::string description,
     313                 :             :         std::vector<RPCResult> inner = {})
     314                 :      152303 :         : m_type{std::move(type)},
     315                 :      152303 :           m_key_name{std::move(m_key_name)},
     316                 :      152303 :           m_inner{std::move(inner)},
     317                 :      152303 :           m_optional{optional},
     318                 :      152303 :           m_skip_type_check{false},
     319                 :      152303 :           m_description{std::move(description)},
     320                 :      152303 :           m_cond{std::move(cond)}
     321                 :             :     {
     322         [ +  - ]:      152303 :         CHECK_NONFATAL(!m_cond.empty());
     323         [ +  - ]:      152303 :         CheckInnerDoc();
     324                 :      152303 :     }
     325                 :             : 
     326                 :      152303 :     RPCResult(
     327                 :             :         std::string cond,
     328                 :             :         Type type,
     329                 :             :         std::string m_key_name,
     330                 :             :         std::string description,
     331                 :             :         std::vector<RPCResult> inner = {})
     332         [ +  - ]:      152303 :         : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
     333                 :             : 
     334                 :     4507832 :     RPCResult(
     335                 :             :         Type type,
     336                 :             :         std::string m_key_name,
     337                 :             :         bool optional,
     338                 :             :         std::string description,
     339                 :             :         std::vector<RPCResult> inner = {},
     340                 :             :         bool skip_type_check = false)
     341                 :     4507832 :         : m_type{std::move(type)},
     342                 :     4507832 :           m_key_name{std::move(m_key_name)},
     343                 :     4507832 :           m_inner{std::move(inner)},
     344                 :     4507832 :           m_optional{optional},
     345                 :     4507832 :           m_skip_type_check{skip_type_check},
     346                 :     4507832 :           m_description{std::move(description)},
     347         [ +  - ]:     4507832 :           m_cond{}
     348                 :             :     {
     349         [ +  - ]:     4507832 :         CheckInnerDoc();
     350                 :     4507832 :     }
     351                 :             : 
     352                 :     3680100 :     RPCResult(
     353                 :             :         Type type,
     354                 :             :         std::string m_key_name,
     355                 :             :         std::string description,
     356                 :             :         std::vector<RPCResult> inner = {},
     357                 :             :         bool skip_type_check = false)
     358         [ +  - ]:     3680100 :         : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
     359                 :             : 
     360                 :             :     /** Append the sections of the result. */
     361                 :             :     void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
     362                 :             :     /** Return the type string of the result when it is in an object (dict). */
     363                 :             :     std::string ToStringObj() const;
     364                 :             :     /** Return the description string, including the result type. */
     365                 :             :     std::string ToDescriptionString() const;
     366                 :             :     /** Check whether the result JSON type matches.
     367                 :             :      * Returns true if type matches, or object describing error(s) if not.
     368                 :             :      */
     369                 :             :     UniValue MatchesType(const UniValue& result) const;
     370                 :             : 
     371                 :             : private:
     372                 :             :     void CheckInnerDoc() const;
     373                 :             : };
     374                 :             : 
     375   [ +  -  +  - ]:     1076858 : struct RPCResults {
     376                 :             :     const std::vector<RPCResult> m_results;
     377                 :             : 
     378                 :      472933 :     RPCResults(RPCResult result)
     379   [ +  -  +  +  :     1418799 :         : m_results{{result}}
                   -  - ]
     380                 :             :     {
     381                 :      945866 :     }
     382                 :             : 
     383                 :       65473 :     RPCResults(std::initializer_list<RPCResult> results)
     384   [ +  -  +  -  :       65473 :         : m_results{results}
          +  -  #  #  #  
           # ][ +  -  +  
          -  +  -  +  -  
           +  - ][ +  -  
             #  #  #  # ]
           [ +  -  +  - ]
     385                 :             :     {
     386                 :       65473 :     }
     387                 :             : 
     388                 :             :     /**
     389                 :             :      * Return the description string.
     390                 :             :      */
     391                 :             :     std::string ToDescriptionString() const;
     392                 :             : };
     393                 :             : 
     394   [ +  -  +  - ]:     1076858 : struct RPCExamples {
     395                 :             :     const std::string m_examples;
     396                 :      538406 :     explicit RPCExamples(
     397                 :             :         std::string examples)
     398                 :      538406 :         : m_examples(std::move(examples))
     399                 :             :     {
     400                 :             :     }
     401                 :             :     std::string ToDescriptionString() const;
     402                 :             : };
     403                 :             : 
     404                 :             : class RPCHelpMan
     405                 :             : {
     406                 :             : public:
     407                 :             :     RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
     408                 :             :     using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
     409                 :             :     RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
     410                 :             : 
     411                 :             :     UniValue HandleRequest(const JSONRPCRequest& request) const;
     412                 :             :     /**
     413                 :             :      * @brief Helper to get a required or default-valued request argument.
     414                 :             :      *
     415                 :             :      * Use this function when the argument is required or when it has a default value. If the
     416                 :             :      * argument is optional and may not be provided, use MaybeArg instead.
     417                 :             :      *
     418                 :             :      * This function only works during m_fun(), i.e., it should only be used in
     419                 :             :      * RPC method implementations. It internally checks whether the user-passed
     420                 :             :      * argument isNull() and parses (from JSON) and returns the user-passed argument,
     421                 :             :      * or the default value derived from the RPCArg documentation.
     422                 :             :      *
     423                 :             :      * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
     424                 :             :      *
     425                 :             :      * @return The value of the RPC argument (or the default value) cast to type R.
     426                 :             :      *
     427                 :             :      * @see MaybeArg for handling optional arguments without default values.
     428                 :             :      */
     429                 :             :     template <typename R>
     430                 :       27801 :     auto Arg(std::string_view key) const
     431                 :             :     {
     432                 :       27801 :         auto i{GetParamIndex(key)};
     433                 :             :         // Return argument (required or with default value).
     434                 :             :         if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
     435                 :             :             // Return numbers by value.
     436                 :        3037 :             return ArgValue<R>(i);
     437                 :             :         } else {
     438                 :             :             // Return everything else by reference.
     439                 :       24764 :             return ArgValue<const R&>(i);
     440                 :             :         }
     441                 :             :     }
     442                 :             :     /**
     443                 :             :      * @brief Helper to get an optional request argument.
     444                 :             :      *
     445                 :             :      * Use this function when the argument is optional and does not have a default value. If the
     446                 :             :      * argument is required or has a default value, use Arg instead.
     447                 :             :      *
     448                 :             :      * This function only works during m_fun(), i.e., it should only be used in
     449                 :             :      * RPC method implementations. It internally checks whether the user-passed
     450                 :             :      * argument isNull() and parses (from JSON) and returns the user-passed argument,
     451                 :             :      * or a falsy value if no argument was passed.
     452                 :             :      *
     453                 :             :      * The instantiation of this helper for type R must match the corresponding RPCArg::Type.
     454                 :             :      *
     455                 :             :      * @return For integral and floating-point types, a std::optional<R> is returned.
     456                 :             :      *         For other types, a R* pointer to the argument is returned. If the
     457                 :             :      *         argument is not provided, std::nullopt or a null pointer is returned.
     458                 :             :      *
     459                 :             :      * @see Arg for handling arguments that are required or have a default value.
     460                 :             :      */
     461                 :             :     template <typename R>
     462                 :        2381 :     auto MaybeArg(std::string_view key) const
     463                 :             :     {
     464                 :        2381 :         auto i{GetParamIndex(key)};
     465                 :             :         // Return optional argument (without default).
     466                 :             :         if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
     467                 :             :             // Return numbers by value, wrapped in optional.
     468                 :        1703 :             return ArgValue<std::optional<R>>(i);
     469                 :             :         } else {
     470                 :             :             // Return other types by pointer.
     471                 :         678 :             return ArgValue<const R*>(i);
     472                 :             :         }
     473                 :             :     }
     474                 :             :     std::string ToString() const;
     475                 :             :     /** Return the named args that need to be converted from string to another JSON type */
     476                 :             :     UniValue GetArgMap() const;
     477                 :             :     /** If the supplied number of args is neither too small nor too high */
     478                 :             :     bool IsValidNumArgs(size_t num_args) const;
     479                 :             :     //! Return list of arguments and whether they are named-only.
     480                 :             :     std::vector<std::pair<std::string, bool>> GetArgNames() const;
     481                 :             : 
     482                 :             :     const std::string m_name;
     483                 :             : 
     484                 :             : private:
     485                 :             :     const RPCMethodImpl m_fun;
     486                 :             :     const std::string m_description;
     487                 :             :     const std::vector<RPCArg> m_args;
     488                 :             :     const RPCResults m_results;
     489                 :             :     const RPCExamples m_examples;
     490                 :             :     mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
     491                 :             :     template <typename R>
     492                 :             :     R ArgValue(size_t i) const;
     493                 :             :     //! Return positional index of a parameter using its name as key.
     494                 :             :     size_t GetParamIndex(std::string_view key) const;
     495                 :             : };
     496                 :             : 
     497                 :             : /**
     498                 :             :  * Push warning messages to an RPC "warnings" field as a JSON array of strings.
     499                 :             :  *
     500                 :             :  * @param[in] warnings  Warning messages to push.
     501                 :             :  * @param[out] obj      UniValue object to push the warnings array object to.
     502                 :             :  */
     503                 :             : void PushWarnings(const UniValue& warnings, UniValue& obj);
     504                 :             : void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
     505                 :             : 
     506                 :             : #endif // BITCOIN_RPC_UTIL_H
        

Generated by: LCOV version 2.0-1