Bitcoin Core  22.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 uint256 ParseHashV(const UniValue& v, std::string strName);
76 uint256 ParseHashO(const UniValue& o, std::string strKey);
77 std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
78 std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
79 
87 CAmount AmountFromValue(const UniValue& value, int decimals = 8);
88 
89 using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
90 std::string HelpExampleCli(const std::string& methodname, const std::string& args);
91 std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
92 std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
93 std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
94 
95 CPubKey HexToPubKey(const std::string& hex_in);
96 CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
97 CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
98 
100 
102 unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
103 
105 UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
106 
108 std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
109 
111 std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider);
112 
115 
120 enum class OuterType {
121  ARR,
122  OBJ,
123  NONE, // Only set on first recursion
124 };
125 
126 struct RPCArg {
127  enum class Type {
128  OBJ,
129  ARR,
130  STR,
131  NUM,
132  BOOL,
133  OBJ_USER_KEYS,
134  AMOUNT,
135  STR_HEX,
136  RANGE,
137  };
138 
139  enum class Optional {
141  NO,
153  OMITTED,
154  };
155  using DefaultHint = std::string;
156  using Default = UniValue;
157  using Fallback = std::variant<Optional, /* hint for default value */ DefaultHint, /* default constant value */ Default>;
158  const std::string m_names;
159  const Type m_type;
160  const bool m_hidden;
161  const std::vector<RPCArg> m_inner;
163  const std::string m_description;
164  const std::string m_oneline_description;
165  const std::vector<std::string> m_type_str;
166 
168  const std::string name,
169  const Type type,
170  const Fallback fallback,
171  const std::string description,
172  const std::string oneline_description = "",
173  const std::vector<std::string> type_str = {},
174  const bool hidden = false)
175  : m_names{std::move(name)},
176  m_type{std::move(type)},
177  m_hidden{hidden},
178  m_fallback{std::move(fallback)},
179  m_description{std::move(description)},
180  m_oneline_description{std::move(oneline_description)},
181  m_type_str{std::move(type_str)}
182  {
183  CHECK_NONFATAL(type != Type::ARR && type != Type::OBJ && type != Type::OBJ_USER_KEYS);
184  }
185 
187  const std::string name,
188  const Type type,
189  const Fallback fallback,
190  const std::string description,
191  const std::vector<RPCArg> inner,
192  const std::string oneline_description = "",
193  const std::vector<std::string> type_str = {})
194  : m_names{std::move(name)},
195  m_type{std::move(type)},
196  m_hidden{false},
197  m_inner{std::move(inner)},
198  m_fallback{std::move(fallback)},
199  m_description{std::move(description)},
200  m_oneline_description{std::move(oneline_description)},
201  m_type_str{std::move(type_str)}
202  {
203  CHECK_NONFATAL(type == Type::ARR || type == Type::OBJ || type == Type::OBJ_USER_KEYS);
204  }
205 
206  bool IsOptional() const;
207 
209  std::string GetFirstName() const;
210 
212  std::string GetName() const;
213 
218  std::string ToString(bool oneline) const;
223  std::string ToStringObj(bool oneline) const;
228  std::string ToDescriptionString() const;
229 };
230 
231 struct RPCResult {
232  enum class Type {
233  OBJ,
234  ARR,
235  STR,
236  NUM,
237  BOOL,
238  NONE,
239  ANY,
240  STR_AMOUNT,
241  STR_HEX,
242  OBJ_DYN,
243  ARR_FIXED,
244  NUM_TIME,
245  ELISION,
246  };
247 
248  const Type m_type;
249  const std::string m_key_name;
250  const std::vector<RPCResult> m_inner;
251  const bool m_optional;
252  const std::string m_description;
253  const std::string m_cond;
254 
256  const std::string cond,
257  const Type type,
258  const std::string m_key_name,
259  const bool optional,
260  const std::string description,
261  const std::vector<RPCResult> inner = {})
262  : m_type{std::move(type)},
263  m_key_name{std::move(m_key_name)},
264  m_inner{std::move(inner)},
265  m_optional{optional},
266  m_description{std::move(description)},
267  m_cond{std::move(cond)}
268  {
269  CHECK_NONFATAL(!m_cond.empty());
270  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
271  CHECK_NONFATAL(inner_needed != inner.empty());
272  }
273 
275  const std::string cond,
276  const Type type,
277  const std::string m_key_name,
278  const std::string description,
279  const std::vector<RPCResult> inner = {})
280  : RPCResult{cond, type, m_key_name, false, description, inner} {}
281 
283  const Type type,
284  const std::string m_key_name,
285  const bool optional,
286  const std::string description,
287  const std::vector<RPCResult> inner = {})
288  : m_type{std::move(type)},
289  m_key_name{std::move(m_key_name)},
290  m_inner{std::move(inner)},
291  m_optional{optional},
292  m_description{std::move(description)},
293  m_cond{}
294  {
295  const bool inner_needed{type == Type::ARR || type == Type::ARR_FIXED || type == Type::OBJ || type == Type::OBJ_DYN};
296  CHECK_NONFATAL(inner_needed != inner.empty());
297  }
298 
300  const Type type,
301  const std::string m_key_name,
302  const std::string description,
303  const std::vector<RPCResult> inner = {})
304  : RPCResult{type, m_key_name, false, description, inner} {}
305 
307  void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const;
309  std::string ToStringObj() const;
311  std::string ToDescriptionString() const;
313  bool MatchesType(const UniValue& result) const;
314 };
315 
316 struct RPCResults {
317  const std::vector<RPCResult> m_results;
318 
320  : m_results{{result}}
321  {
322  }
323 
324  RPCResults(std::initializer_list<RPCResult> results)
325  : m_results{results}
326  {
327  }
328 
332  std::string ToDescriptionString() const;
333 };
334 
335 struct RPCExamples {
336  const std::string m_examples;
337  explicit RPCExamples(
338  std::string examples)
339  : m_examples(std::move(examples))
340  {
341  }
342  std::string ToDescriptionString() const;
343 };
344 
346 {
347 public:
348  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples);
349  using RPCMethodImpl = std::function<UniValue(const RPCHelpMan&, const JSONRPCRequest&)>;
350  RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
351 
352  UniValue HandleRequest(const JSONRPCRequest& request) const;
353  std::string ToString() const;
355  UniValue GetArgMap() const;
357  bool IsValidNumArgs(size_t num_args) const;
358  std::vector<std::string> GetArgNames() const;
359 
360  const std::string m_name;
361 
362 private:
364  const std::string m_description;
365  const std::vector<RPCArg> m_args;
368 };
369 
370 #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:363
RPCErrorFromTransactionError
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:340
HexToPubKey
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:192
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:890
OutputType
OutputType
Definition: outputtype.h:18
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:299
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:164
RPCResult::m_cond
const std::string m_cond
Definition: util.h:253
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:366
EXAMPLE_ADDRESS
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:22
RPCHelpMan
Definition: util.h:345
UniValue::VType
VType
Definition: univalue.h:21
FillableSigningProvider
Fillable signing provider that keeps keys in an address->secret map.
Definition: signingprovider.h:91
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
outputtype.h
RPCResults::RPCResults
RPCResults(RPCResult result)
Definition: util.h:319
RPCHelpMan::RPCMethodImpl
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:349
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:90
RPCArg::Optional::NO
@ NO
Required arg.
RPCResults
Definition: util.h:316
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:248
RPCArg::Type
Type
Definition: util.h:127
RPCArg::m_fallback
const Fallback m_fallback
Definition: util.h:162
RPCResult::m_key_name
const std::string m_key_name
Only used for dicts.
Definition: util.h:249
protocol.h
RPCResult::Type::NUM
@ NUM
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:271
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:255
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:992
RPCExamples::m_examples
const std::string m_examples
Definition: util.h:336
ParseDescriptorRange
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:976
RPCArg::m_inner
const std::vector< RPCArg > m_inner
Only used for arrays or dicts.
Definition: util.h:161
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:250
GetServicesNames
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1030
RPCArg
Definition: util.h:126
RPCHelpMan::m_args
const std::vector< RPCArg > m_args
Definition: util.h:365
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:167
UniValue
Definition: univalue.h:19
HelpExampleCliNamed
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:161
OuterType
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:120
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:759
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:282
RPCArg::IsOptional
bool IsOptional() const
Definition: util.cpp:685
RPCHelpMan::m_examples
const RPCExamples m_examples
Definition: util.h:367
RPCHelpMan::GetArgMap
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:654
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:24
RPCTypeCheckObj
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:48
TransactionError
TransactionError
Definition: error.h:22
RPCExamples::RPCExamples
RPCExamples(std::string examples)
Definition: util.h:337
RPCHelpMan::ToString
std::string ToString() const
Definition: util.cpp:602
RPCArg::Type::OBJ
@ OBJ
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
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:581
RPCTypeCheckArgument
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:41
RPCArg::DefaultHint
std::string DefaultHint
Definition: util.h:155
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:564
RPCHelpMan::m_description
const std::string m_description
Definition: util.h:364
RPCResults::ToDescriptionString
std::string ToDescriptionString() const
Return the description string.
Definition: util.cpp:542
RPCArg::m_description
const std::string m_description
Definition: util.h:163
univalue.h
Sections
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:383
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:335
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:226
RPCResult::MatchesType
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:854
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:274
RPCHelpMan::RPCHelpMan
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:493
RPCExamples::ToDescriptionString
std::string ToDescriptionString() const
Definition: util.cpp:559
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:99
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:158
RPCArg::GetName
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:679
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:405
script.h
RPCArg::Optional
Optional
Definition: util.h:139
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:165
RPCResult::m_optional
const bool m_optional
Definition: util.h:251
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:674
RPCHelpMan::GetArgNames
std::vector< std::string > GetArgNames() const
Definition: util.cpp:593
AmountFromValue
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:78
name
const char * name
Definition: rest.cpp:43
ParseHexV
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:103
coinstats.h
RPCArg::m_type
const Type m_type
Definition: util.h:159
CPubKey
An encapsulated public key.
Definition: pubkey.h:32
RPCArg::m_hidden
const bool m_hidden
Definition: util.h:160
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
RPCResult::Type::BOOL
@ BOOL
RPCArgList
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:89
RPCArg::Fallback
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:157
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:325
RPCArg::Type::BOOL
@ BOOL
RPCResults::m_results
const std::vector< RPCResult > m_results
Definition: util.h:317
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:694
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:186
OuterType::ARR
@ ARR
OuterType::OBJ
@ OBJ
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
RPCResult::Type
Type
Definition: util.h:232
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:231
RPCArg::ToString
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:927
JSONRPCTransactionError
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:359
ParseHexO
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:112
HelpExampleRpcNamed
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:180
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:252
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:330
RPCHelpMan::m_name
const std::string m_name
Definition: util.h:360
AddrToPubKey
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:205
RPCResults::RPCResults
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:324
FlatSigningProvider
Definition: signingprovider.h:73