Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2017-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_RPC_UTIL_H6#define BITCOIN_RPC_UTIL_H8#include <addresstype.h>9#include <consensus/amount.h>10#include <policy/feerate.h>11#include <pubkey.h>12#include <rpc/protocol.h>13#include <rpc/request.h>14#include <script/script.h>15#include <uint256.h>16#include <univalue.h>17#include <util/check.h>19#include <cstddef>20#include <cstdint>21#include <functional>22#include <map>23#include <optional>24#include <stdexcept>25#include <string>26#include <string_view>27#include <type_traits>28#include <utility>29#include <variant>30#include <vector>32enum class OutputType;33struct FlatSigningProvider;34struct bilingual_str;35class CBlockIndex;37namespace common {38enum class PSBTError;39} // namespace common40namespace node {41enum class TransactionError;42} // namespace node44inline constexpr bool DEFAULT_RPC_DOC_CHECK{45#ifdef RPC_DOC_CHECK46true47#else48false49#endif50};52/**53* String used to describe UNIX epoch time in documentation, factored out to a54* constant for consistency.55*/56extern const std::string UNIX_EPOCH_TIME;58/**59* Example bech32 addresses for the RPCExamples help documentation. They are intentionally60* invalid to prevent accidental transactions by users.61*/62extern const std::string EXAMPLE_ADDRESS[2];64struct Sections;66struct HelpResult : std::runtime_error {67explicit HelpResult(const std::string& msg) : std::runtime_error{msg} {}68};70/**71* Gets all existing output types formatted for RPC help sections.72*73* @return Comma separated string representing output type names.74*/75std::string GetAllOutputTypes();77/** Wrapper for UniValue::VType, which includes typeAny:78* Used to denote don't care type. */79struct UniValueType {80UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}81UniValueType() : typeAny(true) {}82bool typeAny;83UniValue::VType type;84};86/*87Check for expected keys/value types in an Object.88*/89void RPCTypeCheckObj(const UniValue& o,90const std::map<std::string, UniValueType>& typesExpected,91bool fAllowNull = false,92bool fStrict = false);94/**95* Utilities: convert hex-encoded Values96* (throws error if not hex).97*/98uint256 ParseHashV(const UniValue& v, std::string_view name);99uint256 ParseHashO(const UniValue& o, std::string_view strKey);100std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name);101std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey);103/**104* Parses verbosity from provided UniValue.105*106* @param[in] arg The verbosity argument as an int (0, 1, 2,...) or bool if allow_bool is set to true107* @param[in] default_verbosity The value to return if verbosity argument is null108* @param[in] allow_bool If true, allows arg to be a bool and parses it109* @returns An integer describing the verbosity level (e.g. 0, 1, 2, etc.)110* @throws JSONRPCError if allow_bool is false but arg provided is boolean111*/112int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool);114/**115* Validate and return a CAmount from a UniValue number or string.116*117* @param[in] value UniValue number or string to parse.118* @param[in] decimals Number of significant digits (default: 8).119* @returns a CAmount if the various checks pass.120*/121CAmount AmountFromValue(const UniValue& value, int decimals = 8);122/**123* Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).124* Reject negative values or rates larger than 1BTC/kvB.125*/126CFeeRate ParseFeeRate(const UniValue& json);128using RPCArgList = std::vector<std::pair<std::string, UniValue>>;129std::string HelpExampleCli(const std::string& methodname, const std::string& args);130std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);131std::string HelpExampleRpc(const std::string& methodname, const std::string& args);132std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);134CPubKey HexToPubKey(const std::string& hex_in);135CTxDestination AddAndGetMultisigDestination(int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);137UniValue DescribeAddress(const CTxDestination& dest);139/** Parse a sighash string representation and raise an RPC error if it is invalid. */140std::optional<int> ParseSighashString(const UniValue& sighash);142//! Parse a confirm target option and raise an RPC error if it is invalid.143unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);145RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr);146UniValue JSONRPCPSBTError(common::PSBTError err);147UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");149//! Parse a JSON range specified as int64, or [int64, int64]150std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);152/** Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range of 1000. */153std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, bool expand_priv = false);155//! Parse BIP32 path156std::vector<uint32_t> ParsePathBIP32(const std::string& path);158/**159* Serializing JSON objects depends on the outer type. Only arrays and160* dictionaries can be nested in json. The top-level outer type is "NONE".161*/162enum class OuterType {163ARR,164OBJ,165NONE, // Only set on first recursion166};168struct RPCArgOptions {169bool skip_type_check{false};170std::string oneline_description{}; //!< Should be empty unless it is supposed to override the auto-generated summary line171std::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.172bool placeholder{false}; //!< If set, the argument is retained only for compatibility and should generally be omitted.173bool hidden{false}; //!< For testing only174bool also_positional{false}; //!< If set allows a named-parameter field in an OBJ_NAMED_PARAM options object175//!< to have the same name as a top-level parameter. By default the RPC176//!< framework disallows this, because if an RPC request passes the value by177//!< name, it is assigned to top-level parameter position, not to the options178//!< position, defeating the purpose of using OBJ_NAMED_PARAMS instead OBJ for179//!< that option. But sometimes it makes sense to allow less-commonly used180//!< options to be passed by name only, and more commonly used options to be181//!< passed by name or position, so the RPC framework allows this as long as182//!< methods set the also_positional flag and read values from both positions.183};185// NOLINTNEXTLINE(misc-no-recursion)186struct RPCArg {187enum class Type {188OBJ,189ARR,190STR,191NUM,192BOOL,193OBJ_NAMED_PARAMS, //!< Special type that behaves almost exactly like194//!< OBJ, defining an options object with a list of195//!< pre-defined keys. The only difference between OBJ196//!< and OBJ_NAMED_PARAMS is that OBJ_NAMED_PARMS197//!< also allows the keys to be passed as top-level198//!< named parameters, as a more convenient way to pass199//!< options to the RPC method without nesting them.200OBJ_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 predefined201AMOUNT, //!< Special type representing a floating point amount (can be either NUM or STR)202STR_HEX, //!< Special type that is a STR with only hex chars203RANGE, //!< Special type that is a NUM or [NUM,NUM]204};206enum class Optional {207/** Required arg */208NO,209/**210* Optional argument for which the default value is omitted from211* help text for one of two reasons:212* - It's a named argument and has a default value of `null`.213* - Its default value is implicitly clear. That is, elements in an214* array may not exist by default.215* When possible, the default value should be specified.216*/217OMITTED,218};219/** Hint for default value */220using DefaultHint = std::string;221/** Default constant value */222using Default = UniValue;223using Fallback = std::variant<Optional, DefaultHint, Default>;225const 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)226const Type m_type;227const std::vector<RPCArg> m_inner; //!< Only used for arrays or dicts228const Fallback m_fallback;229const std::string m_description;230const RPCArgOptions m_opts;232RPCArg(233std::string name,234Type type,235Fallback fallback,236std::string description,237RPCArgOptions opts = {})238: m_names{std::move(name)},239m_type{type},240m_fallback{std::move(fallback)},241m_description{std::move(description)},242m_opts{std::move(opts)}243{244CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);245}247RPCArg(248std::string name,249Type type,250Fallback fallback,