Bitcoin Core  27.1.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 
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};
155 };
164 
165 struct RPCArg {
166  enum class Type {
167  OBJ,
168  ARR,
169  STR,
170  NUM,
171  BOOL,
173  OBJ_USER_KEYS,
180  AMOUNT,
181  STR_HEX,
182  RANGE,
183  };
184 
185  enum class Optional {
187  NO,
196  OMITTED,
197  };
199  using DefaultHint = std::string;
201  using Default = UniValue;
202  using Fallback = std::variant<Optional, DefaultHint, Default>;
203 
204  const std::string m_names;
205  const Type m_type;
206  const std::vector<RPCArg> m_inner;
208  const std::string m_description;
210 
212  std::string name,
213  Type type,
214  Fallback fallback,
215  std::string description,
216  RPCArgOptions opts = {})
217  : m_names{std::move(name)},
218  m_type{std::move(type)},
219  m_fallback{std::move(fallback)},
220  m_description{std::move(description)},
221  m_opts{std::move(opts)}
222  {
223  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_NAMED_PARAMS && type != Type::OBJ_USER_KEYS);
224  }
225 
227  std::string name,
228  Type type,
229  Fallback fallback,
230  std::string description,
231  std::vector<RPCArg> inner,
232  RPCArgOptions opts = {})
233  : m_names{std::move(name)},
234  m_type{std::move(type)},
235  m_inner{std::move(inner)},
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 
243  bool IsOptional() const;
244 
249  UniValue MatchesType(const UniValue& request) const;
250 
252  std::string GetFirstName() const;
253 
255  std::string GetName() const;
256 
261  std::string ToString(bool oneline) const;
266  std::string ToStringObj(bool oneline) const;
271  std::string ToDescriptionString(bool is_named_arg) const;
272 };
273 
274 struct RPCResult {
275  enum class Type {
276  OBJ,
277  ARR,
278  STR,
279  NUM,
280  BOOL,
281  NONE,
282  ANY,
283  STR_AMOUNT,
284  STR_HEX,
285  OBJ_DYN,
286  ARR_FIXED,
287  NUM_TIME,
288  ELISION,
289  };
290 
291  const Type m_type;
292  const std::string m_key_name;
293  const std::vector<RPCResult> m_inner;
294  const bool m_optional;
295  const bool m_skip_type_check;
296  const std::string m_description;
297  const std::string m_cond;
298 
300  std::string cond,
301  Type type,
302  std::string m_key_name,
303  bool optional,
304  std::string description,
305  std::vector<RPCResult> inner = {})
306  : m_type{std::move(type)},
307  m_key_name{std::move(m_key_name)},
308  m_inner{std::move(inner)},
309  m_optional{optional},
310  m_skip_type_check{false},
311  m_description{std::move(description)},
312  m_cond{std::move(cond)}
313  {
314  CHECK_NONFATAL(!m_cond.empty());
315  CheckInnerDoc();
316  }
317 
319  std::string cond,
320  Type type,
321  std::string m_key_name,
322  std::string description,
323  std::vector<RPCResult> inner = {})
324  : RPCResult{std::move(cond), type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner)} {}
325 
327  Type type,
328  std::string m_key_name,
329  bool optional,
330  std::string description,
331  std::vector<RPCResult> inner = {},
332  bool skip_type_check = false)
333  : m_type{std::move(type)},
334  m_key_name{std::move(m_key_name)},
335  m_inner{std::move(inner)},
336  m_optional{optional},
337  m_skip_type_check{skip_type_check},
338  m_description{std::move(description)},
339  m_cond{}
340  {
341  CheckInnerDoc();
342  }
343 
345  Type type,
346  std::string m_key_name,
347  std::string description,
348  std::vector<RPCResult> inner = {},
349  bool skip_type_check = false)
350  : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
351 
353  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
355  std::string ToStringObj() const;
357  std::string ToDescriptionString() const;
361  UniValue MatchesType(const UniValue& result) const;
362 
363 private:
364  void CheckInnerDoc() const;
365 };
366 
367 struct RPCResults {
368  const std::vector<RPCResult> m_results;
369 
371  : m_results{{result}}
372  {
373  }
374 
375  RPCResults(std::initializer_list<RPCResult> results)
376  : m_results{results}
377  {
378  }
379 
383  std::string ToDescriptionString() const;
384 };
385 
386 struct RPCExamples {
387  const std::string m_examples;
388  explicit RPCExamples(
389  std::string examples)
390  : m_examples(std::move(examples))
391  {
392  }
393  std::string ToDescriptionString() const;
394 };
395 
397 {
398 public:
399  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
400  using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
401  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
402 
403  UniValue HandleRequest(const JSONRPCRequest& request) const;
418  template <typename R>
419  auto Arg(size_t i) const
420  {
421  // Return argument (required or with default value).
422  if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
423  // Return numbers by value.
424  return ArgValue<R>(i);
425  } else {
426  // Return everything else by reference.
427  return ArgValue<const R&>(i);
428  }
429  }
430  template <typename R>
431  auto MaybeArg(size_t i) const
432  {
433  // Return optional argument (without default).
434  if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
435  // Return numbers by value, wrapped in optional.
436  return ArgValue<std::optional<R>>(i);
437  } else {
438  // Return other types by pointer.
439  return ArgValue<const R*>(i);
440  }
441  }
442  std::string ToString() const;
444  UniValue GetArgMap() const;
446  bool IsValidNumArgs(size_t num_args) const;
448  std::vector<std::pair<std::string, bool>> GetArgNames() const;
449 
450  const std::string m_name;
451 
452 private:
454  const std::string m_description;
455  const std::vector<RPCArg> m_args;
458  mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
459  template <typename R>
460  R ArgValue(size_t i) const;
461 };
462 
469 void PushWarnings(const UniValue& warnings, UniValue& obj);
470 void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj);
471 
472 #endif // BITCOIN_RPC_UTIL_H
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:329
char const * json() noexcept
Template to generate JSON data.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:155
UniValueType(UniValue::VType _type)
Definition: util.h:75
static const std::string sighash
Definition: sighash.json.h:3
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:111
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::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:293
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings. Vector length is either 0 or 2, m_opts.type_str.at(0) will override the type of the value in a key-value pair, m_opts.type_str.at(1) will override the type in the argument description.
Definition: util.h:152
Type
Definition: util.h:166
RPCArg(std::string name, Type type, Fallback fallback, std::string description, std::vector< RPCArg > inner, RPCArgOptions opts={})
Definition: util.h:226
const Fallback m_fallback
Definition: util.h:207
ServiceFlags
nServices flags
Definition: protocol.h:274
void CheckInnerDoc() const
Definition: util.cpp:1156
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:584
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
const RPCArgOptions m_opts
Definition: util.h:209
Required arg.
auto Arg(size_t i) const
Helper to get a request argument.
Definition: util.h:419
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:1279
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:326
Bilingual messages:
Definition: translation.h:18
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:404
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
bool typeAny
Definition: util.h:77
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
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:204
bool hidden
For testing only.
Definition: util.h:153
R ArgValue(size_t i) const
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:191
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:33
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:31
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:41
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:956
RPCArg(std::string name, Type type, Fallback fallback, std::string description, RPCArgOptions opts={})
Definition: util.h:211
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:73
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
int ParseSighashString(const UniValue &sighash)
Parse a sighash string representation and raise an RPC error if it is invalid.
Definition: util.cpp:339
const std::string m_key_name
Only used for dicts.
Definition: util.h:292
std::string ToDescriptionString() const
Definition: util.cpp:601
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:102
RPCResult(std::string cond, Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:318
std::vector< std::pair< std::string, bool > > GetArgNames() const
Return list of arguments and whether they are named-only.
Definition: util.cpp:716
const RPCExamples m_examples
Definition: util.h:457
const RPCMethodImpl m_fun
Definition: util.h:453
bool skip_type_check
Definition: util.h:150
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:704
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type. ...
Definition: util.cpp:793
std::string ToStringObj() const
Return the type string of the result when it is in an object (dict).
std::string ToString() const
Definition: util.cpp:731
const bool m_skip_type_check
Definition: util.h:295
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:206
OutputType
Definition: outputtype.h:17
const std::string m_cond
Definition: util.h:297
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:361
const Type m_type
Definition: util.h:291
UniValue::VType type
Definition: util.h:78
const std::string m_description
Definition: util.h:454
CFeeRate ParseFeeRate(const UniValue &json)
Parse a json number or string, denoting BTC/kvB, into a CFeeRate (sat/kvB).
Definition: util.cpp:82
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:43
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:151
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1331
Special type that is a STR with only hex chars.
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:877
Special string with only hex chars.
Definition: util.h:165
ArgsManager & args
Definition: bitcoind.cpp:268
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:225
const char * name
Definition: rest.cpp:49
Special array that has a fixed number of entries.
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:375
bool IsOptional() const
Definition: util.cpp:883
An encapsulated public key.
Definition: pubkey.h:33
Fillable signing provider that keeps keys in an address->secret map.
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:204
RPCResult(Type type, std::string m_key_name, std::string description, std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:344
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e...
Special type to disable type checks (for testing only)
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:400
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
const std::vector< RPCResult > m_results
Definition: util.h:368
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:173
std::string DefaultHint
Hint for default value.
Definition: util.h:199
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:872
const std::vector< RPCArg > m_args
Definition: util.h:455
const std::string m_description
Definition: util.h:208
Special numeric to denote unix epoch time.
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:380
const std::string m_examples
Definition: util.h:387
const JSONRPCRequest * m_req
Definition: util.h:458
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:112
const RPCResults m_results
Definition: util.h:456
Special type that is a NUM or [NUM,NUM].
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:202
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:143
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:516
256-bit opaque blob.
Definition: uint256.h:106
Optional argument for which the default value is omitted from help text for one of two reasons: ...
UniValueType()
Definition: util.h:76
Special string to represent a floating point amount.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:179
Optional
Definition: util.h:185
const std::string m_description
Definition: util.h:296
uint256 ParseHashO(const UniValue &o, std::string_view strKey)
Definition: util.cpp:98
Special type representing a floating point amount (can be either NUM or STR)
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:160
RPCResults(RPCResult result)
Definition: util.h:370
UniValue MatchesType(const UniValue &request) const
Check whether the request JSON type matches.
Definition: util.cpp:859
auto MaybeArg(size_t i) const
Definition: util.h:431
const Type m_type
Definition: util.h:205
UniValue MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:1089
RPCExamples(std::string examples)
Definition: util.h:388
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:892
const bool m_optional
Definition: util.h:294
const std::string m_name
Definition: util.h:450
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
Special dictionary with keys that are not literals.
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:606
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:1205
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1263
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:74
RPCResult(std::string cond, Type type, std::string m_key_name, bool optional, std::string description, std::vector< RPCResult > inner={})
Definition: util.h:299
Special type to denote elision (...)
std::string ToDescriptionString() const
Return the description string, including the result type.
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:1167