Bitcoin ABC  0.26.3
P2P Digital Currency
util.h
Go to the documentation of this file.
1 // Copyright (c) 2017-2019 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/coinstats.h>
9 #include <node/transaction.h>
10 #include <outputtype.h>
11 #include <protocol.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> // For CTxDestination
17 #include <univalue.h>
18 #include <util/check.h>
19 
20 #include <boost/variant.hpp>
21 
22 #include <string>
23 #include <vector>
24 
25 class CChainParams;
27 class CPubKey;
28 class CScript;
29 struct Sections;
30 
35 extern const std::string UNIX_EPOCH_TIME;
36 
40 extern const std::string EXAMPLE_ADDRESS;
41 
46 struct UniValueType {
47  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
48  UniValueType() : typeAny(true) {}
49  bool typeAny;
51 };
52 
58 void RPCTypeCheck(const UniValue &params,
59  const std::list<UniValueType> &typesExpected,
60  bool fAllowNull = false);
61 
65 void RPCTypeCheckArgument(const UniValue &value,
66  const UniValueType &typeExpected);
67 
71 void RPCTypeCheckObj(const UniValue &o,
72  const std::map<std::string, UniValueType> &typesExpected,
73  bool fAllowNull = false, bool fStrict = false);
74 
78 extern uint256 ParseHashV(const UniValue &v, std::string strName);
79 extern uint256 ParseHashO(const UniValue &o, std::string strKey);
80 extern std::vector<uint8_t> ParseHexV(const UniValue &v, std::string strName);
81 extern std::vector<uint8_t> ParseHexO(const UniValue &o, std::string strKey);
82 
83 extern Amount AmountFromValue(const UniValue &value);
84 
85 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
86 extern std::string HelpExampleCli(const std::string &methodname,
87  const std::string &args);
88 extern std::string HelpExampleCliNamed(const std::string &methodname,
89  const RPCArgList &args);
90 extern std::string HelpExampleRpc(const std::string &methodname,
91  const std::string &args);
92 extern std::string HelpExampleRpcNamed(const std::string &methodname,
93  const RPCArgList &args);
94 
95 CPubKey HexToPubKey(const std::string &hex_in);
96 CPubKey AddrToPubKey(const CChainParams &chainparams,
97  const FillableSigningProvider &keystore,
98  const std::string &addr_in);
100  const std::vector<CPubKey> &pubkeys,
101  OutputType type,
102  FillableSigningProvider &keystore,
103  CScript &script_out);
104 
106 std::string GetAllOutputTypes();
107 
110  const std::string &err_string = "");
111 
113 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value);
114 
119 std::vector<CScript>
120 EvalDescriptorStringOrObject(const UniValue &scanobject,
121  FlatSigningProvider &provider);
122 
128 
133 enum class OuterType {
134  ARR,
135  OBJ,
136  NONE, // Only set on first recursion
137 };
138 
139 struct RPCArg {
140  enum class Type {
141  OBJ,
142  ARR,
143  STR,
144  NUM,
145  BOOL,
152  AMOUNT,
154  STR_HEX,
156  RANGE,
157  };
158 
159  enum class Optional {
161  NO,
173  OMITTED,
174  };
175  using Fallback =
176  boost::variant<Optional,
177  /* default value for optional args */ std::string>;
178 
181  const std::string m_names;
182  const Type m_type;
183  const bool m_hidden;
185  const std::vector<RPCArg> m_inner;
187  const std::string m_description;
190  const std::string m_oneline_description;
191 
197  const std::vector<std::string> m_type_str;
198 
199  RPCArg(const std::string name, const Type type, const Fallback fallback,
200  const std::string description,
201  const std::string oneline_description = "",
202  const std::vector<std::string> type_str = {},
203  const bool hidden = false)
204  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{hidden},
205  m_fallback{std::move(fallback)}, m_description{std::move(
206  description)},
207  m_oneline_description{std::move(oneline_description)},
208  m_type_str{std::move(type_str)} {
209  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ);
210  }
211 
212  RPCArg(const std::string name, const Type type, const Fallback fallback,
213  const std::string description, const std::vector<RPCArg> inner,
214  const std::string oneline_description = "",
215  const std::vector<std::string> type_str = {})
216  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{false},
217  m_inner{std::move(inner)}, m_fallback{std::move(fallback)},
218  m_description{std::move(description)},
219  m_oneline_description{std::move(oneline_description)},
220  m_type_str{std::move(type_str)} {
221  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ);
222  }
223 
224  bool IsOptional() const;
225 
227  std::string GetFirstName() const;
228 
230  std::string GetName() const;
231 
237  std::string ToString(bool oneline) const;
242  std::string ToStringObj(bool oneline) const;
247  std::string ToDescriptionString() const;
248 };
249 
250 struct RPCResult {
251  enum class Type {
252  OBJ,
253  ARR,
254  STR,
255  NUM,
256  BOOL,
257  NONE,
258  ANY,
259  STR_AMOUNT,
260  STR_HEX,
261  OBJ_DYN,
262  OBJ_EMPTY,
263  ARR_FIXED,
264  NUM_TIME,
265  ELISION,
266  };
267 
268  const Type m_type;
269  const std::string m_key_name;
270  const std::vector<RPCResult> m_inner;
271  const bool m_optional;
272  const std::string m_description;
273  const std::string m_cond;
274 
275  RPCResult(const std::string cond, const Type type,
276  const std::string key_name, const bool optional,
277  const std::string description,
278  const std::vector<RPCResult> inner = {})
279  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
280  m_inner{std::move(inner)}, m_optional{optional},
281  m_description{std::move(description)}, m_cond{std::move(cond)} {
282  CHECK_NONFATAL(!m_cond.empty());
283  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
284  type == Type::OBJ || type == Type::OBJ_DYN};
285  CHECK_NONFATAL(inner_needed != inner.empty());
286  }
287 
288  RPCResult(const std::string cond, const Type type,
289  const std::string key_name, const std::string description,
290  const std::vector<RPCResult> inner = {})
291  : RPCResult{cond, type, key_name, false, description, inner} {}
292 
293  RPCResult(const Type type, const std::string key_name, const bool optional,
294  const std::string description,
295  const std::vector<RPCResult> inner = {})
296  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
297  m_inner{std::move(inner)}, m_optional{optional},
298  m_description{std::move(description)}, m_cond{} {
299  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
300  type == Type::OBJ || type == Type::OBJ_DYN};
301  CHECK_NONFATAL(inner_needed != inner.empty());
302  }
303 
304  RPCResult(const Type type, const std::string key_name,
305  const std::string description,
306  const std::vector<RPCResult> inner = {})
307  : RPCResult{type, key_name, false, description, inner} {}
308 
310  void ToSections(Sections &sections, OuterType outer_type = OuterType::NONE,
311  const int current_indent = 0) const;
313  std::string ToStringObj() const;
315  std::string ToDescriptionString() const;
317  bool MatchesType(const UniValue &result) const;
318 };
319 
320 struct RPCResults {
321  const std::vector<RPCResult> m_results;
322 
323  RPCResults(RPCResult result) : m_results{{result}} {}
324 
325  RPCResults(std::initializer_list<RPCResult> results) : m_results{results} {}
326 
330  std::string ToDescriptionString() const;
331 };
332 
333 struct RPCExamples {
334  const std::string m_examples;
335  explicit RPCExamples(std::string examples)
336  : m_examples(std::move(examples)) {}
337  RPCExamples() : m_examples(std::move("")) {}
338  std::string ToDescriptionString() const;
339 };
340 
341 class RPCHelpMan {
342 public:
343  RPCHelpMan(std::string name, std::string description,
344  std::vector<RPCArg> args, RPCResults results,
345  RPCExamples examples);
346  using RPCMethodImpl = std::function<UniValue(
347  const RPCHelpMan &, const Config &config, const JSONRPCRequest &)>;
348  RPCHelpMan(std::string name, std::string description,
349  std::vector<RPCArg> args, RPCResults results,
350  RPCExamples examples, RPCMethodImpl fun);
351 
352  UniValue HandleRequest(const Config &config,
353  const JSONRPCRequest &request) const;
354  std::string ToString() const;
359  UniValue GetArgMap() const;
361  bool IsValidNumArgs(size_t num_args) const;
362  std::vector<std::string> GetArgNames() const;
363 
364  const std::string m_name;
365 
366 private:
368  const std::string m_description;
369  const std::vector<RPCArg> m_args;
372 };
373 
374 #endif // BITCOIN_RPC_UTIL_H
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
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:371
std::vector< std::string > GetArgNames() const
Definition: util.cpp:590
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:512
const std::string m_description
Definition: util.h:368
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:579
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:347
const RPCMethodImpl m_fun
Definition: util.h:367
const std::string m_name
Definition: util.h:364
const RPCResults m_results
Definition: util.h:370
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
Definition: util.cpp:559
const std::vector< RPCArg > m_args
Definition: util.h:369
std::string ToString() const
Definition: util.cpp:598
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:666
256-bit opaque blob.
Definition: uint256.h:127
TransactionError
Definition: error.h:22
OutputType
Definition: outputtype.h:17
ServiceFlags
nServices flags.
Definition: protocol.h:338
const char * name
Definition: rest.cpp:50
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:1011
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:121
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:177
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:85
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1075
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:260
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:203
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:43
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:360
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:82
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:26
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:341
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:135
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:23
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:133
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:1028
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:194
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:22
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:53
std::string GetAllOutputTypes()
Definition: util.cpp:332
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:218
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:232
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:117
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:100
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:182
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:328
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:93
Definition: amount.h:19
Definition: util.h:139
Type
Definition: util.h:140
@ 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:185
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:181
const Fallback m_fallback
Definition: util.h:186
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:954
boost::variant< Optional, std::string > Fallback
Definition: util.h:177
const bool m_hidden
Definition: util.h:183
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:199
const std::string m_description
Definition: util.h:187
bool IsOptional() const
Definition: util.cpp:694
const Type m_type
Definition: util.h:182
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:197
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:689
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:685
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:190
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:916
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:212
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:702
Optional
Definition: util.h:159
@ 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:555
RPCExamples(std::string examples)
Definition: util.h:335
const std::string m_examples
Definition: util.h:334
RPCExamples()
Definition: util.h:337
const std::string m_description
Definition: util.h:272
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:765
RPCResult(const Type type, const std::string key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:293
@ 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:270
RPCResult(const Type type, const std::string key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:304
const std::string m_cond
Definition: util.h:273
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:275
const bool m_optional
Definition: util.h:271
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:288
const std::string m_key_name
Only used for dicts.
Definition: util.h:269
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:880
const Type m_type
Definition: util.h:268
RPCResults(RPCResult result)
Definition: util.h:323
const std::vector< RPCResult > m_results
Definition: util.h:321
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:325
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:385
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:46
bool typeAny
Definition: util.h:49
UniValueType(UniValue::VType _type)
Definition: util.h:47
UniValue::VType type
Definition: util.h:50
UniValueType()
Definition: util.h:48