Bitcoin Core 31.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
70struct HelpResult : std::runtime_error {
71 explicit HelpResult(const std::string& msg) : std::runtime_error{msg} {}
72};
73
79std::string GetAllOutputTypes();
80
84 UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
85 UniValueType() : typeAny(true) {}
86 bool typeAny;
88};
89
90/*
91 Check for expected keys/value types in an Object.
92*/
93void RPCTypeCheckObj(const UniValue& o,
94 const std::map<std::string, UniValueType>& typesExpected,
95 bool fAllowNull = false,
96 bool fStrict = false);
97
102uint256 ParseHashV(const UniValue& v, std::string_view name);
103uint256 ParseHashO(const UniValue& o, std::string_view strKey);
104std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name);
105std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey);
106
116int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool);
117
125CAmount AmountFromValue(const UniValue& value, int decimals = 8);
131
132using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
133std::string HelpExampleCli(const std::string& methodname, const std::string& args);
134std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
135std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
136std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
137
138CPubKey HexToPubKey(const std::string& hex_in);
139CTxDestination AddAndGetMultisigDestination(int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
140
142
144std::optional<int> ParseSighashString(const UniValue& sighash);
145
147unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
148
151UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
152
154std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
155
157std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, bool expand_priv = false);
158
163enum class OuterType {
164 ARR,
165 OBJ,
166 NONE, // Only set on first recursion
167};
168
170 bool skip_type_check{false};
171 std::string oneline_description{};
172 std::vector<std::string> type_str{};
173 bool hidden{false};
174 bool also_positional{false};
183};
184
185// NOLINTNEXTLINE(misc-no-recursion)
186struct RPCArg {
187 enum class Type {
188 OBJ,
189 ARR,
190 STR,
191 NUM,
192 BOOL,
193 OBJ_NAMED_PARAMS,
200 OBJ_USER_KEYS,
201 AMOUNT,
202 STR_HEX,
203 RANGE,
204 };
205
206 enum class Optional {
208 NO,
217 OMITTED,
218 };
220 using DefaultHint = std::string;
223 using Fallback = std::variant<Optional, DefaultHint, Default>;
224
225 const std::string m_names;
227 const std::vector<RPCArg> m_inner;
229 const std::string m_description;
231
233 std::string name,
234 Type type,
235 Fallback fallback,
236 std::string description,
237 RPCArgOptions opts = {})
238 : m_names{std::move(name)},
239 m_type{std::move(type)},
240 m_fallback{std::move(fallback)},
241 m_description{std::move(description)},
242 m_opts{std::move(opts)}
243 {
244 CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
245 }
246
248 std::string name,
249 Type type,
250 Fallback fallback,
251 std::string description,
252 std::vector<RPCArg> inner,
253 RPCArgOptions opts = {})
254 : m_names{std::move(name)},
255 m_type{std::move(type)},
256 m_inner{std::move(inner)},
257 m_fallback{std::move(fallback)},
258 m_description{std::move(description)},
259 m_opts{std::move(opts)}
260 {
261 CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
262 }
263
264 bool IsOptional() const;
265
270 UniValue MatchesType(const UniValue& request) const;
271
273 std::string GetFirstName() const;
274
276 std::string GetName() const;
277
282 std::string ToString(bool oneline) const;
287 std::string ToStringObj(bool oneline) const;
292 std::string ToDescriptionString(bool is_named_arg) const;
293};
294
299using HelpElision = std::variant<HelpElisionNone, HelpElisionSkip, std::string>;
300
302 bool skip_type_check{false};
304};
305
306// NOLINTNEXTLINE(misc-no-recursion)
307struct RPCResult {
308 enum class Type {
309 OBJ,
310 ARR,
311 STR,
312 NUM,
313 BOOL,
314 NONE,
315 ANY,
316 STR_AMOUNT,
317 STR_HEX,
318 OBJ_DYN,
319 ARR_FIXED,
320 NUM_TIME,
321 };
322
324 const std::string m_key_name;
325 const std::vector<RPCResult> m_inner;
326 const bool m_optional;
328 const std::string m_description;
329 const std::string m_cond;
330
332 std::string cond,
333 Type type,
334 std::string m_key_name,
335 bool optional,
336 std::string description,
337 std::vector<RPCResult> inner = {},
338 RPCResultOptions opts = {})
339 : m_type{std::move(type)},
340 m_key_name{std::move(m_key_name)},
341 m_inner{std::move(inner)},
342 m_optional{optional},
343 m_opts{std::move(opts)},
344 m_description{std::move(description)},
345 m_cond{std::move(cond)}
346 {
347 CHECK_NONFATAL(!m_cond.empty());
349 }
350
352 std::string cond,
353 Type type,
354 std::string m_key_name,
355 std::string description,
356 std::vector<RPCResult> inner = {},
357 RPCResultOptions opts = {})
358 : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
359
361 Type type,
362 std::string m_key_name,
363 bool optional,
364 std::string description,
365 std::vector<RPCResult> inner = {},
366 RPCResultOptions opts = {})
367 : m_type{std::move(type)},
368 m_key_name{std::move(m_key_name)},
369 m_inner{std::move(inner)},
370 m_optional{optional},
371 m_opts{std::move(opts)},
372 m_description{std::move(description)},
373 m_cond{}
374 {
376 }
377
379 Type type,
380 std::string m_key_name,
381 std::string description,
382 std::vector<RPCResult> inner = {},
383 RPCResultOptions opts = {})
384 : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), std::move(opts)} {}
385
388 : m_type{other.m_type},
389 m_key_name{other.m_key_name},
390 m_inner{other.m_inner},
391 m_optional{other.m_optional},
392 m_opts{std::move(opts)},
394 m_cond{other.m_cond} {}
395
397 void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, int current_indent = 0) const;
399 std::string ToStringObj() const;
401 std::string ToDescriptionString() const;
405 UniValue MatchesType(const UniValue& result) const;
406
407private:
408 void CheckInnerDoc() const;
409};
410
413std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary = "");
414
416 const std::vector<RPCResult> m_results;
417
419 : m_results{{result}}
420 {
421 }
422
423 RPCResults(std::initializer_list<RPCResult> results)
424 : m_results{results}
425 {
426 }
427
431 std::string ToDescriptionString() const;
432};
433
435 const std::string m_examples;
436 explicit RPCExamples(
437 std::string examples)
438 : m_examples(std::move(examples))
439 {
440 }
441 std::string ToDescriptionString() const;
442};
443
445{
446public:
447 RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
448 using RPCMethodImpl = std::function<UniValue(const RPCMethod&, const JSONRPCRequest&)>;
449 RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
450
451 UniValue HandleRequest(const JSONRPCRequest& request) const;
469 template <typename R>
470 auto Arg(std::string_view key) const
471 {
472 auto i{GetParamIndex(key)};
473 // Return argument (required or with default value).
474 if constexpr (std::is_trivially_copyable_v<R>) {
475 // Return trivially copyable types by value.
476 return ArgValue<R>(i);
477 } else {
478 // Return everything else by reference.
479 return ArgValue<const R&>(i);
480 }
481 }
501 template <typename R>
502 auto MaybeArg(std::string_view key) const
503 {
504 auto i{GetParamIndex(key)};
505 // Return optional argument (without default).
506 if constexpr (std::is_trivially_copyable_v<R>) {
507 // Return trivially copyable types by value, wrapped in optional.
508 return ArgValue<std::optional<R>>(i);
509 } else {
510 // Return other types by pointer.
511 return ArgValue<const R*>(i);
512 }
513 }
514 std::string ToString() const;
516 UniValue GetArgMap() const;
518 bool IsValidNumArgs(size_t num_args) const;
520 std::vector<std::pair<std::string, bool>> GetArgNames() const;
521
522 const std::string m_name;
523
524private:
526 const std::string m_description;
527 const std::vector<RPCArg> m_args;
530 mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
531 template <typename R>
532 R ArgValue(size_t i) const;
534 size_t GetParamIndex(std::string_view key) const;
535};
536
543void PushWarnings(const UniValue& warnings, UniValue& obj);
544void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
545
546std::vector<RPCResult> ScriptPubKeyDoc();
547
548/***
549 * Get the target for a given block index.
550 *
551 * @param[in] blockindex the block
552 * @param[in] pow_limit PoW limit (consensus parameter)
553 *
554 * @return the target
555 */
556uint256 GetTarget(const CBlockIndex& blockindex, uint256 pow_limit);
557
558#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:280
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
An encapsulated public key.
Definition: pubkey.h:32
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
Fillable signing provider that keeps keys in an address->secret map.
const RPCExamples m_examples
Definition: util.h:529
const std::string m_name
Definition: util.h:522
const std::string m_description
Definition: util.h:526
R ArgValue(size_t i) const
const JSONRPCRequest * m_req
Definition: util.h:530
std::function< UniValue(const RPCMethod &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:448
RPCMethod(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:547
const RPCMethodImpl m_fun
Definition: util.h:525
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:735
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:502
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:747
const RPCResults m_results
Definition: util.h:528
const std::vector< RPCArg > m_args
Definition: util.h:527
size_t GetParamIndex(std::string_view key) const
Return positional index of a parameter using its name as key.
Definition: util.cpp:762
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:637
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:835
std::string ToString() const
Definition: util.cpp:772
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:470
256-bit opaque blob.
Definition: uint256.h:196
char const * json() noexcept
Template to generate JSON data.
Definition: init.cpp:17
PSBTError
Definition: types.h:19
Definition: messages.h:21
TransactionError
Definition: types.h:19
OutputType
Definition: outputtype.h:18
ServiceFlags
nServices flags
Definition: protocol.h:321
const char * name
Definition: rest.cpp:50
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:48
RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr)
CTxDestination AddAndGetMultisigDestination(int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:235
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1320
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:183
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:132
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:207
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider, bool expand_priv=false)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:1336
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:130
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:1390
uint256 GetTarget(const CBlockIndex &blockindex, uint256 pow_limit)
Definition: util.cpp:1413
std::vector< RPCResult > ElideGroup(std::vector< RPCResult > fields, std::string summary="")
Stamp elision onto an entire vector of RPCResult fields at once.
Definition: util.cpp:1419
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:139
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:110
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:163
std::variant< HelpElisionNone, HelpElisionSkip, std::string > HelpElision
Definition: util.h:299
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:201
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:98
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:43
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:56
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:46
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:83
UniValue JSONRPCPSBTError(common::PSBTError err)
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:219
std::optional< int > ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:357
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:44
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:126
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:369
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:188
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:117
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:347
std::vector< RPCResult > ScriptPubKeyDoc()
Definition: util.cpp:1402
#define STR(x)
Definition: util.h:24
Controls how an RPCResult is rendered in human-readable help text.field printed normally.
Definition: util.h:297
field hidden from help
Definition: util.h:298
HelpResult(const std::string &msg)
Definition: util.h:71
Definition: util.h:186
Type
Definition: util.h:187
@ 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:227
const RPCArgOptions m_opts
Definition: util.h:230
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:225
const Fallback m_fallback
Definition: util.h:228
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1261
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:232
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:901
const std::string m_description
Definition: util.h:229
std::string DefaultHint
Hint for default value.
Definition: util.h:220
bool IsOptional() const
Definition: util.cpp:925
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:223
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:934
const Type m_type
Definition: util.h:226
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:247
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:919
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:914
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1222
Optional
Definition: util.h:206
bool hidden
For testing only.
Definition: util.h:173
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:172
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:171
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:174
bool skip_type_check
Definition: util.h:170
std::string ToDescriptionString() const
Definition: util.cpp:632
RPCExamples(std::string examples)
Definition: util.h:436
const std::string m_examples
Definition: util.h:435
const std::string m_description
Definition: util.h:328
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:999
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:325
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={}, RPCResultOptions opts={})
Definition: util.h:331
RPCResult(Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={}, RPCResultOptions opts={})
Definition: util.h:360
const std::string m_cond
Definition: util.h:329
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1144
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).
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, RPCResultOptions opts={})
Definition: util.h:378
void CheckInnerDoc() const
Definition: util.cpp:1210
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, RPCResultOptions opts={})
Definition: util.h:351
RPCResult(const RPCResult &other, RPCResultOptions opts)
Copy with replacement options, for stamping new opts onto an existing result.
Definition: util.h:387
const bool m_optional
Definition: util.h:326
const RPCResultOptions m_opts
Definition: util.h:327
const std::string m_key_name
Only used for dicts.
Definition: util.h:324
const Type m_type
Definition: util.h:323
bool skip_type_check
Definition: util.h:302
HelpElision print_elision
Definition: util.h:303
RPCResults(RPCResult result)
Definition: util.h:418
const std::vector< RPCResult > m_results
Definition: util.h:416
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:423
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:434
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:83
bool typeAny
Definition: util.h:86
UniValueType(UniValue::VType _type)
Definition: util.h:84
UniValue::VType type
Definition: util.h:87
UniValueType()
Definition: util.h:85
Bilingual messages:
Definition: translation.h:24
FuzzedDataProvider provider
Definition: dbwrapper.cpp:367
#define NUM
Definition: tests.c:3811