Bitcoin Core 29.99.0
P2P Digital Currency
util.h
Go to the documentation of this file.
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
34class JSONRPCRequest;
35enum ServiceFlags : uint64_t;
36enum class OutputType;
38struct bilingual_str;
39namespace common {
40enum class PSBTError;
41} // namespace common
42namespace node {
43enum class TransactionError;
44} // namespace node
45
46static constexpr bool DEFAULT_RPC_DOC_CHECK{
47#ifdef RPC_DOC_CHECK
48 true
49#else
50 false
51#endif
52};
53
58extern const std::string UNIX_EPOCH_TIME;
59
64extern const std::string EXAMPLE_ADDRESS[2];
65
67class CScript;
68struct Sections;
69
75std::string GetAllOutputTypes();
76
80 UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
81 UniValueType() : typeAny(true) {}
82 bool typeAny;
84};
85
86/*
87 Check for expected keys/value types in an Object.
88*/
89void RPCTypeCheckObj(const UniValue& o,
90 const std::map<std::string, UniValueType>& typesExpected,
91 bool fAllowNull = false,
92 bool fStrict = false);
93
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);
102
112int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool);
113
121CAmount AmountFromValue(const UniValue& value, int decimals = 8);
127
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);
133
134CPubKey HexToPubKey(const std::string& hex_in);
135CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
136
138
140std::optional<int> ParseSighashString(const UniValue& sighash);
141
143unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
144
147UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
148
150std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
151
153std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false);
154
159enum class OuterType {
160 ARR,
161 OBJ,
162 NONE, // Only set on first recursion
163};
164
166 bool skip_type_check{false};
167 std::string oneline_description{};
168 std::vector<std::string> type_str{};
169 bool hidden{false};
170 bool also_positional{false};
179};
180
181// NOLINTNEXTLINE(misc-no-recursion)
182struct RPCArg {
183 enum class Type {
184 OBJ,
185 ARR,
186 STR,
187 NUM,
188 BOOL,
189 OBJ_NAMED_PARAMS,
196 OBJ_USER_KEYS,
197 AMOUNT,
198 STR_HEX,
199 RANGE,
200 };
201
202 enum class Optional {
204 NO,
213 OMITTED,
214 };
216 using DefaultHint = std::string;
219 using Fallback = std::variant<Optional, DefaultHint, Default>;
220
221 const std::string m_names;
223 const std::vector<RPCArg> m_inner;
225 const std::string m_description;
227
229 std::string name,
230 Type type,
231 Fallback fallback,
232 std::string description,
233 RPCArgOptions opts = {})
234 : m_names{std::move(name)},
235 m_type{std::move(type)},
236 m_fallback{std::move(fallback)},
237 m_description{std::move(description)},
238 m_opts{std::move(opts)}
239 {
240 CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
241 }
242
244 std::string name,
245 Type type,
246 Fallback fallback,
247 std::string description,
248 std::vector<RPCArg> inner,
249 RPCArgOptions opts = {})
250 : m_names{std::move(name)},
251 m_type{std::move(type)},
252 m_inner{std::move(inner)},
253 m_fallback{std::move(fallback)},
254 m_description{std::move(description)},
255 m_opts{std::move(opts)}
256 {
257 CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
258 }
259
260 bool IsOptional() const;
261
266 UniValue MatchesType(const UniValue& request) const;
267
269 std::string GetFirstName() const;
270
272 std::string GetName() const;
273
278 std::string ToString(bool oneline) const;
283 std::string ToStringObj(bool oneline) const;
288 std::string ToDescriptionString(bool is_named_arg) const;
289};
290
291// NOLINTNEXTLINE(misc-no-recursion)
292struct RPCResult {
293 enum class Type {
294 OBJ,
295 ARR,
296 STR,
297 NUM,
298 BOOL,
299 NONE,
300 ANY,
301 STR_AMOUNT,
302 STR_HEX,
303 OBJ_DYN,
304 ARR_FIXED,
305 NUM_TIME,
306 ELISION,
307 };
308
310 const std::string m_key_name;
311 const std::vector<RPCResult> m_inner;
312 const bool m_optional;
314 const std::string m_description;
315 const std::string m_cond;
316
318 std::string cond,
319 Type type,
320 std::string m_key_name,
321 bool optional,
322 std::string description,
323 std::vector<RPCResult> inner = {})
324 : m_type{std::move(type)},
325 m_key_name{std::move(m_key_name)},
326 m_inner{std::move(inner)},
327 m_optional{optional},
328 m_skip_type_check{false},
329 m_description{std::move(description)},
330 m_cond{std::move(cond)}
331 {
332 CHECK_NONFATAL(!m_cond.empty());
334 }
335
337 std::string cond,
338 Type type,
339 std::string m_key_name,
340 std::string description,
341 std::vector<RPCResult> inner = {})
342 : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
343
345 Type type,
346 std::string m_key_name,
347 bool optional,
348 std::string description,
349 std::vector<RPCResult> inner = {},
350 bool skip_type_check = false)
351 : m_type{std::move(type)},
352 m_key_name{std::move(m_key_name)},
353 m_inner{std::move(inner)},
354 m_optional{optional},
355 m_skip_type_check{skip_type_check},
356 m_description{std::move(description)},
357 m_cond{}
358 {
360 }
361
363 Type type,
364 std::string m_key_name,
365 std::string description,
366 std::vector<RPCResult> inner = {},
367 bool skip_type_check = false)
368 : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
369
371 void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
373 std::string ToStringObj() const;
375 std::string ToDescriptionString() const;
379 UniValue MatchesType(const UniValue& result) const;
380
381private:
382 void CheckInnerDoc() const;
383};
384
386 const std::vector<RPCResult> m_results;
387
389 : m_results{{result}}
390 {
391 }
392
393 RPCResults(std::initializer_list<RPCResult> results)
394 : m_results{results}
395 {
396 }
397
401 std::string ToDescriptionString() const;
402};
403
405 const std::string m_examples;
406 explicit RPCExamples(
407 std::string examples)
408 : m_examples(std::move(examples))
409 {
410 }
411 std::string ToDescriptionString() const;
412};
413
415{
416public:
417 RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
418 using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
419 RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
420
421 UniValue HandleRequest(const JSONRPCRequest& request) const;
439 template <typename R>
440 auto Arg(std::string_view key) const
441 {
442 auto i{GetParamIndex(key)};
443 // Return argument (required or with default value).
444 if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
445 // Return numbers by value.
446 return ArgValue<R>(i);
447 } else {
448 // Return everything else by reference.
449 return ArgValue<const R&>(i);
450 }
451 }
471 template <typename R>
472 auto MaybeArg(std::string_view key) const
473 {
474 auto i{GetParamIndex(key)};
475 // Return optional argument (without default).
476 if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
477 // Return numbers by value, wrapped in optional.
478 return ArgValue<std::optional<R>>(i);
479 } else {
480 // Return other types by pointer.
481 return ArgValue<const R*>(i);
482 }
483 }
484 std::string ToString() const;
486 UniValue GetArgMap() const;
488 bool IsValidNumArgs(size_t num_args) const;
490 std::vector<std::pair<std::string, bool>> GetArgNames() const;
491
492 const std::string m_name;
493
494private:
496 const std::string m_description;
497 const std::vector<RPCArg> m_args;
500 mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
501 template <typename R>
502 R ArgValue(size_t i) const;
504 size_t GetParamIndex(std::string_view key) const;
505};
506
513void PushWarnings(const UniValue& warnings, UniValue& obj);
514void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
515
516std::vector<RPCResult> ScriptPubKeyDoc();
517
518/***
519 * Get the target for a given block index.
520 *
521 * @param[in] blockindex the block
522 * @param[in] pow_limit PoW limit (consensus parameter)
523 *
524 * @return the target
525 */
526uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit);
527
528#endif // BITCOIN_RPC_UTIL_H
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager & args
Definition: bitcoind.cpp:277
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:102
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
An encapsulated public key.
Definition: pubkey.h:34
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
Fillable signing provider that keeps keys in an address->secret map.
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:418
const RPCExamples m_examples
Definition: util.h:499
size_t GetParamIndex(std::string_view key) const
Return positional index of a parameter using its name as key.
Definition: util.cpp:763
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:548
const std::string m_description
Definition: util.h:496
R ArgValue(size_t i) const
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:736
const RPCMethodImpl m_fun
Definition: util.h:495
const std::string m_name
Definition: util.h:492
const RPCResults m_results
Definition: util.h:498
const std::vector< RPCArg > m_args
Definition: util.h:497
std::string ToString() const
Definition: util.cpp:773
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:836
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:440
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:748
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:472
const JSONRPCRequest * m_req
Definition: util.h:500
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:638
256-bit opaque blob.
Definition: uint256.h:196
char const * json() noexcept
Template to generate JSON data.
Definition: args.cpp:868
PSBTError
Definition: types.h:17
Definition: messages.h:20
TransactionError
Definition: types.h:23
OutputType
Definition: outputtype.h:17
ServiceFlags
nServices flags
Definition: protocol.h:309
const char * name
Definition: rest.cpp:49
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:25
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider, const bool expand_priv=false)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:1327
RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr)
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1311
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:186
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:128
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:210
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:133
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:46
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1381
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:142
uint256 GetTarget(const CBlockIndex &blockindex, const uint256 pow_limit)
Definition: util.cpp:1404
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:113
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:159
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:204
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:101
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:46
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:59
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:49
UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string &err_string="")
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
Definition: util.cpp:86
UniValue JSONRPCPSBTError(common::PSBTError err)
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:222
std::optional< int > ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:360
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:47
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:238
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:129
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
Definition: util.cpp:372
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:191
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:120
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:350
std::vector< RPCResult > ScriptPubKeyDoc()
Definition: util.cpp:1393
#define STR(x)
Definition: util.h:24
Definition: util.h:182
Type
Definition: util.h:183
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:223
const RPCArgOptions m_opts
Definition: util.h:226
const std::string m_names
The name of the arg (can be empty for inner args, can contain multiple aliases separated by | for nam...
Definition: util.h:221
const Fallback m_fallback
Definition: util.h:224
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1252
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:228
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:902
const std::string m_description
Definition: util.h:225
std::string DefaultHint
Hint for default value.
Definition: util.h:216
bool IsOptional() const
Definition: util.cpp:926
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:219
std::string ToDescriptionString(bool is_named_arg) const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:935
const Type m_type
Definition: util.h:222
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:243
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:920
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:915
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1213
Optional
Definition: util.h:202
bool hidden
For testing only.
Definition: util.h:169
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:168
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:167
bool also_positional
If set allows a named-parameter field in an OBJ_NAMED_PARAM options object to have the same name as a...
Definition: util.h:170
bool skip_type_check
Definition: util.h:166
std::string ToDescriptionString() const
Definition: util.cpp:633
RPCExamples(std::string examples)
Definition: util.h:406
const std::string m_examples
Definition: util.h:405
const std::string m_description
Definition: util.h:314
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:1000
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:311
RPCResult(Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:344
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:362
const std::string m_cond
Definition: util.h:315
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1134
std::string ToDescriptionString() const
Return the description string, including the result type.
std::string ToStringObj() const
Return the type string of the result when it is in an object (dict).
void CheckInnerDoc() const
Definition: util.cpp:1201
const bool m_optional
Definition: util.h:312
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:336
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:317
const std::string m_key_name
Only used for dicts.
Definition: util.h:310
const Type m_type
Definition: util.h:309
const bool m_skip_type_check
Definition: util.h:313
RPCResults(RPCResult result)
Definition: util.h:388
const std::vector< RPCResult > m_results
Definition: util.h:386
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:393
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:435
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:79
bool typeAny
Definition: util.h:82
UniValueType(UniValue::VType _type)
Definition: util.h:80
UniValue::VType type
Definition: util.h:83
UniValueType()
Definition: util.h:81
Bilingual messages:
Definition: translation.h:24
#define NUM
Definition: tests.c:3588