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
29extern const std::string UNIX_EPOCH_TIME;
30
35extern const std::string EXAMPLE_ADDRESS[2];
36
38class CPubKey;
39class CScript;
40struct Sections;
41
45 UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
46 UniValueType() : typeAny(true) {}
47 bool typeAny;
49};
50
55void RPCTypeCheck(const UniValue& params,
56 const std::list<UniValueType>& typesExpected, bool fAllowNull=false);
57
61void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected);
62
63/*
64 Check for expected keys/value types in an Object.
65*/
66void RPCTypeCheckObj(const UniValue& o,
67 const std::map<std::string, UniValueType>& typesExpected,
68 bool fAllowNull = false,
69 bool fStrict = false);
70
75uint256 ParseHashV(const UniValue& v, std::string strName);
76uint256 ParseHashO(const UniValue& o, std::string strKey);
77std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
78std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
79
87CAmount AmountFromValue(const UniValue& value, int decimals = 8);
88
89using RPCArgList = std::vector<std::pair<std::string, UniValue>>;
90std::string HelpExampleCli(const std::string& methodname, const std::string& args);
91std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args);
92std::string HelpExampleRpc(const std::string& methodname, const std::string& args);
93std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args);
94
95CPubKey HexToPubKey(const std::string& hex_in);
96CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
97CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FillableSigningProvider& keystore, CScript& script_out);
98
100
102unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target);
103
105UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string = "");
106
108std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
109
111std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider);
112
115
120enum class OuterType {
121 ARR,
122 OBJ,
123 NONE, // Only set on first recursion
124};
125
126struct RPCArg {
127 enum class Type {
128 OBJ,
129 ARR,
130 STR,
131 NUM,
132 BOOL,
134 AMOUNT,
135 STR_HEX,
136 RANGE,
137 };
138
139 enum class Optional {
141 NO,
153 OMITTED,
154 };
155 using DefaultHint = std::string;
157 using Fallback = std::variant<Optional, /* hint for default value */ DefaultHint, /* default constant value */ Default>;
158 const std::string m_names;
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
231struct 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
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
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
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{
347public:
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
362private:
364 const std::string m_description;
365 const std::vector<RPCArg> m_args;
368};
369
370#endif // BITCOIN_RPC_UTIL_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
An encapsulated public key.
Definition: pubkey.h:33
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
Fillable signing provider that keeps keys in an address->secret map.
std::function< UniValue(const RPCHelpMan &, const JSONRPCRequest &)> RPCMethodImpl
Definition: util.h:349
const RPCExamples m_examples
Definition: util.h:367
std::vector< std::string > GetArgNames() const
Definition: util.cpp:593
RPCHelpMan(std::string name, std::string description, std::vector< RPCArg > args, RPCResults results, RPCExamples examples)
Definition: util.cpp:493
const std::string m_description
Definition: util.h:364
bool IsValidNumArgs(size_t num_args) const
If the supplied number of args is neither too small nor too high.
Definition: util.cpp:581
const RPCMethodImpl m_fun
Definition: util.h:363
const std::string m_name
Definition: util.h:360
const RPCResults m_results
Definition: util.h:366
const std::vector< RPCArg > m_args
Definition: util.h:365
std::string ToString() const
Definition: util.cpp:602
UniValue GetArgMap() const
Return the named args that need to be converted from string to another JSON type.
Definition: util.cpp:654
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:564
256-bit opaque blob.
Definition: uint256.h:124
TransactionError
Definition: error.h:22
OutputType
Definition: outputtype.h:18
ServiceFlags
nServices flags
Definition: protocol.h:271
const char * name
Definition: rest.cpp:43
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:24
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:103
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:976
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
std::vector< std::pair< std::string, UniValue > > RPCArgList
Definition: util.h:89
UniValue GetServicesNames(ServiceFlags services)
Returns, given services flags, a list of humanly readable (known) network services.
Definition: util.cpp:1030
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:226
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:180
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:41
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string="")
Definition: util.cpp:359
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
RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
Definition: util.cpp:340
OuterType
Serializing JSON objects depends on the outer type.
Definition: util.h:120
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
CAmount AmountFromValue(const UniValue &value, int decimals=8)
Validate and return a CAmount from a UniValue number or string.
Definition: util.cpp:78
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
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
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:112
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull=false, bool fStrict=false)
Definition: util.cpp:48
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:192
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:99
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:90
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:22
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
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:161
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:205
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:325
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
Definition: util.h:126
Type
Definition: util.h:127
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
@ 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:161
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
const Fallback m_fallback
Definition: util.h:162
std::string ToString(bool oneline) const
Return the type string of the argument.
Definition: util.cpp:927
const bool m_hidden
Definition: util.h:160
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
const std::string m_description
Definition: util.h:163
std::string DefaultHint
Definition: util.h:155
bool IsOptional() const
Definition: util.cpp:685
std::variant< Optional, DefaultHint, Default > Fallback
Definition: util.h:157
const Type m_type
Definition: util.h:159
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
std::string GetName() const
Return the name, throws when there are aliases.
Definition: util.cpp:679
std::string GetFirstName() const
Return the first of all aliases.
Definition: util.cpp:674
const std::string m_oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:164
std::string ToStringObj(bool oneline) const
Return the type string of the argument when it is in an object (dict).
Definition: util.cpp:890
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
std::string ToDescriptionString() const
Return the description string, including the argument type and whether the argument is required.
Definition: util.cpp:694
Optional
Definition: util.h:139
@ 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:559
RPCExamples(std::string examples)
Definition: util.h:337
const std::string m_examples
Definition: util.h:336
const std::string m_description
Definition: util.h:252
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(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
@ 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.
const std::vector< RPCResult > m_inner
Only used for arrays or dicts.
Definition: util.h:250
const std::string m_cond
Definition: util.h:253
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 Type type, const std::string m_key_name, const std::string description, const std::vector< RPCResult > inner={})
Definition: util.h:299
const bool m_optional
Definition: util.h:251
const std::string m_key_name
Only used for dicts.
Definition: util.h:249
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
bool MatchesType(const UniValue &result) const
Check whether the result JSON type matches.
Definition: util.cpp:854
const Type m_type
Definition: util.h:248
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
RPCResults(RPCResult result)
Definition: util.h:319
const std::vector< RPCResult > m_results
Definition: util.h:317
RPCResults(std::initializer_list< RPCResult > results)
Definition: util.h:324
Keeps track of RPCArgs by transforming them into sections for the purpose of serializing everything t...
Definition: util.cpp:383
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
Definition: util.h:44
bool typeAny
Definition: util.h:47
UniValueType(UniValue::VType _type)
Definition: util.h:45
UniValue::VType type
Definition: util.h:48
UniValueType()
Definition: util.h:46