Bitcoin Core 28.99.0
P2P Digital Currency
util.h
Go to the documentation of this file.
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
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);
135CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
136CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
137
139
141int ParseSighashString(const UniValue& sighash);
142
144unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
145
148UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
149
151std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
152
154std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false);
155
160enum class OuterType {
161 ARR,
162 OBJ,
163 NONE, // Only set on first recursion
164};
165
167 bool skip_type_check{false};
168 std::string oneline_description{};
169 std::vector<std::string> type_str{};
170 bool hidden{false};
171 bool also_positional{false};
180};
181
182// NOLINTNEXTLINE(misc-no-recursion)
183struct RPCArg {
184 enum class Type {
185 OBJ,
186 ARR,
187 STR,
188 NUM,
189 BOOL,
190 OBJ_NAMED_PARAMS,
197 OBJ_USER_KEYS,
198 AMOUNT,
199 STR_HEX,
200 RANGE,
201 };
202
203 enum class Optional {
205 NO,
214 OMITTED,
215 };
217 using DefaultHint = std::string;
220 using Fallback = std::variant<Optional, DefaultHint, Default>;
221
222 const std::string m_names;
224 const std::vector<RPCArg> m_inner;
226 const std::string m_description;
228
230 std::string name,
231 Type type,
232 Fallback fallback,
233 std::string description,
234 RPCArgOptions opts = {})
235 : m_names{std::move(name)},
236 m_type{std::move(type)},
237 m_fallback{std::move(fallback)},
238 m_description{std::move(description)},
239 m_opts{std::move(opts)}
240 {
241 CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
242 }
243
245 std::string name,
246 Type type,
247 Fallback fallback,
248 std::string description,
249 std::vector<RPCArg> inner,
250 RPCArgOptions opts = {})
251 : m_names{std::move(name)},
252 m_type{std::move(type)},
253 m_inner{std::move(inner)},
254 m_fallback{std::move(fallback)},
255 m_description{std::move(description)},
256 m_opts{std::move(opts)}
257 {
258 CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
259 }
260
261 bool IsOptional() const;
262
267 UniValue MatchesType(const UniValue& request) const;
268
270 std::string GetFirstName() const;
271
273 std::string GetName() const;
274
279 std::string ToString(bool oneline) const;
284 std::string ToStringObj(bool oneline) const;
289 std::string ToDescriptionString(bool is_named_arg) const;
290};
291
292// NOLINTNEXTLINE(misc-no-recursion)
293struct RPCResult {
294 enum class Type {
295 OBJ,
296 ARR,
297 STR,
298 NUM,
299 BOOL,
300 NONE,
301 ANY,
302 STR_AMOUNT,
303 STR_HEX,
304 OBJ_DYN,
305 ARR_FIXED,
306 NUM_TIME,
307 ELISION,
308 };
309
311 const std::string m_key_name;
312 const std::vector<RPCResult> m_inner;
313 const bool m_optional;
315 const std::string m_description;
316 const std::string m_cond;
317
319 std::string cond,
320 Type type,
321 std::string m_key_name,
322 bool optional,
323 std::string description,
324 std::vector<RPCResult> inner = {})
325 : m_type{std::move(type)},
326 m_key_name{std::move(m_key_name)},
327 m_inner{std::move(inner)},
328 m_optional{optional},
329 m_skip_type_check{false},
330 m_description{std::move(description)},
331 m_cond{std::move(cond)}
332 {
333 CHECK_NONFATAL(!m_cond.empty());
335 }
336
338 std::string cond,
339 Type type,
340 std::string m_key_name,
341 std::string description,
342 std::vector<RPCResult> inner = {})
343 : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
344
346 Type type,
347 std::string m_key_name,
348 bool optional,
349 std::string description,
350 std::vector<RPCResult> inner = {},
351 bool skip_type_check = false)
352 : m_type{std::move(type)},
353 m_key_name{std::move(m_key_name)},
354 m_inner{std::move(inner)},
355 m_optional{optional},
356 m_skip_type_check{skip_type_check},
357 m_description{std::move(description)},
358 m_cond{}
359 {
361 }
362
364 Type type,
365 std::string m_key_name,
366 std::string description,
367 std::vector<RPCResult> inner = {},
368 bool skip_type_check = false)
369 : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
370
372 void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
374 std::string ToStringObj() const;
376 std::string ToDescriptionString() const;
380 UniValue MatchesType(const UniValue& result) const;
381
382private:
383 void CheckInnerDoc() const;
384};
385
387 const std::vector<RPCResult> m_results;
388
390 : m_results{{result}}
391 {
392 }
393
394 RPCResults(std::initializer_list<RPCResult> results)
395 : m_results{results}
396 {
397 }
398
402 std::string ToDescriptionString() const;
403};
404
406 const std::string m_examples;
407 explicit RPCExamples(
408 std::string examples)
409 : m_examples(std::move(examples))
410 {
411 }
412 std::string ToDescriptionString() const;
413};
414
416{
417public:
418 RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
419 using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
420 RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
421
422 UniValue HandleRequest(const JSONRPCRequest& request) const;
440 template <typename R>
441 auto Arg(std::string_view key) const
442 {
443 auto i{GetParamIndex(key)};
444 // Return argument (required or with default value).
445 if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
446 // Return numbers by value.
447 return ArgValue<R>(i);
448 } else {
449 // Return everything else by reference.
450 return ArgValue<const R&>(i);
451 }
452 }
472 template <typename R>
473 auto MaybeArg(std::string_view key) const
474 {
475 auto i{GetParamIndex(key)};
476 // Return optional argument (without default).
477 if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
478 // Return numbers by value, wrapped in optional.
479 return ArgValue<std::optional<R>>(i);
480 } else {
481 // Return other types by pointer.
482 return ArgValue<const R*>(i);
483 }
484 }
485 std::string ToString() const;
487 UniValue GetArgMap() const;
489 bool IsValidNumArgs(size_t num_args) const;
491 std::vector<std::pair<std::string, bool>> GetArgNames() const;
492
493 const std::string m_name;
494
495private:
497 const std::string m_description;
498 const std::vector<RPCArg> m_args;
501 mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
502 template <typename R>
503 R ArgValue(size_t i) const;
505 size_t GetParamIndex(std::string_view key) const;
506};
507
514void PushWarnings(const UniValue& warnings, UniValue& obj);
515void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
516
517std::vector<RPCResult> ScriptPubKeyDoc();
518
519#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:140
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:81
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:419
const RPCExamples m_examples
Definition: util.h:500
size_t GetParamIndex(std::string_view key) const
Return positional index of a parameter using its name as key.
Definition: util.cpp:782
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:567
const std::string m_description
Definition: util.h:497
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:755
const RPCMethodImpl m_fun
Definition: util.h:496
const std::string m_name
Definition: util.h:493
const RPCResults m_results
Definition: util.h:499
const std::vector< RPCArg > m_args
Definition: util.h:498
std::string ToString() const
Definition: util.cpp:792
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:854
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:441
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:767
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:473
const JSONRPCRequest * m_req
Definition: util.h:501
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:657
256-bit opaque blob.
Definition: uint256.h:190
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:20
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:1345
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:1329
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
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:208
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:131
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:1399
int ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:379
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:140
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:111
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:160
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:202
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:99
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:44
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:57
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:47
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:84
UniValue JSONRPCPSBTError(common::PSBTError err)
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:220
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:45
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:257
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:127
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:391
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:189
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:118
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:236
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:369
std::vector< RPCResult > ScriptPubKeyDoc()
Definition: util.cpp:1411
#define STR(x)
Definition: util.h:24
Definition: util.h:183
Type
Definition: util.h:184
@ 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:224
const RPCArgOptions m_opts
Definition: util.h:227
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:222
const Fallback m_fallback
Definition: util.h:225
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1270
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:229
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:920
const std::string m_description
Definition: util.h:226
std::string DefaultHint
Hint for default value.
Definition: util.h:217
bool IsOptional() const
Definition: util.cpp:944
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:220
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:953
const Type m_type
Definition: util.h:223
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:244
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:938
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:933
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1231
Optional
Definition: util.h:203
bool hidden
For testing only.
Definition: util.h:170
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:169
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:168
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:171
bool skip_type_check
Definition: util.h:167
std::string ToDescriptionString() const
Definition: util.cpp:652
RPCExamples(std::string examples)
Definition: util.h:407
const std::string m_examples
Definition: util.h:406
const std::string m_description
Definition: util.h:315
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:1018
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:312
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:345
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:363
const std::string m_cond
Definition: util.h:316
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1152
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:1219
const bool m_optional
Definition: util.h:313
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:337
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:318
const std::string m_key_name
Only used for dicts.
Definition: util.h:311
const Type m_type
Definition: util.h:310
const bool m_skip_type_check
Definition: util.h:314
RPCResults(RPCResult result)
Definition: util.h:389
const std::vector< RPCResult > m_results
Definition: util.h:387
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:394
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:454
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:21
#define NUM
Definition: tests.c:3597