Bitcoin Core  27.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 
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 
58 extern const std::string UNIX_EPOCH_TIME;
59 
64 extern const std::string EXAMPLE_ADDRESS[2];
65 
67 class CScript;
68 struct Sections;
69 
75 std::string GetAllOutputTypes();
76 
79 struct UniValueType {
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 */
89 void RPCTypeCheckObj(const UniValue& o,
90  const std::map<std::string, UniValueType>& typesExpected,
91  bool fAllowNull = false,
92  bool fStrict = false);
93 
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 
110 CAmount AmountFromValue(const UniValue& value, int decimals = 8);
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 
128 
130 int ParseSighashString(const UniValue& sighash);
131 
133 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
134 
137 UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string& err_string = "");
138 
140 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
141 
143 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false);
144 
149 enum class OuterType {
150  ARR,
151  OBJ,
152  NONE, // Only set on first recursion
153 };
154 
156  bool skip_type_check{false};
157  std::string oneline_description{};
158  std::vector<std::string> type_str{};
159  bool hidden{false};
160  bool also_positional{false};
169 };
170 
171 // NOLINTNEXTLINE(misc-no-recursion)
172 struct RPCArg {
173  enum class Type {
174  OBJ,
175  ARR,
176  STR,
177  NUM,
178  BOOL,
186  OBJ_USER_KEYS,
187  AMOUNT,
188  STR_HEX,
189  RANGE,
190  };
191 
192  enum class Optional {
194  NO,
203  OMITTED,
204  };
206  using DefaultHint = std::string;
208  using Default = UniValue;
209  using Fallback = std::variant<Optional, DefaultHint, Default>;
210 
211  const std::string m_names;
212  const Type m_type;
213  const std::vector<RPCArg> m_inner;
215  const std::string m_description;
217 
219  std::string name,
220  Type type,
221  Fallback fallback,
222  std::string description,
223  RPCArgOptions opts = {})
224  : m_names{std::move(name)},
225  m_type{std::move(type)},
226  m_fallback{std::move(fallback)},
227  m_description{std::move(description)},
228  m_opts{std::move(opts)}
229  {
230  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
231  }
232 
234  std::string name,
235  Type type,
236  Fallback fallback,
237  std::string description,
238  std::vector<RPCArg> inner,
239  RPCArgOptions opts = {})
240  : m_names{std::move(name)},
241  m_type{std::move(type)},
242  m_inner{std::move(inner)},
243  m_fallback{std::move(fallback)},
244  m_description{std::move(description)},
245  m_opts{std::move(opts)}
246  {
247  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_NAMED_PARAMS || type == Type::OBJ_USER_KEYS);
248  }
249 
250  bool IsOptional() const;
251 
256  UniValue MatchesType(const UniValue& request) const;
257 
259  std::string GetFirstName() const;
260 
262  std::string GetName() const;
263 
268  std::string ToString(bool oneline) const;
273  std::string ToStringObj(bool oneline) const;
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,
291  STR_AMOUNT,
292  STR_HEX,
293  OBJ_DYN,
294  ARR_FIXED,
295  NUM_TIME,
296  ELISION,
297  };
298 
299  const Type m_type;
300  const std::string m_key_name;
301  const std::vector<RPCResult> m_inner;
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 
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  : m_type{std::move(type)},
315  m_key_name{std::move(m_key_name)},
316  m_inner{std::move(inner)},
317  m_optional{optional},
318  m_skip_type_check{false},
319  m_description{std::move(description)},
320  m_cond{std::move(cond)}
321  {
322  CHECK_NONFATAL(!m_cond.empty());
323  CheckInnerDoc();
324  }
325 
327  std::string cond,
328  Type type,
329  std::string m_key_name,
330  std::string description,
331  std::vector<RPCResult> inner = {})
332  : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
333 
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  : m_type{std::move(type)},
342  m_key_name{std::move(m_key_name)},
343  m_inner{std::move(inner)},
344  m_optional{optional},
345  m_skip_type_check{skip_type_check},
346  m_description{std::move(description)},
347  m_cond{}
348  {
349  CheckInnerDoc();
350  }
351 
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  : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
359 
361  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
363  std::string ToStringObj() const;
365  std::string ToDescriptionString() const;
369  UniValue MatchesType(const UniValue& result) const;
370 
371 private:
372  void CheckInnerDoc() const;
373 };
374 
375 struct RPCResults {
376  const std::vector<RPCResult> m_results;
377 
379  : m_results{{result}}
380  {
381  }
382 
383  RPCResults(std::initializer_list<RPCResult> results)
384  : m_results{results}
385  {
386  }
387 
391  std::string ToDescriptionString() const;
392 };
393 
394 struct RPCExamples {
395  const std::string m_examples;
396  explicit RPCExamples(
397  std::string examples)
398  : m_examples(std::move(examples))
399  {
400  }
401  std::string ToDescriptionString() const;
402 };
403 
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;
429  template <typename R>
430  auto Arg(std::string_view key) const
431  {
432  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  return ArgValue<R>(i);
437  } else {
438  // Return everything else by reference.
439  return ArgValue<const R&>(i);
440  }
441  }
461  template <typename R>
462  auto MaybeArg(std::string_view key) const
463  {
464  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  return ArgValue<std::optional<R>>(i);
469  } else {
470  // Return other types by pointer.
471  return ArgValue<const R*>(i);
472  }
473  }
474  std::string ToString() const;
476  UniValue GetArgMap() const;
478  bool IsValidNumArgs(size_t num_args) const;
480  std::vector<std::pair<std::string, bool>> GetArgNames() const;
481 
482  const std::string m_name;
483 
484 private:
486  const std::string m_description;
487  const std::vector<RPCArg> m_args;
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;
494  size_t GetParamIndex(std::string_view key) const;
495 };
496 
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
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager & args
Definition: bitcoind.cpp:270
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:73
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:414
Fillable signing provider that keeps keys in an address->secret map.
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:408
const RPCExamples m_examples
Definition: util.h:489
size_t GetParamIndex(std::string_view key) const
Return positional index of a parameter using its name as key.
Definition: util.cpp:758
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:543
const std::string m_description
Definition: util.h:486
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:731
const RPCMethodImpl m_fun
Definition: util.h:485
const std::string m_name
Definition: util.h:482
const RPCResults m_results
Definition: util.h:488
const std::vector< RPCArg > m_args
Definition: util.h:487
std::string ToString() const
Definition: util.cpp:768
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:830
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:430
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:743
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:462
const JSONRPCRequest * m_req
Definition: util.h:490
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:633
256-bit opaque blob.
Definition: uint256.h:127
char const * json() noexcept
Template to generate JSON data.
Definition: args.cpp:840
PSBTError
Definition: types.h:17
Definition: messages.h:20
TransactionError
Definition: types.h:19
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::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1305
RPCErrorCode RPCErrorFromTransactionError(node::TransactionError terr)
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:168
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:117
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:192
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:1373
int ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:355
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:124
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:95
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:149
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:1321
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:186
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:115
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:83
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="")
UniValue JSONRPCPSBTError(common::PSBTError err)
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:204
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:44
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FlatSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:241
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:111
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:367
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:173
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:102
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:220
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:345
Definition: util.h:172
Type
Definition: util.h:173
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
@ 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:213
const RPCArgOptions m_opts
Definition: util.h:216
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:211
const Fallback m_fallback
Definition: util.h:214
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1246
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:218
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:896
const std::string m_description
Definition: util.h:215
std::string DefaultHint
Hint for default value.
Definition: util.h:206
bool IsOptional() const
Definition: util.cpp:920
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:209
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:929
const Type m_type
Definition: util.h:212
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:233
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:914
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:909
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1207
Optional
Definition: util.h:192
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
bool hidden
For testing only.
Definition: util.h:159
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:158
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:157
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:160
bool skip_type_check
Definition: util.h:156
std::string ToDescriptionString() const
Definition: util.cpp:628
RPCExamples(std::string examples)
Definition: util.h:396
const std::string m_examples
Definition: util.h:395
const std::string m_description
Definition: util.h:304
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:994
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ANY
Special type to disable type checks (for testing only)
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:301
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:334
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:352
const std::string m_cond
Definition: util.h:305
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1128
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:1195
const bool m_optional
Definition: util.h:302
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:326
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:307
const std::string m_key_name
Only used for dicts.
Definition: util.h:300
const Type m_type
Definition: util.h:299
const bool m_skip_type_check
Definition: util.h:303
RPCResults(RPCResult result)
Definition: util.h:378
const std::vector< RPCResult > m_results
Definition: util.h:376
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:383
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:430
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:18