Bitcoin ABC  0.26.3
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 <rpc/protocol.h>
12 #include <rpc/request.h>
13 #include <script/script.h>
14 #include <script/sign.h>
15 #include <script/standard.h> // For CTxDestination
16 #include <univalue.h>
17 #include <util/check.h>
18 
19 #include <string>
20 #include <variant>
21 #include <vector>
22 
23 class CChainParams;
25 class CPubKey;
26 class CScript;
27 struct Sections;
28 
33 extern const std::string UNIX_EPOCH_TIME;
34 
38 extern const std::string EXAMPLE_ADDRESS;
39 
44 struct UniValueType {
45  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
46  UniValueType() : typeAny(true) {}
47  bool typeAny;
49 };
50 
56 void RPCTypeCheck(const UniValue &params,
57  const std::list<UniValueType> &typesExpected,
58  bool fAllowNull = false);
59 
63 void RPCTypeCheckArgument(const UniValue &value,
64  const UniValueType &typeExpected);
65 
69 void RPCTypeCheckObj(const UniValue &o,
70  const std::map<std::string, UniValueType> &typesExpected,
71  bool fAllowNull = false, bool fStrict = false);
72 
76 extern uint256 ParseHashV(const UniValue &v, std::string strName);
77 extern uint256 ParseHashO(const UniValue &o, std::string strKey);
78 extern std::vector<uint8_t> ParseHexV(const UniValue &v, std::string strName);
79 extern std::vector<uint8_t> ParseHexO(const UniValue &o, std::string strKey);
80 
81 extern Amount AmountFromValue(const UniValue &value);
82 
83 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
84 extern std::string HelpExampleCli(const std::string &methodname,
85  const std::string &args);
86 extern std::string HelpExampleCliNamed(const std::string &methodname,
87  const RPCArgList &args);
88 extern std::string HelpExampleRpc(const std::string &methodname,
89  const std::string &args);
90 extern std::string HelpExampleRpcNamed(const std::string &methodname,
91  const RPCArgList &args);
92 
93 CPubKey HexToPubKey(const std::string &hex_in);
94 CPubKey AddrToPubKey(const CChainParams &chainparams,
95  const FillableSigningProvider &keystore,
96  const std::string &addr_in);
98  const std::vector<CPubKey> &pubkeys,
99  OutputType type,
100  FillableSigningProvider &keystore,
101  CScript &script_out);
102 
104 std::string GetAllOutputTypes();
105 
108  const std::string &err_string = "");
109 
111 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value);
112 
117 std::vector<CScript>
118 EvalDescriptorStringOrObject(const UniValue &scanobject,
119  FlatSigningProvider &provider);
120 
126 
131 enum class OuterType {
132  ARR,
133  OBJ,
134  NONE, // Only set on first recursion
135 };
136 
137 struct RPCArg {
138  enum class Type {
139  OBJ,
140  ARR,
141  STR,
142  NUM,
143  BOOL,
150  AMOUNT,
152  STR_HEX,
154  RANGE,
155  };
156 
157  enum class Optional {
159  NO,
171  OMITTED,
172  };
173  using DefaultHint = std::string;
174  using Default = UniValue;
175  using Fallback =
176  std::variant<Optional, /* hint for default value */ DefaultHint,
177  /* default constant value */ Default>;
180  const std::string m_names;
181  const Type m_type;
182  const bool m_hidden;
184  const std::vector<RPCArg> m_inner;
186  const std::string m_description;
189  const std::string m_oneline_description;
190 
196  const std::vector<std::string> m_type_str;
197 
198  RPCArg(const std::string name, const Type type, const Fallback fallback,
199  const std::string description,
200  const std::string oneline_description = "",
201  const std::vector<std::string> type_str = {},
202  const bool hidden = false)
203  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{hidden},
204  m_fallback{std::move(fallback)}, m_description{std::move(
205  description)},
206  m_oneline_description{std::move(oneline_description)},
207  m_type_str{std::move(type_str)} {
208  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ);
209  }
210 
211  RPCArg(const std::string name, const Type type, const Fallback fallback,
212  const std::string description, const std::vector<RPCArg> inner,
213  const std::string oneline_description = "",
214  const std::vector<std::string> type_str = {})
215  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{false},
216  m_inner{std::move(inner)}, m_fallback{std::move(fallback)},
217  m_description{std::move(description)},
218  m_oneline_description{std::move(oneline_description)},
219  m_type_str{std::move(type_str)} {
220  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ);
221  }
222 
223  bool IsOptional() const;
224 
226  std::string GetFirstName() const;
227 
229  std::string GetName() const;
230 
236  std::string ToString(bool oneline) const;
241  std::string ToStringObj(bool oneline) const;
246  std::string ToDescriptionString() const;
247 };
248 
249 struct RPCResult {
250  enum class Type {
251  OBJ,
252  ARR,
253  STR,
254  NUM,
255  BOOL,
256  NONE,
257  ANY,
258  STR_AMOUNT,
259  STR_HEX,
260  OBJ_DYN,
261  OBJ_EMPTY,
262  ARR_FIXED,
263  NUM_TIME,
264  ELISION,
265  };
266 
267  const Type m_type;
268  const std::string m_key_name;
269  const std::vector<RPCResult> m_inner;
270  const bool m_optional;
271  const std::string m_description;
272  const std::string m_cond;
273 
274  RPCResult(const std::string cond, const Type type,
275  const std::string key_name, const bool optional,
276  const std::string description,
277  const std::vector<RPCResult> inner = {})
278  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
279  m_inner{std::move(inner)}, m_optional{optional},
280  m_description{std::move(description)}, m_cond{std::move(cond)} {
281  CHECK_NONFATAL(!m_cond.empty());
282  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
283  type == Type::OBJ || type == Type::OBJ_DYN};
284  CHECK_NONFATAL(inner_needed != inner.empty());
285  }
286 
287  RPCResult(const std::string cond, const Type type,
288  const std::string key_name, const std::string description,
289  const std::vector<RPCResult> inner = {})
290  : RPCResult{cond, type, key_name, false, description, inner} {}
291 
292  RPCResult(const Type type, const std::string key_name, const bool optional,
293  const std::string description,
294  const std::vector<RPCResult> inner = {})
295  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
296  m_inner{std::move(inner)}, m_optional{optional},
297  m_description{std::move(description)}, m_cond{} {
298  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
299  type == Type::OBJ || type == Type::OBJ_DYN};
300  CHECK_NONFATAL(inner_needed != inner.empty());
301  }
302 
303  RPCResult(const Type type, const std::string key_name,
304  const std::string description,
305  const std::vector<RPCResult> inner = {})
306  : RPCResult{type, key_name, false, description, inner} {}
307 
309  void ToSections(Sections &sections, OuterType outer_type = OuterType::NONE,
310  const int current_indent = 0) const;
312  std::string ToStringObj() const;
314  std::string ToDescriptionString() const;
316  bool MatchesType(const UniValue &result) const;
317 };
318 
319 struct RPCResults {
320  const std::vector<RPCResult> m_results;
321 
322  RPCResults(RPCResult result) : m_results{{result}} {}
323 
324  RPCResults(std::initializer_list<RPCResult> results) : m_results{results} {}
325 
329  std::string ToDescriptionString() const;
330 };
331 
332 struct RPCExamples {
333  const std::string m_examples;
334  explicit RPCExamples(std::string examples)
335  : m_examples(std::move(examples)) {}
336  RPCExamples() : m_examples(std::move("")) {}
337  std::string ToDescriptionString() const;
338 };
339 
340 class RPCHelpMan {
341 public:
342  RPCHelpMan(std::string name, std::string description,
343  std::vector<RPCArg> args, RPCResults results,
344  RPCExamples examples);
345  using RPCMethodImpl = std::function<UniValue(
346  const RPCHelpMan &, const Config &config, const JSONRPCRequest &)>;
347  RPCHelpMan(std::string name, std::string description,
348  std::vector<RPCArg> args, RPCResults results,
349  RPCExamples examples, RPCMethodImpl fun);
350 
351  UniValue HandleRequest(const Config &config,
352  const JSONRPCRequest &request) const;
353  std::string ToString() const;
358  UniValue GetArgMap() const;
360  bool IsValidNumArgs(size_t num_args) const;
361  std::vector<std::string> GetArgNames() const;
362 
363  const std::string m_name;
364 
365 private:
367  const std::string m_description;
368  const std::vector<RPCArg> m_args;
371 };
372 
373 #endif // BITCOIN_RPC_UTIL_H
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
An encapsulated public key.
Definition: pubkey.h:31
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
Definition: config.h:17
Fillable signing provider that keeps keys in an address->secret map.
const RPCExamples m_examples
Definition: util.h:370
std::vector< std::string > GetArgNames() const
Definition: util.cpp:618
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:510
const std::string m_description
Definition: util.h:367
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:607
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:346
const RPCMethodImpl m_fun
Definition: util.h:366
const std::string m_name
Definition: util.h:363
const RPCResults m_results
Definition: util.h:369
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
Definition: util.cpp:587
const std::vector< RPCArg > m_args
Definition: util.h:368
std::string ToString() const
Definition: util.cpp:626
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:694
256-bit opaque blob.
Definition: uint256.h:127
TransactionError
Definition: error.h:22
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
OutputType
Definition: outputtype.h:16
ServiceFlags
nServices flags.
Definition: protocol.h:335
const char * name
Definition: rest.cpp:48
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:22
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1043
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:119
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:175
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:83
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1107
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:258
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:201
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:41
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:358
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:80
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:24
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:339
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:133
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:21
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:131
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:1060
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:192
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
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Check for expected keys/value types in an Object.
Definition: util.cpp:51
std::string GetAllOutputTypes()
Definition: util.cpp:330
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:216
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:230
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:115
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:98
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:180
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:326
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:92
Definition: amount.h:19
Definition: util.h:137
Type
Definition: util.h:138
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g.
@ 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)
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:184
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:180
const Fallback m_fallback
Definition: util.h:185
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:986
const bool m_hidden
Definition: util.h:182
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:198
const std::string m_description
Definition: util.h:186
std::string DefaultHint
Definition: util.h:173
bool IsOptional() const
Definition: util.cpp:721
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:177
const Type m_type
Definition: util.h:181
const std::vector< std::string > m_type_str
Should be empty unless it is supposed to override the auto-generated type strings.
Definition: util.h:196
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:716
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:712
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:189
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:947
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:211
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:729
Optional
Definition: util.h:157
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
std::string ToDescriptionString() const
Definition: util.cpp:583
RPCExamples(std::string examples)
Definition: util.h:334
const std::string m_examples
Definition: util.h:333
RPCExamples()
Definition: util.h:336
const std::string m_description
Definition: util.h:271
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:796
RPCResult(const Type type, const std::string key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:292
@ 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.
@ OBJ_EMPTY
Special type to allow empty OBJ.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:269
RPCResult(const Type type, const std::string key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:303
const std::string m_cond
Definition: util.h:272
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).
RPCResult(const std::string cond, const Type type, const std::string key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:274
const bool m_optional
Definition: util.h:270
RPCResult(const std::string cond, const Type type, const std::string key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:287
const std::string m_key_name
Only used for dicts.
Definition: util.h:268
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:911
const Type m_type
Definition: util.h:267
RPCResults(RPCResult result)
Definition: util.h:322
const std::vector< RPCResult > m_results
Definition: util.h:320
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:324
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:383
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:44
bool typeAny
Definition: util.h:47
UniValueType(UniValue::VType _type)
Definition: util.h:45
UniValue::VType type
Definition: util.h:48
UniValueType()
Definition: util.h:46