Bitcoin Core  21.99.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/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 <variant>
23 #include <vector>
24 
29 extern const std::string UNIX_EPOCH_TIME;
30 
35 extern const std::string EXAMPLE_ADDRESS[2];
36 
38 class CPubKey;
39 class CScript;
40 struct Sections;
41 
44 struct UniValueType {
45  UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
46  UniValueType() : typeAny(true) {}
47  bool typeAny;
49 };
50 
55 void RPCTypeCheck(const UniValue& params,
56  const std::list<UniValueType>& typesExpected, bool fAllowNull=false);
57 
61 void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected);
62 
63 /*
64  Check for expected keys/value types in an Object.
65 */
66 void RPCTypeCheckObj(const UniValue& o,
67  const std::map<std::string, UniValueType>& typesExpected,
68  bool fAllowNull = false,
69  bool fStrict = false);
70 
75 extern uint256 ParseHashV(const UniValue& v, std::string strName);
76 extern uint256 ParseHashO(const UniValue& o, std::string strKey);
77 extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
78 extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
79 
80 extern CAmount AmountFromValue(const UniValue& value);
81 
82 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
83 extern std::string HelpExampleCli(const std::string& methodname, const std::string& args);
84 extern std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
85 extern std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
86 extern std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
87 
88 CPubKey HexToPubKey(const std::string& hex_in);
89 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
90 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
91 
93 
95 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
96 
98 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
99 
101 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
102 
104 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider);
105 
108 
113 enum class OuterType {
114  ARR,
115  OBJ,
116  NONE, // Only set on first recursion
117 };
118 
119 struct RPCArg {
120  enum class Type {
121  OBJ,
122  ARR,
123  STR,
124  NUM,
125  BOOL,
126  OBJ_USER_KEYS,
127  AMOUNT,
128  STR_HEX,
129  RANGE,
130  };
131 
132  enum class Optional {
134  NO,
146  OMITTED,
147  };
148  using Fallback = std::variant<Optional, /* default value for optional args */ std::string>;
149  const std::string m_names;
150  const Type m_type;
151  const bool m_hidden;
152  const std::vector<RPCArg> m_inner;
154  const std::string m_description;
155  const std::string m_oneline_description;
156  const std::vector<std::string> m_type_str;
157 
159  const std::string name,
160  const Type type,
161  const Fallback fallback,
162  const std::string description,
163  const std::string oneline_description = "",
164  const std::vector<std::string> type_str = {},
165  const bool hidden = false)
166  : m_names{std::move(name)},
167  m_type{std::move(type)},
168  m_hidden{hidden},
169  m_fallback{std::move(fallback)},
170  m_description{std::move(description)},
171  m_oneline_description{std::move(oneline_description)},
172  m_type_str{std::move(type_str)}
173  {
174  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ);
175  }
176 
178  const std::string name,
179  const Type type,
180  const Fallback fallback,
181  const std::string description,
182  const std::vector<RPCArg> inner,
183  const std::string oneline_description = "",
184  const std::vector<std::string> type_str = {})
185  : m_names{std::move(name)},
186  m_type{std::move(type)},
187  m_hidden{false},
188  m_inner{std::move(inner)},
189  m_fallback{std::move(fallback)},
190  m_description{std::move(description)},
191  m_oneline_description{std::move(oneline_description)},
192  m_type_str{std::move(type_str)}
193  {
194  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ);
195  }
196 
197  bool IsOptional() const;
198 
200  std::string GetFirstName() const;
201 
203  std::string GetName() const;
204 
209  std::string ToString(bool oneline) const;
214  std::string ToStringObj(bool oneline) const;
219  std::string ToDescriptionString() const;
220 };
221 
222 struct RPCResult {
223  enum class Type {
224  OBJ,
225  ARR,
226  STR,
227  NUM,
228  BOOL,
229  NONE,
230  ANY,
231  STR_AMOUNT,
232  STR_HEX,
233  OBJ_DYN,
234  ARR_FIXED,
235  NUM_TIME,
236  ELISION,
237  };
238 
239  const Type m_type;
240  const std::string m_key_name;
241  const std::vector<RPCResult> m_inner;
242  const bool m_optional;
243  const std::string m_description;
244  const std::string m_cond;
245 
247  const std::string cond,
248  const Type type,
249  const std::string m_key_name,
250  const bool optional,
251  const std::string description,
252  const std::vector<RPCResult> inner = {})
253  : m_type{std::move(type)},
254  m_key_name{std::move(m_key_name)},
255  m_inner{std::move(inner)},
256  m_optional{optional},
257  m_description{std::move(description)},
258  m_cond{std::move(cond)}
259  {
260  CHECK_NONFATAL(!m_cond.empty());
261  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
262  CHECK_NONFATAL(inner_needed != inner.empty());
263  }
264 
266  const std::string cond,
267  const Type type,
268  const std::string m_key_name,
269  const std::string description,
270  const std::vector<RPCResult> inner = {})
271  : RPCResult{cond, type, m_key_name, false, description, inner} {}
272 
274  const Type type,
275  const std::string m_key_name,
276  const bool optional,
277  const std::string description,
278  const std::vector<RPCResult> inner = {})
279  : m_type{std::move(type)},
280  m_key_name{std::move(m_key_name)},
281  m_inner{std::move(inner)},
282  m_optional{optional},
283  m_description{std::move(description)},
284  m_cond{}
285  {
286  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
287  CHECK_NONFATAL(inner_needed != inner.empty());
288  }
289 
291  const Type type,
292  const std::string m_key_name,
293  const std::string description,
294  const std::vector<RPCResult> inner = {})
295  : RPCResult{type, m_key_name, false, description, inner} {}
296 
298  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
300  std::string ToStringObj() const;
302  std::string ToDescriptionString() const;
304  bool MatchesType(const UniValue& result) const;
305 };
306 
307 struct RPCResults {
308  const std::vector<RPCResult> m_results;
309 
311  : m_results{{result}}
312  {
313  }
314 
315  RPCResults(std::initializer_list<RPCResult> results)
316  : m_results{results}
317  {
318  }
319 
323  std::string ToDescriptionString() const;
324 };
325 
326 struct RPCExamples {
327  const std::string m_examples;
328  explicit RPCExamples(
329  std::string examples)
330  : m_examples(std::move(examples))
331  {
332  }
333  std::string ToDescriptionString() const;
334 };
335 
337 {
338 public:
339  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
340  using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
341  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
342 
343  UniValue HandleRequest(const JSONRPCRequest& request) const;
344  std::string ToString() const;
346  UniValue GetArgMap() const;
348  bool IsValidNumArgs(size_t num_args) const;
349  std::vector<std::string> GetArgNames() const;
350 
351  const std::string m_name;
352 
353 private:
355  const std::string m_description;
356  const std::vector<RPCArg> m_args;
359 };
360 
361 #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:354
RPCErrorFromTransactionError
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:329
HexToPubKey
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:191
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:850
OutputType
OutputType
Definition: outputtype.h:17
UniValueType::UniValueType
UniValueType(UniValue::VType _type)
Definition: util.h:45
RPCResult::RPCResult
RPCResult(const Type type, const std::string m_key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:290
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:155
RPCResult::m_cond
const std::string m_cond
Definition: util.h:244
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
OuterType::NONE
@ NONE
RPCHelpMan::m_results
const RPCResults m_results
Definition: util.h:357
EXAMPLE_ADDRESS
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
RPCHelpMan
Definition: util.h:336
UniValue::VType
VType
Definition: univalue.h:21
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:63
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:155
outputtype.h
RPCResults::RPCResults
RPCResults(RPCResult result)
Definition: util.h:310
RPCHelpMan::RPCMethodImpl
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:340
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
RPCArg::Optional::NO
@ NO
Required arg.
RPCResults
Definition: util.h:307
RPCArg::Type::STR
@ STR
UniValueType::type
UniValue::VType type
Definition: util.h:48
RPCArg::Type::ARR
@ ARR
RPCResult::m_type
const Type m_type
Definition: util.h:239
RPCArg::Type
Type
Definition: util.h:120
RPCArg::m_fallback
const Fallback m_fallback
Definition: util.h:153
RPCResult::m_key_name
const std::string m_key_name
Only used for dicts.
Definition: util.h:240
protocol.h
RPCResult::Type::NUM
@ NUM
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:269
RPCResult::RPCResult
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:246
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:952
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:936
RPCArg::m_inner
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:152
pubkey.h
RPCArg::Type::OBJ_USER_KEYS
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
UniValueType::typeAny
bool typeAny
Definition: util.h:47
RPCResult::m_inner
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:241
GetServicesNames
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:990
RPCArg
Definition: util.h:119
RPCHelpMan::m_args
const std::vector< RPCArg > m_args
Definition: util.h:356
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:158
UniValue
Definition: univalue.h:19
HelpExampleCliNamed
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:160
OuterType
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:113
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:719
RPCResult::Type::ARR_FIXED
@ ARR_FIXED
Special array that has a fixed number of entries.
transaction.h
RPCArg::Type::NUM
@ NUM
RPCResult::RPCResult
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:273
RPCArg::IsOptional
bool IsOptional() const
Definition: util.cpp:647
RPCHelpMan::m_examples
const RPCExamples m_examples
Definition: util.h:358
RPCHelpMan::GetArgMap
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:616
UniValueType
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:44
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:23
RPCTypeCheckObj
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:47
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:564
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:543
RPCTypeCheckArgument
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:40
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::HandleRequest
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:526
RPCHelpMan::m_description
const std::string m_description
Definition: util.h:355
RPCResults::ToDescriptionString
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:504
RPCArg::m_description
const std::string m_description
Definition: util.h:154
univalue.h
Sections
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:372
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
sign.h
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
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:20
AddAndGetMultisigDestination
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:225
RPCArg::Fallback
std::variant< Optional, std::string > Fallback
Definition: util.h:148
RPCResult::MatchesType
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:814
RPCResult::Type::STR
@ STR
RPCResult::RPCResult
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:265
RPCHelpMan::RPCHelpMan
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:482
RPCExamples::ToDescriptionString
std::string ToDescriptionString() const
Definition: util.cpp:521
uint256
256-bit opaque blob.
Definition: uint256.h:124
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:98
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:149
RPCArg::GetName
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:641
RPCResult::Type::ANY
@ ANY
Special type to disable type checks (for testing only)
request.h
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
RPCArg::Optional
Optional
Definition: util.h:132
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:156
RPCResult::m_optional
const bool m_optional
Definition: util.h:242
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:636
RPCHelpMan::GetArgNames
std::vector< std::string > GetArgNames() const
Definition: util.cpp:555
name
const char * name
Definition: rest.cpp:43
ParseHexV
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:102
coinstats.h
AmountFromValue
CAmount AmountFromValue(const UniValue &value)
Definition: util.cpp:77
RPCArg::m_type
const Type m_type
Definition: util.h:150
CPubKey
An encapsulated public key.
Definition: pubkey.h:31
RPCArg::m_hidden
const bool m_hidden
Definition: util.h:151
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:173
RPCResult::Type::BOOL
@ BOOL
RPCArgList
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:82
RPCErrorCode
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:23
UniValueType::UniValueType
UniValueType()
Definition: util.h:46
DescribeAddress
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:314
RPCArg::Type::BOOL
@ BOOL
RPCResults::m_results
const std::vector< RPCResult > m_results
Definition: util.h:308
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:656
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:177
OuterType::ARR
@ ARR
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
OuterType::OBJ
@ OBJ
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
RPCResult::Type
Type
Definition: util.h:223
script.h
RPCArg::Type::AMOUNT
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
JSONRPCRequest
Definition: request.h:28
RPCResult
Definition: util.h:222
RPCArg::ToString
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:887
JSONRPCTransactionError
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:348
ParseHexO
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:111
HelpExampleRpcNamed
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:179
RPCResult::Type::STR_AMOUNT
@ STR_AMOUNT
Special string to represent a floating point amount.
RPCResult::m_description
const std::string m_description
Definition: util.h:243
ParseConfirmTarget
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:319
RPCHelpMan::m_name
const std::string m_name
Definition: util.h:351
AddrToPubKey
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:204
RPCResults::RPCResults
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:315
FlatSigningProvider
Definition: signingprovider.h:47