Bitcoin Core  24.1.0
P2P Digital Currency
util.h
Go to the documentation of this file.
1 // Copyright (c) 2017-2021 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 <node/transaction.h>
9 #include <outputtype.h>
10 #include <protocol.h>
11 #include <pubkey.h>
12 #include <rpc/protocol.h>
13 #include <rpc/request.h>
14 #include <script/script.h>
15 #include <script/sign.h>
16 #include <script/standard.h>
17 #include <univalue.h>
18 #include <util/check.h>
19 
20 #include <string>
21 #include <variant>
22 #include <vector>
23 
24 static constexpr bool DEFAULT_RPC_DOC_CHECK{
25 #ifdef RPC_DOC_CHECK
26  true
27 #else
28  false
29 #endif
30 };
31 
36 extern const std::string UNIX_EPOCH_TIME;
37 
42 extern const std::string EXAMPLE_ADDRESS[2];
43 
45 class CPubKey;
46 class CScript;
47 struct Sections;
48 
54 std::string GetAllOutputTypes();
55 
58 struct UniValueType {
59  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
60  UniValueType() : typeAny(true) {}
61  bool typeAny;
63 };
64 
69 void RPCTypeCheck(const UniValue& params,
70  const std::list<UniValueType>& typesExpected, bool fAllowNull=false);
71 
75 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected);
76 
77 /*
78  Check for expected keys/value types in an Object.
79 */
80 void RPCTypeCheckObj(const UniValue& o,
81  const std::map<std::string, UniValueType>& typesExpected,
82  bool fAllowNull = false,
83  bool fStrict = false);
84 
89 uint256 ParseHashV(const UniValue& v, std::string strName);
90 uint256 ParseHashO(const UniValue& o, std::string strKey);
91 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
92 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
93 
101 CAmount AmountFromValue(const UniValue& value, int decimals = 8);
102 
103 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
104 std::string HelpExampleCli(const std::string& methodname, const std::string& args);
105 std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
106 std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
107 std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
108 
109 CPubKey HexToPubKey(const std::string& hex_in);
110 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
111 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
112 
114 
116 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
117 
119 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
120 
122 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
123 
125 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider);
126 
129 
134 enum class OuterType {
135  ARR,
136  OBJ,
137  NONE, // Only set on first recursion
138 };
139 
140 struct RPCArg {
141  enum class Type {
142  OBJ,
143  ARR,
144  STR,
145  NUM,
146  BOOL,
147  OBJ_USER_KEYS,
148  AMOUNT,
149  STR_HEX,
150  RANGE,
151  };
152 
153  enum class Optional {
155  NO,
167  OMITTED,
168  };
169  using DefaultHint = std::string;
170  using Default = UniValue;
171  using Fallback = std::variant<Optional, /* hint for default value */ DefaultHint, /* default constant value */ Default>;
172  const std::string m_names;
173  const Type m_type;
174  const bool m_hidden;
175  const std::vector<RPCArg> m_inner;
177  const std::string m_description;
178  const std::string m_oneline_description;
179  const std::vector<std::string> m_type_str;
180 
182  const std::string name,
183  const Type type,
184  const Fallback fallback,
185  const std::string description,
186  const std::string oneline_description = "",
187  const std::vector<std::string> type_str = {},
188  const bool hidden = false)
189  : m_names{std::move(name)},
190  m_type{std::move(type)},
191  m_hidden{hidden},
192  m_fallback{std::move(fallback)},
193  m_description{std::move(description)},
194  m_oneline_description{std::move(oneline_description)},
195  m_type_str{std::move(type_str)}
196  {
197  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_USER_KEYS);
198  }
199 
201  const std::string name,
202  const Type type,
203  const Fallback fallback,
204  const std::string description,
205  const std::vector<RPCArg> inner,
206  const std::string oneline_description = "",
207  const std::vector<std::string> type_str = {})
208  : m_names{std::move(name)},
209  m_type{std::move(type)},
210  m_hidden{false},
211  m_inner{std::move(inner)},
212  m_fallback{std::move(fallback)},
213  m_description{std::move(description)},
214  m_oneline_description{std::move(oneline_description)},
215  m_type_str{std::move(type_str)}
216  {
217  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_USER_KEYS);
218  }
219 
220  bool IsOptional() const;
221 
223  std::string GetFirstName() const;
224 
226  std::string GetName() const;
227 
232  std::string ToString(bool oneline) const;
237  std::string ToStringObj(bool oneline) const;
242  std::string ToDescriptionString() const;
243 };
244 
245 struct RPCResult {
246  enum class Type {
247  OBJ,
248  ARR,
249  STR,
250  NUM,
251  BOOL,
252  NONE,
253  ANY,
254  STR_AMOUNT,
255  STR_HEX,
256  OBJ_DYN,
257  ARR_FIXED,
258  NUM_TIME,
259  ELISION,
260  };
261 
262  const Type m_type;
263  const std::string m_key_name;
264  const std::vector<RPCResult> m_inner;
265  const bool m_optional;
266  const bool m_skip_type_check;
267  const std::string m_description;
268  const std::string m_cond;
269 
271  const std::string cond,
272  const Type type,
273  const std::string m_key_name,
274  const bool optional,
275  const std::string description,
276  const std::vector<RPCResult> inner = {})
277  : m_type{std::move(type)},
278  m_key_name{std::move(m_key_name)},
279  m_inner{std::move(inner)},
280  m_optional{optional},
281  m_skip_type_check{false},
282  m_description{std::move(description)},
283  m_cond{std::move(cond)}
284  {
285  CHECK_NONFATAL(!m_cond.empty());
286  CheckInnerDoc();
287  }
288 
290  const std::string cond,
291  const Type type,
292  const std::string m_key_name,
293  const std::string description,
294  const std::vector<RPCResult> inner = {})
295  : RPCResult{cond, type, m_key_name, false, description, inner} {}
296 
298  const Type type,
299  const std::string m_key_name,
300  const bool optional,
301  const std::string description,
302  const std::vector<RPCResult> inner = {},
303  bool skip_type_check = false)
304  : m_type{std::move(type)},
305  m_key_name{std::move(m_key_name)},
306  m_inner{std::move(inner)},
307  m_optional{optional},
308  m_skip_type_check{skip_type_check},
309  m_description{std::move(description)},
310  m_cond{}
311  {
312  CheckInnerDoc();
313  }
314 
316  const Type type,
317  const std::string m_key_name,
318  const std::string description,
319  const std::vector<RPCResult> inner = {},
320  bool skip_type_check = false)
321  : RPCResult{type, m_key_name, false, description, inner, skip_type_check} {}
322 
324  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
326  std::string ToStringObj() const;
328  std::string ToDescriptionString() const;
330  bool MatchesType(const UniValue& result) const;
331 
332 private:
333  void CheckInnerDoc() const;
334 };
335 
336 struct RPCResults {
337  const std::vector<RPCResult> m_results;
338 
340  : m_results{{result}}
341  {
342  }
343 
344  RPCResults(std::initializer_list<RPCResult> results)
345  : m_results{results}
346  {
347  }
348 
352  std::string ToDescriptionString() const;
353 };
354 
355 struct RPCExamples {
356  const std::string m_examples;
357  explicit RPCExamples(
358  std::string examples)
359  : m_examples(std::move(examples))
360  {
361  }
362  std::string ToDescriptionString() const;
363 };
364 
366 {
367 public:
368  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
369  using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
370  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
371 
372  UniValue HandleRequest(const JSONRPCRequest& request) const;
373  std::string ToString() const;
375  UniValue GetArgMap() const;
377  bool IsValidNumArgs(size_t num_args) const;
378  std::vector<std::string> GetArgNames() const;
379 
380  const std::string m_name;
381 
382 private:
384  const std::string m_description;
385  const std::vector<RPCArg> m_args;
388 };
389 
390 #endif // BITCOIN_RPC_UTIL_H
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:335
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:166
UniValueType(UniValue::VType _type)
Definition: util.h:59
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull=false)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:33
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:88
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:100
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:113
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:264
Type
Definition: util.h:141
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:1057
const Fallback m_fallback
Definition: util.h:176
ServiceFlags
nServices flags
Definition: protocol.h:267
std::vector< std::string > GetArgNames() const
Definition: util.cpp:604
void CheckInnerDoc() const
Definition: util.cpp:944
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:551
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:109
Required arg.
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:393
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:178
RPCResult(const Type type, const std::string m_key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:297
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:20
bool typeAny
Definition: util.h:61
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:215
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:202
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
Definition: util.cpp:23
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:24
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:768
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:47
const std::string m_key_name
Only used for dicts.
Definition: util.h:263
std::string ToDescriptionString() const
Definition: util.cpp:568
const RPCExamples m_examples
Definition: util.h:387
RPCArg(const std::string name, const Type type, const Fallback fallback, const std::string description, const std::string oneline_description="", const std::vector< std::string > type_str={}, const bool hidden=false)
Definition: util.h:181
const RPCMethodImpl m_fun
Definition: util.h:383
RPCResult(const std::string cond, const Type type, const std::string m_key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:270
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:592
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type. ...
Definition: util.cpp:664
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:613
const bool m_skip_type_check
Definition: util.h:266
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:175
OutputType
Definition: outputtype.h:17
ArgsManager args
const std::string m_cond
Definition: util.h:268
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:50
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:350
const Type m_type
Definition: util.h:262
UniValue::VType type
Definition: util.h:62
const std::string m_description
Definition: util.h:384
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:58
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:688
Special string with only hex chars.
Definition: util.h:140
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:236
const char * name
Definition: rest.cpp:46
Special array that has a fixed number of entries.
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:344
bool IsOptional() const
Definition: util.cpp:694
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:172
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)
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1095
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:369
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:340
const std::vector< RPCResult > m_results
Definition: util.h:337
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:866
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
std::string DefaultHint
Definition: util.h:169
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:683
const std::vector< RPCArg > m_args
Definition: util.h:385
const std::string m_description
Definition: util.h:177
Special numeric to denote unix epoch time.
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:369
const std::string m_examples
Definition: util.h:356
Optional arg that is a named argument and has a default value of null.
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:103
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings. Vector length is either 0 or 2, m_type_str.at(0) will override the type of the value in a key-value pair, m_type_str.at(1) will override the type in the argument description.
Definition: util.h:179
const RPCResults m_results
Definition: util.h:386
Special type that is a NUM or [NUM,NUM].
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:171
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:134
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:503
256-bit opaque blob.
Definition: uint256.h:119
Optional argument with default value omitted because they are implicitly clear.
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required...
Definition: util.cpp:703
UniValueType()
Definition: util.h:60
Special string to represent a floating point amount.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:190
Optional
Definition: util.h:153
const std::string m_description
Definition: util.h:267
Special type representing a floating point amount (can be either NUM or STR)
TransactionError
Definition: error.h:22
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:171
RPCResults(RPCResult result)
Definition: util.h:339
RPCResult(const std::string cond, const Type type, const std::string m_key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:289
const Type m_type
Definition: util.h:173
RPCResult(const Type type, const std::string m_key_name, const std::string description, const std::vector< RPCResult > inner={}, bool skip_type_check=false)
Definition: util.h:315
RPCArg(const std::string name, const Type type, const Fallback fallback, const std::string description, const std::vector< RPCArg > inner, const std::string oneline_description="", const std::vector< std::string > type_str={})
Definition: util.h:200
RPCExamples(std::string examples)
Definition: util.h:357
const bool m_hidden
Definition: util.h:174
const bool m_optional
Definition: util.h:265
const std::string m_name
Definition: util.h:380
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:573
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:992
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1041
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:58
Special type to denote elision (...)
std::string ToDescriptionString() const
Return the description string, including the result type.
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:122
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:955