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 enum class TransactionError;
38 struct FlatSigningProvider;
39 struct bilingual_str;
40 
41 static constexpr bool DEFAULT_RPC_DOC_CHECK{
42 #ifdef RPC_DOC_CHECK
43  true
44 #else
45  false
46 #endif
47 };
48 
53 extern const std::string UNIX_EPOCH_TIME;
54 
59 extern const std::string EXAMPLE_ADDRESS[2];
60 
62 class CScript;
63 struct Sections;
64 
70 std::string GetAllOutputTypes();
71 
74 struct UniValueType {
75  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
76  UniValueType() : typeAny(true) {}
77  bool typeAny;
79 };
80 
81 /*
82  Check for expected keys/value types in an Object.
83 */
84 void RPCTypeCheckObj(const UniValue& o,
85  const std::map<std::string, UniValueType>& typesExpected,
86  bool fAllowNull = false,
87  bool fStrict = false);
88 
93 uint256 ParseHashV(const UniValue& v, std::string_view name);
94 uint256 ParseHashO(const UniValue& o, std::string_view strKey);
95 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name);
96 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey);
97 
105 CAmount AmountFromValue(const UniValue& value, int decimals = 8);
111 
112 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
113 std::string HelpExampleCli(const std::string& methodname, const std::string& args);
114 std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
115 std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
116 std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
117 
118 CPubKey HexToPubKey(const std::string& hex_in);
119 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
120 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
121 
123 
125 int ParseSighashString(const UniValue& sighash);
126 
128 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
129 
131 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
132 
134 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
135 
137 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false);
138 
143 enum class OuterType {
144  ARR,
145  OBJ,
146  NONE, // Only set on first recursion
147 };
148 
150  bool skip_type_check{false};
151  std::string oneline_description{};
152  std::vector<std::string> type_str{};
153  bool hidden{false};
154  bool also_positional{false};
163 };
164 
165 // NOLINTNEXTLINE(misc-no-recursion)
166 struct RPCArg {
167  enum class Type {
168  OBJ,
169  ARR,
170  STR,
171  NUM,
172  BOOL,
180  OBJ_USER_KEYS,
181  AMOUNT,
182  STR_HEX,
183  RANGE,
184  };
185 
186  enum class Optional {
188  NO,
197  OMITTED,
198  };
200  using DefaultHint = std::string;
202  using Default = UniValue;
203  using Fallback = std::variant<Optional, DefaultHint, Default>;
204 
205  const std::string m_names;
206  const Type m_type;
207  const std::vector<RPCArg> m_inner;
209  const std::string m_description;
211 
213  std::string name,
214  Type type,
215  Fallback fallback,
216  std::string description,
217  RPCArgOptions opts = {})
218  : m_names{std::move(name)},
219  m_type{std::move(type)},
220  m_fallback{std::move(fallback)},
221  m_description{std::move(description)},
222  m_opts{std::move(opts)}
223  {
224  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
225  }
226 
228  std::string name,
229  Type type,
230  Fallback fallback,
231  std::string description,
232  std::vector<RPCArg> inner,
233  RPCArgOptions opts = {})
234  : m_names{std::move(name)},
235  m_type{std::move(type)},
236  m_inner{std::move(inner)},
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 
244  bool IsOptional() const;
245 
250  UniValue MatchesType(const UniValue& request) const;
251 
253  std::string GetFirstName() const;
254 
256  std::string GetName() const;
257 
262  std::string ToString(bool oneline) const;
267  std::string ToStringObj(bool oneline) const;
272  std::string ToDescriptionString(bool is_named_arg) const;
273 };
274 
275 // NOLINTNEXTLINE(misc-no-recursion)
276 struct RPCResult {
277  enum class Type {
278  OBJ,
279  ARR,
280  STR,
281  NUM,
282  BOOL,
283  NONE,
284  ANY,
285  STR_AMOUNT,
286  STR_HEX,
287  OBJ_DYN,
288  ARR_FIXED,
289  NUM_TIME,
290  ELISION,
291  };
292 
293  const Type m_type;
294  const std::string m_key_name;
295  const std::vector<RPCResult> m_inner;
296  const bool m_optional;
297  const bool m_skip_type_check;
298  const std::string m_description;
299  const std::string m_cond;
300 
302  std::string cond,
303  Type type,
304  std::string m_key_name,
305  bool optional,
306  std::string description,
307  std::vector<RPCResult> inner = {})
308  : m_type{std::move(type)},
309  m_key_name{std::move(m_key_name)},
310  m_inner{std::move(inner)},
311  m_optional{optional},
312  m_skip_type_check{false},
313  m_description{std::move(description)},
314  m_cond{std::move(cond)}
315  {
316  CHECK_NONFATAL(!m_cond.empty());
317  CheckInnerDoc();
318  }
319 
321  std::string cond,
322  Type type,
323  std::string m_key_name,
324  std::string description,
325  std::vector<RPCResult> inner = {})
326  : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
327 
329  Type type,
330  std::string m_key_name,
331  bool optional,
332  std::string description,
333  std::vector<RPCResult> inner = {},
334  bool skip_type_check = false)
335  : m_type{std::move(type)},
336  m_key_name{std::move(m_key_name)},
337  m_inner{std::move(inner)},
338  m_optional{optional},
339  m_skip_type_check{skip_type_check},
340  m_description{std::move(description)},
341  m_cond{}
342  {
343  CheckInnerDoc();
344  }
345 
347  Type type,
348  std::string m_key_name,
349  std::string description,
350  std::vector<RPCResult> inner = {},
351  bool skip_type_check = false)
352  : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
353 
355  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
357  std::string ToStringObj() const;
359  std::string ToDescriptionString() const;
363  UniValue MatchesType(const UniValue& result) const;
364 
365 private:
366  void CheckInnerDoc() const;
367 };
368 
369 struct RPCResults {
370  const std::vector<RPCResult> m_results;
371 
373  : m_results{{result}}
374  {
375  }
376 
377  RPCResults(std::initializer_list<RPCResult> results)
378  : m_results{results}
379  {
380  }
381 
385  std::string ToDescriptionString() const;
386 };
387 
388 struct RPCExamples {
389  const std::string m_examples;
390  explicit RPCExamples(
391  std::string examples)
392  : m_examples(std::move(examples))
393  {
394  }
395  std::string ToDescriptionString() const;
396 };
397 
399 {
400 public:
401  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
402  using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
403  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
404 
405  UniValue HandleRequest(const JSONRPCRequest& request) const;
420  template <typename R>
421  auto Arg(size_t i) const
422  {
423  // Return argument (required or with default value).
424  if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
425  // Return numbers by value.
426  return ArgValue<R>(i);
427  } else {
428  // Return everything else by reference.
429  return ArgValue<const R&>(i);
430  }
431  }
432  template <typename R>
433  auto MaybeArg(size_t i) const
434  {
435  // Return optional argument (without default).
436  if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
437  // Return numbers by value, wrapped in optional.
438  return ArgValue<std::optional<R>>(i);
439  } else {
440  // Return other types by pointer.
441  return ArgValue<const R*>(i);
442  }
443  }
444  std::string ToString() const;
446  UniValue GetArgMap() const;
448  bool IsValidNumArgs(size_t num_args) const;
450  std::vector<std::pair<std::string, bool>> GetArgNames() const;
451 
452  const std::string m_name;
453 
454 private:
456  const std::string m_description;
457  const std::vector<RPCArg> m_args;
460  mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
461  template <typename R>
462  R ArgValue(size_t i) const;
463 };
464 
471 void PushWarnings(const UniValue& warnings, UniValue& obj);
472 void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
473 
474 #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:268
#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:402
const RPCExamples m_examples
Definition: util.h:459
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:517
const std::string m_description
Definition: util.h:456
R ArgValue(size_t i) const
auto Arg(size_t i) const
Helper to get a request argument.
Definition: util.h:421
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:705
const RPCMethodImpl m_fun
Definition: util.h:455
const std::string m_name
Definition: util.h:452
auto MaybeArg(size_t i) const
Definition: util.h:433
const RPCResults m_results
Definition: util.h:458
const std::vector< RPCArg > m_args
Definition: util.h:457
std::string ToString() const
Definition: util.cpp:732
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:794
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:717
const JSONRPCRequest * m_req
Definition: util.h:460
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:607
256-bit opaque blob.
Definition: uint256.h:106
TransactionError
Definition: error.h:22
char const * json() noexcept
Template to generate JSON data.
OutputType
Definition: outputtype.h:17
ServiceFlags
nServices flags
Definition: protocol.h:274
const char * name
Definition: rest.cpp:50
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:24
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1269
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:155
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:112
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:225
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:179
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:380
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:41
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1337
int ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:339
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:361
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:111
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:82
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:143
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:1285
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:173
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:102
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:70
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:30
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:43
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:33
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:191
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:31
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:98
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:351
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:160
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:204
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:329
Definition: util.h:166
Type
Definition: util.h:167
@ 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:207
const RPCArgOptions m_opts
Definition: util.h:210
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:205
const Fallback m_fallback
Definition: util.h:208
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1210
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:212
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:860
const std::string m_description
Definition: util.h:209
std::string DefaultHint
Hint for default value.
Definition: util.h:200
bool IsOptional() const
Definition: util.cpp:884
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:203
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:893
const Type m_type
Definition: util.h:206
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:227
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:878
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:873
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1171
Optional
Definition: util.h:186
@ 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:153
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:152
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:151
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:154
bool skip_type_check
Definition: util.h:150
std::string ToDescriptionString() const
Definition: util.cpp:602
RPCExamples(std::string examples)
Definition: util.h:390
const std::string m_examples
Definition: util.h:389
const std::string m_description
Definition: util.h:298
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:958
@ 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:295
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:328
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:346
const std::string m_cond
Definition: util.h:299
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1092
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:1159
const bool m_optional
Definition: util.h:296
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:320
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:301
const std::string m_key_name
Only used for dicts.
Definition: util.h:294
const Type m_type
Definition: util.h:293
const bool m_skip_type_check
Definition: util.h:297
RPCResults(RPCResult result)
Definition: util.h:372
const std::vector< RPCResult > m_results
Definition: util.h:370
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:377
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:404
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:74
bool typeAny
Definition: util.h:77
UniValueType(UniValue::VType _type)
Definition: util.h:75
UniValue::VType type
Definition: util.h:78
UniValueType()
Definition: util.h:76
Bilingual messages:
Definition: translation.h:18