Bitcoin Core  0.20.99
P2P Digital Currency
util.h
Go to the documentation of this file.
1 // Copyright (c) 2017-2020 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 <pubkey.h>
13 #include <rpc/protocol.h>
14 #include <rpc/request.h>
15 #include <script/script.h>
16 #include <script/sign.h>
17 #include <script/standard.h>
18 #include <univalue.h>
19 #include <util/check.h>
20 
21 #include <string>
22 #include <vector>
23 
24 #include <boost/variant.hpp>
25 
30 extern const std::string UNIX_EPOCH_TIME;
31 
36 extern const std::string EXAMPLE_ADDRESS[2];
37 
39 class CPubKey;
40 class CScript;
41 struct Sections;
42 
45 struct UniValueType {
46  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
47  UniValueType() : typeAny(true) {}
48  bool typeAny;
50 };
51 
56 void RPCTypeCheck(const UniValue& params,
57  const std::list<UniValueType>& typesExpected, bool fAllowNull=false);
58 
62 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected);
63 
64 /*
65  Check for expected keys/value types in an Object.
66 */
67 void RPCTypeCheckObj(const UniValue& o,
68  const std::map<std::string, UniValueType>& typesExpected,
69  bool fAllowNull = false,
70  bool fStrict = false);
71 
76 extern uint256 ParseHashV(const UniValue& v, std::string strName);
77 extern uint256 ParseHashO(const UniValue& o, std::string strKey);
78 extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
79 extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
80 
81 CoinStatsHashType ParseHashType(const UniValue& param, const CoinStatsHashType default_type);
82 
83 extern CAmount AmountFromValue(const UniValue& value);
84 extern std::string HelpExampleCli(const std::string& methodname, const std::string& args);
85 extern std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
86 
87 CPubKey HexToPubKey(const std::string& hex_in);
88 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
89 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
90 
92 
94 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
95 
97 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
98 
100 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
101 
103 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider);
104 
107 
112 enum class OuterType {
113  ARR,
114  OBJ,
115  NONE, // Only set on first recursion
116 };
117 
118 struct RPCArg {
119  enum class Type {
120  OBJ,
121  ARR,
122  STR,
123  NUM,
124  BOOL,
125  OBJ_USER_KEYS,
126  AMOUNT,
127  STR_HEX,
128  RANGE,
129  };
130 
131  enum class Optional {
133  NO,
138  OMITTED_NAMED_ARG,
145  OMITTED,
146  };
147  using Fallback = boost::variant<Optional, /* default value for optional args */ std::string>;
148  const std::string m_names;
149  const Type m_type;
150  const std::vector<RPCArg> m_inner;
152  const std::string m_description;
153  const std::string m_oneline_description;
154  const std::vector<std::string> m_type_str;
155 
157  const std::string name,
158  const Type type,
159  const Fallback fallback,
160  const std::string description,
161  const std::string oneline_description = "",
162  const std::vector<std::string> type_str = {})
163  : m_names{std::move(name)},
164  m_type{std::move(type)},
165  m_fallback{std::move(fallback)},
166  m_description{std::move(description)},
167  m_oneline_description{std::move(oneline_description)},
168  m_type_str{std::move(type_str)}
169  {
170  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ);
171  }
172 
174  const std::string name,
175  const Type type,
176  const Fallback fallback,
177  const std::string description,
178  const std::vector<RPCArg> inner,
179  const std::string oneline_description = "",
180  const std::vector<std::string> type_str = {})
181  : m_names{std::move(name)},
182  m_type{std::move(type)},
183  m_inner{std::move(inner)},
184  m_fallback{std::move(fallback)},
185  m_description{std::move(description)},
186  m_oneline_description{std::move(oneline_description)},
187  m_type_str{std::move(type_str)}
188  {
189  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ);
190  }
191 
192  bool IsOptional() const;
193 
195  std::string GetFirstName() const;
196 
198  std::string GetName() const;
199 
204  std::string ToString(bool oneline) const;
209  std::string ToStringObj(bool oneline) const;
214  std::string ToDescriptionString() const;
215 };
216 
217 struct RPCResult {
218  enum class Type {
219  OBJ,
220  ARR,
221  STR,
222  NUM,
223  BOOL,
224  NONE,
225  STR_AMOUNT,
226  STR_HEX,
227  OBJ_DYN,
228  ARR_FIXED,
229  NUM_TIME,
230  ELISION,
231  };
232 
233  const Type m_type;
234  const std::string m_key_name;
235  const std::vector<RPCResult> m_inner;
236  const bool m_optional;
237  const std::string m_description;
238  const std::string m_cond;
239 
241  const std::string cond,
242  const Type type,
243  const std::string m_key_name,
244  const bool optional,
245  const std::string description,
246  const std::vector<RPCResult> inner = {})
247  : m_type{std::move(type)},
248  m_key_name{std::move(m_key_name)},
249  m_inner{std::move(inner)},
250  m_optional{optional},
251  m_description{std::move(description)},
252  m_cond{std::move(cond)}
253  {
254  CHECK_NONFATAL(!m_cond.empty());
255  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
256  CHECK_NONFATAL(inner_needed != inner.empty());
257  }
258 
260  const std::string cond,
261  const Type type,
262  const std::string m_key_name,
263  const std::string description,
264  const std::vector<RPCResult> inner = {})
265  : RPCResult{cond, type, m_key_name, false, description, inner} {}
266 
268  const Type type,
269  const std::string m_key_name,
270  const bool optional,
271  const std::string description,
272  const std::vector<RPCResult> inner = {})
273  : m_type{std::move(type)},
274  m_key_name{std::move(m_key_name)},
275  m_inner{std::move(inner)},
276  m_optional{optional},
277  m_description{std::move(description)},
278  m_cond{}
279  {
280  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
281  CHECK_NONFATAL(inner_needed != inner.empty());
282  }
283 
285  const Type type,
286  const std::string m_key_name,
287  const std::string description,
288  const std::vector<RPCResult> inner = {})
289  : RPCResult{type, m_key_name, false, description, inner} {}
290 
292  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
294  std::string ToStringObj() const;
296  std::string ToDescriptionString() const;
297 };
298 
299 struct RPCResults {
300  const std::vector<RPCResult> m_results;
301 
303  : m_results{{result}}
304  {
305  }
306 
307  RPCResults(std::initializer_list<RPCResult> results)
308  : m_results{results}
309  {
310  }
311 
315  std::string ToDescriptionString() const;
316 };
317 
318 struct RPCExamples {
319  const std::string m_examples;
320  explicit RPCExamples(
321  std::string examples)
322  : m_examples(std::move(examples))
323  {
324  }
325  std::string ToDescriptionString() const;
326 };
327 
329 {
330 public:
331  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
332 
333  std::string ToString() const;
335  bool IsValidNumArgs(size_t num_args) const;
340  inline void Check(const JSONRPCRequest& request) const {
341  if (request.fHelp || !IsValidNumArgs(request.params.size())) {
342  throw std::runtime_error(ToString());
343  }
344  }
345 
346 private:
347  const std::string m_name;
348  const std::string m_description;
349  const std::vector<RPCArg> m_args;
352 };
353 
354 #endif // BITCOIN_RPC_UTIL_H
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:268
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:133
UniValueType(UniValue::VType _type)
Definition: util.h:46
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:23
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:102
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:235
Type
Definition: util.h:119
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:822
const Fallback m_fallback
Definition: util.h:151
ServiceFlags
nServices flags
Definition: protocol.h:270
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:98
RPCResult(const Type type, const std::string m_key_name, const bool optional, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:267
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:325
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:153
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:48
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:158
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:145
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
CAmount AmountFromValue(const UniValue &value)
Definition: util.cpp:77
const std::string m_key_name
Only used for dicts.
Definition: util.h:234
RPCResult(const Type type, const std::string m_key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:284
const RPCExamples m_examples
Definition: util.h:351
boost::variant< Optional, std::string > Fallback
Definition: util.h:147
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:240
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:340
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:150
OutputType
Definition: outputtype.h:17
const std::string m_cond
Definition: util.h:238
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:40
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:282
const Type m_type
Definition: util.h:233
UniValue::VType type
Definition: util.h:49
const std::string m_description
Definition: util.h:348
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:47
CoinStatsHashType
Definition: coinstats.h:17
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:69
Definition: util.h:118
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:179
UniValue params
Definition: request.h:36
const char * name
Definition: rest.cpp:41
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={})
Definition: util.h:156
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:307
An encapsulated public key.
Definition: pubkey.h:30
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:148
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:860
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:273
const std::vector< RPCResult > m_results
Definition: util.h:300
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
const std::vector< RPCArg > m_args
Definition: util.h:349
const std::string m_description
Definition: util.h:152
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:301
const std::string m_examples
Definition: util.h:319
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:154
const RPCResults m_results
Definition: util.h:350
bool fHelp
Definition: request.h:37
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:112
256-bit opaque blob.
Definition: uint256.h:120
UniValueType()
Definition: util.h:47
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
Optional
Definition: util.h:131
const std::string m_description
Definition: util.h:237
CoinStatsHashType ParseHashType(const UniValue &param, const CoinStatsHashType default_type)
Definition: util.cpp:116
TransactionError
Definition: error.h:22
RPCResults(RPCResult result)
Definition: util.h:302
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:259
const Type m_type
Definition: util.h:149
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:173
RPCExamples(std::string examples)
Definition: util.h:320
const bool m_optional
Definition: util.h:236
size_t size() const
Definition: univalue.h:68
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
const std::string m_name
Definition: util.h:347
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:209
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:806
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:45
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:111