Bitcoin ABC  0.24.7
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 
84  const CoinStatsHashType default_type);
85 
86 extern Amount AmountFromValue(const UniValue &value);
87 extern std::string HelpExampleCli(const std::string &methodname,
88  const std::string &args);
89 extern std::string HelpExampleRpc(const std::string &methodname,
90  const std::string &args);
91 
92 CPubKey HexToPubKey(const std::string &hex_in);
93 CPubKey AddrToPubKey(const CChainParams &chainparams,
94  const FillableSigningProvider &keystore,
95  const std::string &addr_in);
97  const std::vector<CPubKey> &pubkeys,
98  OutputType type,
99  FillableSigningProvider &keystore,
100  CScript &script_out);
101 
103 std::string GetAllOutputTypes();
104 
107  const std::string &err_string = "");
108 
110 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue &value);
111 
116 std::vector<CScript>
117 EvalDescriptorStringOrObject(const UniValue &scanobject,
118  FlatSigningProvider &provider);
119 
125 
130 enum class OuterType {
131  ARR,
132  OBJ,
133  NONE, // Only set on first recursion
134 };
135 
136 struct RPCArg {
137  enum class Type {
138  OBJ,
139  ARR,
140  STR,
141  NUM,
142  BOOL,
149  AMOUNT,
151  STR_HEX,
153  RANGE,
154  };
155 
156  enum class Optional {
158  NO,
170  OMITTED,
171  };
172  using Fallback =
173  boost::variant<Optional,
174  /* default value for optional args */ std::string>;
175 
178  const std::string m_names;
179  const Type m_type;
180  const bool m_hidden;
182  const std::vector<RPCArg> m_inner;
184  const std::string m_description;
187  const std::string m_oneline_description;
188 
194  const std::vector<std::string> m_type_str;
195 
196  RPCArg(const std::string name, const Type type, const Fallback fallback,
197  const std::string description,
198  const std::string oneline_description = "",
199  const std::vector<std::string> type_str = {},
200  const bool hidden = false)
201  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{hidden},
202  m_fallback{std::move(fallback)}, m_description{std::move(
203  description)},
204  m_oneline_description{std::move(oneline_description)},
205  m_type_str{std::move(type_str)} {
206  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ);
207  }
208 
209  RPCArg(const std::string name, const Type type, const Fallback fallback,
210  const std::string description, const std::vector<RPCArg> inner,
211  const std::string oneline_description = "",
212  const std::vector<std::string> type_str = {})
213  : m_names{std::move(name)}, m_type{std::move(type)}, m_hidden{false},
214  m_inner{std::move(inner)}, m_fallback{std::move(fallback)},
215  m_description{std::move(description)},
216  m_oneline_description{std::move(oneline_description)},
217  m_type_str{std::move(type_str)} {
218  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ);
219  }
220 
221  bool IsOptional() const;
222 
224  std::string GetFirstName() const;
225 
227  std::string GetName() const;
228 
234  std::string ToString(bool oneline) const;
239  std::string ToStringObj(bool oneline) const;
244  std::string ToDescriptionString() const;
245 };
246 
247 struct RPCResult {
248  enum class Type {
249  OBJ,
250  ARR,
251  STR,
252  NUM,
253  BOOL,
254  NONE,
255  STR_AMOUNT,
256  STR_HEX,
257  OBJ_DYN,
258  ARR_FIXED,
259  NUM_TIME,
260  ELISION,
261  };
262 
263  const Type m_type;
264  const std::string m_key_name;
265  const std::vector<RPCResult> m_inner;
266  const bool m_optional;
267  const std::string m_description;
268  const std::string m_cond;
269 
270  RPCResult(const std::string cond, const Type type,
271  const std::string key_name, const bool optional,
272  const std::string description,
273  const std::vector<RPCResult> inner = {})
274  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
275  m_inner{std::move(inner)}, m_optional{optional},
276  m_description{std::move(description)}, m_cond{std::move(cond)} {
277  CHECK_NONFATAL(!m_cond.empty());
278  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
279  type == Type::OBJ || type == Type::OBJ_DYN};
280  CHECK_NONFATAL(inner_needed != inner.empty());
281  }
282 
283  RPCResult(const std::string cond, const Type type,
284  const std::string key_name, const std::string description,
285  const std::vector<RPCResult> inner = {})
286  : RPCResult{cond, type, key_name, false, description, inner} {}
287 
288  RPCResult(const Type type, const std::string key_name, const bool optional,
289  const std::string description,
290  const std::vector<RPCResult> inner = {})
291  : m_type{std::move(type)}, m_key_name{std::move(key_name)},
292  m_inner{std::move(inner)}, m_optional{optional},
293  m_description{std::move(description)}, m_cond{} {
294  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED ||
295  type == Type::OBJ || type == Type::OBJ_DYN};
296  CHECK_NONFATAL(inner_needed != inner.empty());
297  }
298 
299  RPCResult(const Type type, const std::string key_name,
300  const std::string description,
301  const std::vector<RPCResult> inner = {})
302  : RPCResult{type, key_name, false, description, inner} {}
303 
305  void ToSections(Sections &sections, OuterType outer_type = OuterType::NONE,
306  const int current_indent = 0) const;
308  std::string ToStringObj() const;
310  std::string ToDescriptionString() const;
311 };
312 
313 struct RPCResults {
314  const std::vector<RPCResult> m_results;
315 
316  RPCResults(RPCResult result) : m_results{{result}} {}
317 
318  RPCResults(std::initializer_list<RPCResult> results) : m_results{results} {}
319 
323  std::string ToDescriptionString() const;
324 };
325 
326 struct RPCExamples {
327  const std::string m_examples;
328  explicit RPCExamples(std::string examples)
329  : m_examples(std::move(examples)) {}
330  RPCExamples() : m_examples(std::move("")) {}
331  std::string ToDescriptionString() const;
332 };
333 
334 class RPCHelpMan {
335 public:
336  RPCHelpMan(std::string name, std::string description,
337  std::vector<RPCArg> args, RPCResults results,
338  RPCExamples examples);
339  using RPCMethodImpl = std::function<UniValue(
340  const RPCHelpMan &, const Config &config, const JSONRPCRequest &)>;
341  RPCHelpMan(std::string name, std::string description,
342  std::vector<RPCArg> args, RPCResults results,
343  RPCExamples examples, RPCMethodImpl fun);
344 
345  std::string ToString() const;
347  const JSONRPCRequest &request) {
348  Check(request);
349  return m_fun(*this, config, request);
350  }
352  bool IsValidNumArgs(size_t num_args) const;
357  inline void Check(const JSONRPCRequest &request) const {
358  if (request.fHelp || !IsValidNumArgs(request.params.size())) {
359  throw std::runtime_error(ToString());
360  }
361  }
362 
363  std::vector<std::string> GetArgNames() const;
364 
365  const std::string m_name;
366 
367 private:
369  const std::string m_description;
370  const std::vector<RPCArg> m_args;
373 };
374 
375 #endif // BITCOIN_RPC_UTIL_H
RPCResult::ToDescriptionString
std::string ToDescriptionString() const
Return the description string, including the result type.
RPCHelpMan::m_fun
const RPCMethodImpl m_fun
Definition: util.h:368
RPCErrorFromTransactionError
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:295
ParseHexV
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:120
HexToPubKey
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:172
RPCResult::Type::ELISION
@ ELISION
Special type to denote elision (...)
RPCArg::ToStringObj
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:781
OutputType
OutputType
Definition: outputtype.h:17
RPCResult::RPCResult
RPCResult(const Type type, const std::string key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:299
UniValueType::UniValueType
UniValueType(UniValue::VType _type)
Definition: util.h:47
check.h
RPCArg::m_oneline_description
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:187
RPCResult::m_cond
const std::string m_cond
Definition: util.h:268
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
OuterType::NONE
@ NONE
RPCHelpMan::m_results
const RPCResults m_results
Definition: util.h:371
AddrToPubKey
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:186
ParseHexO
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:134
RPCExamples::RPCExamples
RPCExamples()
Definition: util.h:330
RPCHelpMan
Definition: util.h:334
UniValue::VType
VType
Definition: univalue.h:27
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:76
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:157
RPCResult::RPCResult
RPCResult(const Type type, const std::string key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:288
outputtype.h
RPCResults::RPCResults
RPCResults(RPCResult result)
Definition: util.h:316
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:99
RPCArg::Optional::NO
@ NO
Required arg.
RPCResults
Definition: util.h:313
RPCArg::Type::STR
@ STR
ParseHashType
CoinStatsHashType ParseHashType(const UniValue &param, const CoinStatsHashType default_type)
Definition: util.cpp:138
UniValueType::type
UniValue::VType type
Definition: util.h:50
RPCArg::Type::ARR
@ ARR
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
RPCResult::m_type
const Type m_type
Definition: util.h:263
RPCArg::Type
Type
Definition: util.h:137
RPCArg::m_fallback
const Fallback m_fallback
Definition: util.h:183
RPCResult::m_key_name
const std::string m_key_name
Only used for dicts.
Definition: util.h:264
protocol.h
RPCResult::Type::NUM
@ NUM
ServiceFlags
ServiceFlags
nServices flags.
Definition: protocol.h:314
EvalDescriptorStringOrObject
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:893
RPCExamples::m_examples
const std::string m_examples
Definition: util.h:327
ParseDescriptorRange
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:876
AmountFromValue
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:81
RPCArg::m_inner
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:182
RPCArg::Type::OBJ_USER_KEYS
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g.
UniValueType::typeAny
bool typeAny
Definition: util.h:49
RPCResult::m_inner
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:265
RPCArg::Fallback
boost::variant< Optional, std::string > Fallback
Definition: util.h:174
GetServicesNames
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:940
RPCArg
Definition: util.h:136
RPCHelpMan::m_args
const std::vector< RPCArg > m_args
Definition: util.h:370
RPCArg::RPCArg
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:196
UniValue
Definition: univalue.h:23
RPCHelpMan::RPCMethodImpl
std::function< UniValue(const RPCHelpMan &, const Config &config, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:340
OuterType
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:130
RPCResult::ToSections
void ToSections(Sections &sections, OuterType outer_type=OuterType::NONE, const int current_indent=0) const
Append the sections of the result.
Definition: util.cpp:675
RPCResult::Type::ARR_FIXED
@ ARR_FIXED
Special array that has a fixed number of entries.
transaction.h
RPCArg::Type::NUM
@ NUM
RPCArg::IsOptional
bool IsOptional() const
Definition: util.cpp:604
RPCHelpMan::m_examples
const RPCExamples m_examples
Definition: util.h:372
UniValueType
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:46
Config
Definition: config.h:17
RPCTypeCheck
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:25
RPCTypeCheckObj
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:52
TransactionError
TransactionError
Definition: error.h:22
RPCExamples::RPCExamples
RPCExamples(std::string examples)
Definition: util.h:328
RPCHelpMan::ToString
std::string ToString() const
Definition: util.cpp:527
RPCArg::Type::OBJ
@ OBJ
RPCHelpMan::IsValidNumArgs
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:508
RPCTypeCheckArgument
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:42
RPCArg::Optional::OMITTED_NAMED_ARG
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
RPCResult::ToStringObj
std::string ToStringObj() const
Return the type string of the result when it is in an object (dict).
RPCArg::Type::STR_HEX
@ STR_HEX
Special type that is a STR with only hex chars.
RPCResult::Type::OBJ
@ OBJ
RPCResult::Type::NONE
@ NONE
RPCHelpMan::m_description
const std::string m_description
Definition: util.h:369
RPCResult::RPCResult
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:270
RPCResults::ToDescriptionString
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:489
RPCArg::m_description
const std::string m_description
Definition: util.h:184
univalue.h
Sections
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:339
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
sign.h
RPCHelpMan::HandleRequest
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request)
Definition: util.h:346
JSONRPCRequest::fHelp
bool fHelp
Definition: request.h:38
standard.h
RPCExamples
Definition: util.h:326
UNIX_EPOCH_TIME
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:21
AddAndGetMultisigDestination
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:214
RPCResult::RPCResult
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:283
RPCResult::Type::STR
@ STR
RPCHelpMan::RPCHelpMan
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:466
RPCExamples::ToDescriptionString
std::string ToDescriptionString() const
Definition: util.cpp:504
uint256
256-bit opaque blob.
Definition: uint256.h:127
RPCResult::Type::NUM_TIME
@ NUM_TIME
Special numeric to denote unix epoch time.
ParseHashO
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:116
RPCResult::Type::ARR
@ ARR
RPCArg::m_names
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:178
RPCArg::GetName
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:599
Amount
Definition: amount.h:19
request.h
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
RPCArg::Optional
Optional
Definition: util.h:156
RPCArg::m_type_str
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:194
RPCResult::m_optional
const bool m_optional
Definition: util.h:266
RPCArg::Type::RANGE
@ RANGE
Special type that is a NUM or [NUM,NUM].
RPCArg::GetFirstName
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:595
RPCHelpMan::GetArgNames
std::vector< std::string > GetArgNames() const
Definition: util.cpp:519
JSONRPCRequest::params
UniValue params
Definition: request.h:37
name
const char * name
Definition: rest.cpp:43
coinstats.h
EXAMPLE_ADDRESS
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:22
RPCArg::m_type
const Type m_type
Definition: util.h:179
CPubKey
An encapsulated public key.
Definition: pubkey.h:31
RPCArg::m_hidden
const bool m_hidden
Definition: util.h:180
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:162
RPCResult::Type::BOOL
@ BOOL
RPCErrorCode
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:22
GetAllOutputTypes
std::string GetAllOutputTypes()
Definition: util.cpp:286
UniValueType::UniValueType
UniValueType()
Definition: util.h:48
DescribeAddress
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:282
RPCArg::Type::BOOL
@ BOOL
RPCResults::m_results
const std::vector< RPCResult > m_results
Definition: util.h:314
RPCArg::Optional::OMITTED
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
RPCArg::ToDescriptionString
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:612
RPCArg::RPCArg
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:209
OuterType::ARR
@ ARR
OuterType::OBJ
@ OBJ
RPCHelpMan::Check
void Check(const JSONRPCRequest &request) const
Check if the given request is valid according to this command or if the user is asking for help infor...
Definition: util.h:357
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
UniValue::size
size_t size() const
Definition: univalue.h:80
RPCResult::Type
Type
Definition: util.h:248
script.h
RPCArg::Type::AMOUNT
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
JSONRPCRequest
Definition: request.h:33
RPCResult
Definition: util.h:247
RPCArg::ToString
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:819
JSONRPCTransactionError
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:314
RPCResult::Type::STR_AMOUNT
@ STR_AMOUNT
Special string to represent a floating point amount.
CoinStatsHashType
CoinStatsHashType
Definition: coinstats.h:18
RPCResult::m_description
const std::string m_description
Definition: util.h:267
RPCHelpMan::m_name
const std::string m_name
Definition: util.h:365
CTxDestination
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:132
RPCResults::RPCResults
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:318
FlatSigningProvider
Definition: signingprovider.h:58