/tmp/bitcoin/src/rpc/util.cpp
Line | Count | Source |
1 | | // Copyright (c) 2017-present 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 | | #include <rpc/util.h> |
6 | | |
7 | | #include <arith_uint256.h> |
8 | | #include <chain.h> |
9 | | #include <common/args.h> |
10 | | #include <common/messages.h> |
11 | | #include <common/types.h> |
12 | | #include <consensus/amount.h> |
13 | | #include <core_io.h> |
14 | | #include <crypto/hex_base.h> |
15 | | #include <node/types.h> |
16 | | #include <outputtype.h> |
17 | | #include <pow.h> |
18 | | #include <script/descriptor.h> |
19 | | #include <script/signingprovider.h> |
20 | | #include <script/solver.h> |
21 | | #include <tinyformat.h> |
22 | | #include <uint256.h> |
23 | | #include <univalue.h> |
24 | | #include <util/bip32.h> |
25 | | #include <util/check.h> |
26 | | #include <util/result.h> |
27 | | #include <util/strencodings.h> |
28 | | #include <util/string.h> |
29 | | #include <util/translation.h> |
30 | | |
31 | | #include <algorithm> |
32 | | #include <iterator> |
33 | | #include <memory> |
34 | | #include <set> |
35 | | #include <span> |
36 | | #include <string_view> |
37 | | #include <tuple> |
38 | | #include <utility> |
39 | | |
40 | | using common::PSBTError; |
41 | | using common::PSBTErrorString; |
42 | | using common::TransactionErrorString; |
43 | | using node::TransactionError; |
44 | | using util::Join; |
45 | | using util::SplitString; |
46 | | using util::TrimString; |
47 | | |
48 | | const std::string UNIX_EPOCH_TIME = "UNIX epoch time"; |
49 | | const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"}; |
50 | | |
51 | | std::string GetAllOutputTypes() |
52 | 56.2k | { |
53 | 56.2k | std::vector<std::string> ret; |
54 | 56.2k | using U = std::underlying_type_t<TxoutType>; |
55 | 675k | for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) { |
56 | 618k | ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i))); |
57 | 618k | } |
58 | 56.2k | return Join(ret, ", "); |
59 | 56.2k | } |
60 | | |
61 | | void RPCTypeCheckObj(const UniValue& o, |
62 | | const std::map<std::string, UniValueType>& typesExpected, |
63 | | bool fAllowNull, |
64 | | bool fStrict) |
65 | 2.18k | { |
66 | 22.2k | for (const auto& t : typesExpected) { |
67 | 22.2k | const UniValue& v = o.find_value(t.first); |
68 | 22.2k | if (!fAllowNull && v.isNull()) |
69 | 11 | throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); |
70 | | |
71 | 22.2k | if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) |
72 | 27 | throw JSONRPCError(RPC_TYPE_ERROR, strprintf("JSON value of type %s for field %s is not of expected type %s", uvTypeName(v.type()), t.first, uvTypeName(t.second.type))); |
73 | 22.2k | } |
74 | | |
75 | 2.15k | if (fStrict) |
76 | 1.24k | { |
77 | 1.24k | for (const std::string& k : o.getKeys()) |
78 | 2.43k | { |
79 | 2.43k | if (!typesExpected.contains(k)) |
80 | 5 | { |
81 | 5 | std::string err = strprintf("Unexpected key %s", k); |
82 | 5 | throw JSONRPCError(RPC_TYPE_ERROR, err); |
83 | 5 | } |
84 | 2.43k | } |
85 | 1.24k | } |
86 | 2.15k | } |
87 | | |
88 | | int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool) |
89 | 7.29k | { |
90 | 7.29k | if (!arg.isNull()) { |
91 | 5.64k | if (arg.isBool()) { |
92 | 3.96k | if (!allow_bool) { |
93 | 2 | throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed"); |
94 | 2 | } |
95 | 3.96k | return arg.get_bool(); // true = 1 |
96 | 3.96k | } else { |
97 | 1.67k | return arg.getInt<int>(); |
98 | 1.67k | } |
99 | 5.64k | } |
100 | 1.65k | return default_verbosity; |
101 | 7.29k | } |
102 | | |
103 | | CAmount AmountFromValue(const UniValue& value, int decimals) |
104 | 54.1k | { |
105 | 54.1k | if (!value.isNum() && !value.isStr()) |
106 | 12 | throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string"); |
107 | 54.1k | int64_t amount; |
108 | 54.1k | if (!ParseFixedPoint(value.getValStr(), decimals, &amount)) |
109 | 83 | throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); |
110 | 54.0k | if (!MoneyRange(amount)) |
111 | 12 | throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range"); |
112 | 54.0k | return amount; |
113 | 54.0k | } |
114 | | |
115 | | CFeeRate ParseFeeRate(const UniValue& json) |
116 | 37.6k | { |
117 | 37.6k | CAmount val{AmountFromValue(json)}; |
118 | 37.6k | if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted"); |
119 | 37.6k | return CFeeRate{val}; |
120 | 37.6k | } |
121 | | |
122 | | uint256 ParseHashV(const UniValue& v, std::string_view name) |
123 | 30.5k | { |
124 | 30.5k | const std::string& strHex(v.get_str()); |
125 | 30.5k | if (auto rv{uint256::FromHex(strHex)}) return *rv; |
126 | 29 | if (auto expected_len{uint256::size() * 2}; strHex.length() != expected_len) { |
127 | 16 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d, for '%s')", name, expected_len, strHex.length(), strHex)); |
128 | 16 | } |
129 | 13 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex)); |
130 | 29 | } |
131 | | uint256 ParseHashO(const UniValue& o, std::string_view strKey) |
132 | 6.57k | { |
133 | 6.57k | return ParseHashV(o.find_value(strKey), strKey); |
134 | 6.57k | } |
135 | | std::vector<unsigned char> ParseHexV(const UniValue& v, std::string_view name) |
136 | 907 | { |
137 | 907 | std::string strHex; |
138 | 907 | if (v.isStr()) |
139 | 907 | strHex = v.get_str(); |
140 | 907 | if (!IsHex(strHex)) |
141 | 4 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be hexadecimal string (not '%s')", name, strHex)); |
142 | 903 | return ParseHex(strHex); |
143 | 907 | } |
144 | | std::vector<unsigned char> ParseHexO(const UniValue& o, std::string_view strKey) |
145 | 600 | { |
146 | 600 | return ParseHexV(o.find_value(strKey), strKey); |
147 | 600 | } |
148 | | |
149 | | namespace { |
150 | | |
151 | | /** |
152 | | * Quote an argument for shell. |
153 | | * |
154 | | * @note This is intended for help, not for security-sensitive purposes. |
155 | | */ |
156 | | std::string ShellQuote(const std::string& s) |
157 | 2.56k | { |
158 | 2.56k | std::string result; |
159 | 2.56k | result.reserve(s.size() * 2); |
160 | 220k | for (const char ch: s) { |
161 | 220k | if (ch == '\'') { |
162 | 1 | result += "'\''"; |
163 | 220k | } else { |
164 | 220k | result += ch; |
165 | 220k | } |
166 | 220k | } |
167 | 2.56k | return "'" + result + "'"; |
168 | 2.56k | } |
169 | | |
170 | | /** |
171 | | * Shell-quotes the argument if it needs quoting, else returns it literally, to save typing. |
172 | | * |
173 | | * @note This is intended for help, not for security-sensitive purposes. |
174 | | */ |
175 | | std::string ShellQuoteIfNeeded(const std::string& s) |
176 | 15.8k | { |
177 | 104k | for (const char ch: s) { |
178 | 104k | if (ch == ' ' || ch == '\'' || ch == '"') { |
179 | 2.56k | return ShellQuote(s); |
180 | 2.56k | } |
181 | 104k | } |
182 | | |
183 | 13.3k | return s; |
184 | 15.8k | } |
185 | | |
186 | | } |
187 | | |
188 | | std::string HelpExampleCli(const std::string& methodname, const std::string& args) |
189 | 747k | { |
190 | 747k | return "> bitcoin-cli " + methodname + " " + args + "\n"; |
191 | 747k | } |
192 | | |
193 | | std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args) |
194 | 6.73k | { |
195 | 6.73k | std::string result = "> bitcoin-cli -named " + methodname; |
196 | 15.8k | for (const auto& argpair: args) { |
197 | 15.8k | const auto& value = argpair.second.isStr() |
198 | 15.8k | ? argpair.second.get_str() |
199 | 15.8k | : argpair.second.write(); |
200 | 15.8k | result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value); |
201 | 15.8k | } |
202 | 6.73k | result += "\n"; |
203 | 6.73k | return result; |
204 | 6.73k | } |
205 | | |
206 | | std::string HelpExampleRpc(const std::string& methodname, const std::string& args) |
207 | 488k | { |
208 | 488k | return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", " |
209 | 488k | "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n"; |
210 | 488k | } |
211 | | |
212 | | std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args) |
213 | 4.17k | { |
214 | 4.17k | UniValue params(UniValue::VOBJ); |
215 | 10.7k | for (const auto& param: args) { |
216 | 10.7k | params.pushKV(param.first, param.second); |
217 | 10.7k | } |
218 | | |
219 | 4.17k | return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", " |
220 | 4.17k | "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n"; |
221 | 4.17k | } |
222 | | |
223 | | // Converts a hex string to a public key if possible |
224 | | CPubKey HexToPubKey(const std::string& hex_in) |
225 | 568 | { |
226 | 568 | if (!IsHex(hex_in)) { |
227 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be a hex string"); |
228 | 1 | } |
229 | 567 | if (hex_in.length() != 66 && hex_in.length() != 130) { |
230 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must have a length of either 33 or 65 bytes"); |
231 | 1 | } |
232 | 566 | CPubKey vchPubKey(ParseHex(hex_in)); |
233 | 566 | if (!vchPubKey.IsFullyValid()) { |
234 | 0 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be cryptographically valid."); |
235 | 0 | } |
236 | 566 | return vchPubKey; |
237 | 566 | } |
238 | | |
239 | | // Creates a multisig address from a given list of public keys, number of signatures required, and the address type |
240 | | CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out) |
241 | 83 | { |
242 | | // Gather public keys |
243 | 83 | if (required < 1) { |
244 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem"); |
245 | 0 | } |
246 | 83 | if ((int)pubkeys.size() < required) { |
247 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", pubkeys.size(), required)); |
248 | 0 | } |
249 | 83 | if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) { |
250 | 2 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Number of keys involved in the multisignature address creation > %d\nReduce the number", MAX_PUBKEYS_PER_MULTISIG)); |
251 | 2 | } |
252 | | |
253 | 81 | script_out = GetScriptForMultisig(required, pubkeys); |
254 | | |
255 | | // Check if any keys are uncompressed. If so, the type is legacy |
256 | 480 | for (const CPubKey& pk : pubkeys) { |
257 | 480 | if (!pk.IsCompressed()) { |
258 | 18 | type = OutputType::LEGACY; |
259 | 18 | break; |
260 | 18 | } |
261 | 480 | } |
262 | | |
263 | 81 | if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) { |
264 | 1 | throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf("redeemScript exceeds size limit: %d > %d", script_out.size(), MAX_SCRIPT_ELEMENT_SIZE))); |
265 | 1 | } |
266 | | |
267 | | // Make the address |
268 | 80 | CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type); |
269 | | |
270 | 80 | return dest; |
271 | 81 | } |
272 | | |
273 | | class DescribeAddressVisitor |
274 | | { |
275 | | public: |
276 | | explicit DescribeAddressVisitor() = default; |
277 | | |
278 | | UniValue operator()(const CNoDestination& dest) const |
279 | 0 | { |
280 | 0 | return UniValue(UniValue::VOBJ); |
281 | 0 | } |
282 | | |
283 | | UniValue operator()(const PubKeyDestination& dest) const |
284 | 0 | { |
285 | 0 | return UniValue(UniValue::VOBJ); |
286 | 0 | } |
287 | | |
288 | | UniValue operator()(const PKHash& keyID) const |
289 | 133 | { |
290 | 133 | UniValue obj(UniValue::VOBJ); |
291 | 133 | obj.pushKV("isscript", false); |
292 | 133 | obj.pushKV("iswitness", false); |
293 | 133 | return obj; |
294 | 133 | } |
295 | | |
296 | | UniValue operator()(const ScriptHash& scriptID) const |
297 | 130 | { |
298 | 130 | UniValue obj(UniValue::VOBJ); |
299 | 130 | obj.pushKV("isscript", true); |
300 | 130 | obj.pushKV("iswitness", false); |
301 | 130 | return obj; |
302 | 130 | } |
303 | | |
304 | | UniValue operator()(const WitnessV0KeyHash& id) const |
305 | 500 | { |
306 | 500 | UniValue obj(UniValue::VOBJ); |
307 | 500 | obj.pushKV("isscript", false); |
308 | 500 | obj.pushKV("iswitness", true); |
309 | 500 | obj.pushKV("witness_version", 0); |
310 | 500 | obj.pushKV("witness_program", HexStr(id)); |
311 | 500 | return obj; |
312 | 500 | } |
313 | | |
314 | | UniValue operator()(const WitnessV0ScriptHash& id) const |
315 | 43 | { |
316 | 43 | UniValue obj(UniValue::VOBJ); |
317 | 43 | obj.pushKV("isscript", true); |
318 | 43 | obj.pushKV("iswitness", true); |
319 | 43 | obj.pushKV("witness_version", 0); |
320 | 43 | obj.pushKV("witness_program", HexStr(id)); |
321 | 43 | return obj; |
322 | 43 | } |
323 | | |
324 | | UniValue operator()(const WitnessV1Taproot& tap) const |
325 | 123 | { |
326 | 123 | UniValue obj(UniValue::VOBJ); |
327 | 123 | obj.pushKV("isscript", true); |
328 | 123 | obj.pushKV("iswitness", true); |
329 | 123 | obj.pushKV("witness_version", 1); |
330 | 123 | obj.pushKV("witness_program", HexStr(tap)); |
331 | 123 | return obj; |
332 | 123 | } |
333 | | |
334 | | UniValue operator()(const PayToAnchor& anchor) const |
335 | 1 | { |
336 | 1 | UniValue obj(UniValue::VOBJ); |
337 | 1 | obj.pushKV("isscript", true); |
338 | 1 | obj.pushKV("iswitness", true); |
339 | 1 | return obj; |
340 | 1 | } |
341 | | |
342 | | UniValue operator()(const WitnessUnknown& id) const |
343 | 5 | { |
344 | 5 | UniValue obj(UniValue::VOBJ); |
345 | 5 | obj.pushKV("iswitness", true); |
346 | 5 | obj.pushKV("witness_version", id.GetWitnessVersion()); |
347 | 5 | obj.pushKV("witness_program", HexStr(id.GetWitnessProgram())); |
348 | 5 | return obj; |
349 | 5 | } |
350 | | }; |
351 | | |
352 | | UniValue DescribeAddress(const CTxDestination& dest) |
353 | 935 | { |
354 | 935 | return std::visit(DescribeAddressVisitor(), dest); |
355 | 935 | } |
356 | | |
357 | | /** |
358 | | * Returns a sighash value corresponding to the passed in argument. |
359 | | * |
360 | | * @pre The sighash argument should be string or null. |
361 | | */ |
362 | | std::optional<int> ParseSighashString(const UniValue& sighash) |
363 | 1.08k | { |
364 | 1.08k | if (sighash.isNull()) { |
365 | 991 | return std::nullopt; |
366 | 991 | } |
367 | 92 | const auto result{SighashFromStr(sighash.get_str())}; |
368 | 92 | if (!result) { |
369 | 4 | throw JSONRPCError(RPC_INVALID_PARAMETER, util::ErrorString(result).original); |
370 | 4 | } |
371 | 88 | return result.value(); |
372 | 92 | } |
373 | | |
374 | | unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target) |
375 | 352 | { |
376 | 352 | const int target{value.getInt<int>()}; |
377 | 352 | const unsigned int unsigned_target{static_cast<unsigned int>(target)}; |
378 | 352 | if (target < 1 || unsigned_target > max_target) { |
379 | 31 | throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target)); |
380 | 31 | } |
381 | 321 | return unsigned_target; |
382 | 352 | } |
383 | | |
384 | | RPCErrorCode RPCErrorFromPSBTError(PSBTError err) |
385 | 15 | { |
386 | 15 | switch (err) { |
387 | 0 | case PSBTError::UNSUPPORTED: |
388 | 0 | return RPC_INVALID_PARAMETER; |
389 | 14 | case PSBTError::SIGHASH_MISMATCH: |
390 | 14 | return RPC_DESERIALIZATION_ERROR; |
391 | 1 | default: break; |
392 | 15 | } |
393 | 1 | return RPC_TRANSACTION_ERROR; |
394 | 15 | } |
395 | | |
396 | | RPCErrorCode RPCErrorFromTransactionError(TransactionError terr) |
397 | 4.45k | { |
398 | 4.45k | switch (terr) { |
399 | 4.43k | case TransactionError::MEMPOOL_REJECTED: |
400 | 4.43k | return RPC_TRANSACTION_REJECTED; |
401 | 3 | case TransactionError::ALREADY_IN_UTXO_SET: |
402 | 3 | return RPC_VERIFY_ALREADY_IN_UTXO_SET; |
403 | 5 | case TransactionError::PRIVATE_BROADCAST_FULL: |
404 | 5 | return RPC_LIMIT_EXCEEDED; |
405 | 12 | default: break; |
406 | 4.45k | } |
407 | 12 | return RPC_TRANSACTION_ERROR; |
408 | 4.45k | } |
409 | | |
410 | | UniValue JSONRPCPSBTError(PSBTError err) |
411 | 15 | { |
412 | 15 | return JSONRPCError(RPCErrorFromPSBTError(err), PSBTErrorString(err).original); |
413 | 15 | } |
414 | | |
415 | | UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string) |
416 | 4.45k | { |
417 | 4.45k | if (err_string.length() > 0) { |
418 | 4.44k | return JSONRPCError(RPCErrorFromTransactionError(terr), err_string); |
419 | 4.44k | } else { |
420 | 15 | return JSONRPCError(RPCErrorFromTransactionError(terr), TransactionErrorString(terr).original); |
421 | 15 | } |
422 | 4.45k | } |
423 | | |
424 | | /** |
425 | | * A pair of strings that can be aligned (through padding) with other Sections |
426 | | * later on |
427 | | */ |
428 | | struct Section { |
429 | | Section(const std::string& left, const std::string& right) |
430 | 20.9k | : m_left{left}, m_right{right} {} |
431 | | std::string m_left; |
432 | | const std::string m_right; |
433 | | }; |
434 | | |
435 | | /** |
436 | | * Keeps track of RPCArgs by transforming them into sections for the purpose |
437 | | * of serializing everything to a single string |
438 | | */ |
439 | | struct Sections { |
440 | | std::vector<Section> m_sections; |
441 | | size_t m_max_pad{0}; |
442 | | |
443 | | void PushSection(const Section& s) |
444 | 18.9k | { |
445 | 18.9k | m_max_pad = std::max(m_max_pad, s.m_left.size()); |
446 | 18.9k | m_sections.push_back(s); |
447 | 18.9k | } |
448 | | |
449 | | /** |
450 | | * Recursive helper to translate an RPCArg into sections |
451 | | */ |
452 | | // NOLINTNEXTLINE(misc-no-recursion) |
453 | | void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE) |
454 | 3.24k | { |
455 | 3.24k | const auto indent = std::string(current_indent, ' '); |
456 | 3.24k | const auto indent_next = std::string(current_indent + 2, ' '); |
457 | 3.24k | const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name |
458 | 3.24k | const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion |
459 | | |
460 | 3.24k | switch (arg.m_type) { |
461 | 486 | case RPCArg::Type::STR_HEX: |
462 | 1.33k | case RPCArg::Type::STR: |
463 | 1.93k | case RPCArg::Type::NUM: |
464 | 2.08k | case RPCArg::Type::AMOUNT: |
465 | 2.14k | case RPCArg::Type::RANGE: |
466 | 2.62k | case RPCArg::Type::BOOL: |
467 | 2.69k | case RPCArg::Type::OBJ_NAMED_PARAMS: { |
468 | 2.69k | if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion |
469 | 703 | auto left = indent; |
470 | 703 | if (arg.m_opts.type_str.size() != 0 && push_name) { |
471 | 3 | left += "\"" + arg.GetName() + "\": " + arg.m_opts.type_str.at(0); |
472 | 700 | } else { |
473 | 700 | left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false); |
474 | 700 | } |
475 | 703 | left += ","; |
476 | 703 | PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)}); |
477 | 703 | break; |
478 | 2.69k | } |
479 | 176 | case RPCArg::Type::OBJ: |
480 | 216 | case RPCArg::Type::OBJ_USER_KEYS: { |
481 | 216 | const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name); |
482 | 216 | PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right}); |
483 | 500 | for (const auto& arg_inner : arg.m_inner) { |
484 | 500 | Push(arg_inner, current_indent + 2, OuterType::OBJ); |
485 | 500 | } |
486 | 216 | if (arg.m_type != RPCArg::Type::OBJ) { |
487 | 40 | PushSection({indent_next + "...", ""}); |
488 | 40 | } |
489 | 216 | PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""}); |
490 | 216 | break; |
491 | 176 | } |
492 | 332 | case RPCArg::Type::ARR: { |
493 | 332 | auto left = indent; |
494 | 332 | left += push_name ? "\"" + arg.GetName() + "\": " : ""; |
495 | 332 | left += "["; |
496 | 332 | const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name); |
497 | 332 | PushSection({left, right}); |
498 | 437 | for (const auto& arg_inner : arg.m_inner) { |
499 | 437 | Push(arg_inner, current_indent + 2, OuterType::ARR); |
500 | 437 | } |
501 | 332 | PushSection({indent_next + "...", ""}); |
502 | 332 | PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""}); |
503 | 332 | break; |
504 | 176 | } |
505 | 3.24k | } // no default case, so the compiler can warn about missing cases |
506 | 3.24k | } |
507 | | |
508 | | /** |
509 | | * Concatenate all sections with proper padding |
510 | | */ |
511 | | std::string ToString() const |
512 | 3.54k | { |
513 | 3.54k | std::string ret; |
514 | 3.54k | const size_t pad = m_max_pad + 4; |
515 | 20.9k | for (const auto& s : m_sections) { |
516 | | // The left part of a section is assumed to be a single line, usually it is the name of the JSON struct or a |
517 | | // brace like {, }, [, or ] |
518 | 20.9k | CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos); |
519 | 20.9k | if (s.m_right.empty()) { |
520 | 5.57k | ret += s.m_left; |
521 | 5.57k | ret += "\n"; |
522 | 5.57k | continue; |
523 | 5.57k | } |
524 | | |
525 | 15.3k | std::string left = s.m_left; |
526 | 15.3k | left.resize(pad, ' '); |
527 | 15.3k | ret += left; |
528 | | |
529 | | // Properly pad after newlines |
530 | 15.3k | std::string right; |
531 | 15.3k | size_t begin = 0; |
532 | 15.3k | size_t new_line_pos = s.m_right.find_first_of('\n'); |
533 | 17.2k | while (true) { |
534 | 17.2k | right += s.m_right.substr(begin, new_line_pos - begin); |
535 | 17.2k | if (new_line_pos == std::string::npos) { |
536 | 15.1k | break; //No new line |
537 | 15.1k | } |
538 | 2.05k | right += "\n" + std::string(pad, ' '); |
539 | 2.05k | begin = s.m_right.find_first_not_of(' ', new_line_pos + 1); |
540 | 2.05k | if (begin == std::string::npos) { |
541 | 159 | break; // Empty line |
542 | 159 | } |
543 | 1.89k | new_line_pos = s.m_right.find_first_of('\n', begin + 1); |
544 | 1.89k | } |
545 | 15.3k | ret += right; |
546 | 15.3k | ret += "\n"; |
547 | 15.3k | } |
548 | 3.54k | return ret; |
549 | 3.54k | } |
550 | | }; |
551 | | |
552 | | RPCMethod::RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples) |
553 | 19 | : RPCMethod{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {} |
554 | | |
555 | | RPCMethod::RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun) |
556 | 537k | : m_name{std::move(name)}, |
557 | 537k | m_fun{std::move(fun)}, |
558 | 537k | m_description{std::move(description)}, |
559 | 537k | m_args{std::move(args)}, |
560 | 537k | m_results{std::move(results)}, |
561 | 537k | m_examples{std::move(examples)} |
562 | 537k | { |
563 | | // Map of parameter names and types just used to check whether the names are |
564 | | // unique. Parameter names always need to be unique, with the exception that |
565 | | // there can be pairs of POSITIONAL and NAMED parameters with the same name. |
566 | 537k | enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 }; |
567 | 537k | std::map<std::string, int> param_names; |
568 | | |
569 | 1.01M | for (const auto& arg : m_args) { |
570 | 1.01M | std::vector<std::string> names = SplitString(arg.m_names, '|'); |
571 | | // Should have unique named arguments |
572 | 1.02M | for (const std::string& name : names) { |
573 | 1.02M | auto& param_type = param_names[name]; |
574 | 1.02M | CHECK_NONFATAL(!(param_type & POSITIONAL)); |
575 | 1.02M | CHECK_NONFATAL(!(param_type & NAMED_ONLY)); |
576 | 1.02M | param_type |= POSITIONAL; |
577 | 1.02M | } |
578 | 1.01M | if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) { |
579 | 119k | for (const auto& inner : arg.m_inner) { |
580 | 119k | std::vector<std::string> inner_names = SplitString(inner.m_names, '|'); |
581 | 119k | for (const std::string& inner_name : inner_names) { |
582 | 119k | auto& param_type = param_names[inner_name]; |
583 | 119k | CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional); |
584 | 119k | CHECK_NONFATAL(!(param_type & NAMED)); |
585 | 119k | CHECK_NONFATAL(!(param_type & NAMED_ONLY)); |
586 | 119k | param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY; |
587 | 119k | } |
588 | 119k | } |
589 | 20.9k | } |
590 | | // Default value type should match argument type only when defined |
591 | 1.01M | if (arg.m_fallback.index() == 2) { |
592 | 359k | const RPCArg::Type type = arg.m_type; |
593 | 359k | [&]() { |
594 | 359k | switch (std::get<RPCArg::Default>(arg.m_fallback).getType()) { |
595 | 0 | case UniValue::VOBJ: |
596 | 0 | CHECK_NONFATAL(type == RPCArg::Type::OBJ); |
597 | 0 | return; |
598 | 2.17k | case UniValue::VARR: |
599 | 2.17k | CHECK_NONFATAL(type == RPCArg::Type::ARR); |
600 | 2.17k | return; |
601 | 132k | case UniValue::VSTR: |
602 | 132k | CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT); |
603 | 132k | return; |
604 | 76.2k | case UniValue::VNUM: |
605 | 76.2k | CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE); |
606 | 76.2k | return; |
607 | 148k | case UniValue::VBOOL: |
608 | 148k | CHECK_NONFATAL(type == RPCArg::Type::BOOL); |
609 | 148k | return; |
610 | 0 | case UniValue::VNULL: |
611 | | // Null values are accepted in all arguments |
612 | 0 | return; |
613 | 359k | } // no default case, so the compiler can warn about missing cases |
614 | 359k | NONFATAL_UNREACHABLE(); |
615 | 359k | }(); |
616 | 359k | } |
617 | 1.01M | } |
618 | 537k | } |
619 | | |
620 | | std::string RPCResults::ToDescriptionString() const |
621 | 1.11k | { |
622 | 1.11k | std::string result; |
623 | 1.33k | for (const auto& r : m_results) { |
624 | 1.33k | Sections sections; |
625 | 1.33k | r.ToSections(sections); |
626 | | // A result can be empty via HelpElisionSkip |
627 | 1.33k | if (sections.m_sections.empty()) continue; |
628 | | |
629 | 1.32k | if (r.m_cond.empty()) { |
630 | 983 | result += "\nResult:\n"; |
631 | 983 | } else { |
632 | 337 | result += "\nResult (" + r.m_cond + "):\n"; |
633 | 337 | } |
634 | 1.32k | result += sections.ToString(); |
635 | 1.32k | } |
636 | 1.11k | return result; |
637 | 1.11k | } |
638 | | |
639 | | std::string RPCExamples::ToDescriptionString() const |
640 | 1.11k | { |
641 | 1.11k | return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples; |
642 | 1.11k | } |
643 | | |
644 | | UniValue RPCMethod::HandleRequest(const JSONRPCRequest& request) const |
645 | 201k | { |
646 | 201k | if (request.mode == JSONRPCRequest::GET_ARGS) { |
647 | 350 | return GetArgMap(); |
648 | 350 | } |
649 | | /* |
650 | | * Check if the given request is valid according to this command or if |
651 | | * the user is asking for help information, and throw help when appropriate. |
652 | | */ |
653 | 201k | if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) { |
654 | 1.10k | throw HelpResult{ToString()}; |
655 | 1.10k | } |
656 | 199k | UniValue arg_mismatch{UniValue::VOBJ}; |
657 | 593k | for (size_t i{0}; i < m_args.size(); ++i) { |
658 | 393k | const auto& arg{m_args.at(i)}; |
659 | 393k | UniValue match{arg.MatchesType(request.params[i])}; |
660 | 393k | if (!match.isTrue()) { |
661 | 31 | arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match)); |
662 | 31 | } |
663 | 393k | } |
664 | 199k | if (!arg_mismatch.empty()) { |
665 | 29 | throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4))); |
666 | 29 | } |
667 | 199k | CHECK_NONFATAL(m_req == nullptr); |
668 | 199k | m_req = &request; |
669 | 199k | UniValue ret = m_fun(*this, request); |
670 | 199k | m_req = nullptr; |
671 | 199k | if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) { |
672 | 193k | UniValue mismatch{UniValue::VARR}; |
673 | 204k | for (const auto& res : m_results.m_results) { |
674 | 204k | UniValue match{res.MatchesType(ret)}; |
675 | 204k | if (match.isTrue()) { |
676 | 193k | mismatch.setNull(); |
677 | 193k | break; |
678 | 193k | } |
679 | 10.7k | mismatch.push_back(std::move(match)); |
680 | 10.7k | } |
681 | 193k | if (!mismatch.isNull()) { |
682 | 0 | std::string explain{ |
683 | 0 | mismatch.empty() ? "no possible results defined" : |
684 | 0 | mismatch.size() == 1 ? mismatch[0].write(4) : |
685 | 0 | mismatch.write(4)}; |
686 | 0 | throw std::runtime_error{ |
687 | 0 | STR_INTERNAL_BUG(strprintf("RPC call \"%s\" returned incorrect type:\n%s", m_name, explain)), |
688 | 0 | }; |
689 | 0 | } |
690 | 193k | } |
691 | 199k | return ret; |
692 | 199k | } |
693 | | |
694 | | using CheckFn = void(const RPCArg&); |
695 | | static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i) |
696 | 50.1k | { |
697 | 50.1k | CHECK_NONFATAL(i < params.size()); |
698 | 50.1k | const UniValue& arg{CHECK_NONFATAL(req)->params[i]}; |
699 | 50.1k | const RPCArg& param{params.at(i)}; |
700 | 50.1k | if (check) check(param); |
701 | | |
702 | 50.1k | if (!arg.isNull()) return &arg; |
703 | 23.3k | if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr; |
704 | 20.8k | return &std::get<RPCArg::Default>(param.m_fallback); |
705 | 23.3k | } |
706 | | |
707 | | static void CheckRequiredOrDefault(const RPCArg& param) |
708 | 45.9k | { |
709 | | // Must use `Arg<Type>(key)` to get the argument or its default value. |
710 | 45.9k | const bool required{ |
711 | 45.9k | std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback), |
712 | 45.9k | }; |
713 | 45.9k | CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback)); |
714 | 45.9k | } |
715 | | |
716 | | #define TMPL_INST(check_param, ret_type, return_code) \ |
717 | | template <> \ |
718 | | ret_type RPCMethod::ArgValue<ret_type>(size_t i) const \ |
719 | 50.1k | { \ |
720 | 50.1k | const UniValue* maybe_arg{ \ |
721 | 50.1k | DetailMaybeArg(check_param, m_args, m_req, i), \ |
722 | 50.1k | }; \ |
723 | 50.1k | return return_code \ |
724 | 50.1k | } \ UniValue const* RPCMethod::ArgValue<UniValue const*>(unsigned long) const Line | Count | Source | 719 | 1.34k | { \ | 720 | 1.34k | const UniValue* maybe_arg{ \ | 721 | 1.34k | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 1.34k | }; \ | 723 | 1.34k | return return_code \ | 724 | 1.34k | } \ |
std::optional<double> RPCMethod::ArgValue<std::optional<double>>(unsigned long) const Line | Count | Source | 719 | 723 | { \ | 720 | 723 | const UniValue* maybe_arg{ \ | 721 | 723 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 723 | }; \ | 723 | 1.44k | return return_code \ | 724 | 723 | } \ |
std::optional<bool> RPCMethod::ArgValue<std::optional<bool>>(unsigned long) const Line | Count | Source | 719 | 804 | { \ | 720 | 804 | const UniValue* maybe_arg{ \ | 721 | 804 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 804 | }; \ | 723 | 1.60k | return return_code \ | 724 | 804 | } \ |
std::optional<long> RPCMethod::ArgValue<std::optional<long>>(unsigned long) const Line | Count | Source | 719 | 107 | { \ | 720 | 107 | const UniValue* maybe_arg{ \ | 721 | 107 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 107 | }; \ | 723 | 214 | return return_code \ | 724 | 107 | } \ |
std::optional<std::basic_string_view<char, std::char_traits<char>>> RPCMethod::ArgValue<std::optional<std::basic_string_view<char, std::char_traits<char>>>>(unsigned long) const Line | Count | Source | 719 | 1.27k | { \ | 720 | 1.27k | const UniValue* maybe_arg{ \ | 721 | 1.27k | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 1.27k | }; \ | 723 | 2.55k | return return_code \ | 724 | 1.27k | } \ |
UniValue const& RPCMethod::ArgValue<UniValue const&>(unsigned long) const Line | Count | Source | 719 | 37.6k | { \ | 720 | 37.6k | const UniValue* maybe_arg{ \ | 721 | 37.6k | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 37.6k | }; \ | 723 | 37.6k | return return_code \ | 724 | 37.6k | } \ |
bool RPCMethod::ArgValue<bool>(unsigned long) const Line | Count | Source | 719 | 893 | { \ | 720 | 893 | const UniValue* maybe_arg{ \ | 721 | 893 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 893 | }; \ | 723 | 893 | return return_code \ | 724 | 893 | } \ |
int RPCMethod::ArgValue<int>(unsigned long) const Line | Count | Source | 719 | 1.42k | { \ | 720 | 1.42k | const UniValue* maybe_arg{ \ | 721 | 1.42k | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 1.42k | }; \ | 723 | 1.42k | return return_code \ | 724 | 1.42k | } \ |
unsigned long RPCMethod::ArgValue<unsigned long>(unsigned long) const Line | Count | Source | 719 | 833 | { \ | 720 | 833 | const UniValue* maybe_arg{ \ | 721 | 833 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 833 | }; \ | 723 | 833 | return return_code \ | 724 | 833 | } \ |
unsigned int RPCMethod::ArgValue<unsigned int>(unsigned long) const Line | Count | Source | 719 | 998 | { \ | 720 | 998 | const UniValue* maybe_arg{ \ | 721 | 998 | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 998 | }; \ | 723 | 998 | return return_code \ | 724 | 998 | } \ |
std::basic_string_view<char, std::char_traits<char>> RPCMethod::ArgValue<std::basic_string_view<char, std::char_traits<char>>>(unsigned long) const Line | Count | Source | 719 | 4.18k | { \ | 720 | 4.18k | const UniValue* maybe_arg{ \ | 721 | 4.18k | DetailMaybeArg(check_param, m_args, m_req, i), \ | 722 | 4.18k | }; \ | 723 | 4.18k | return return_code \ | 724 | 4.18k | } \ |
|
725 | | void force_semicolon(ret_type) |
726 | | |
727 | | // Optional arg (without default). Can also be called on required args, if needed. |
728 | | TMPL_INST(nullptr, const UniValue*, maybe_arg;); |
729 | | TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;); |
730 | | TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;); |
731 | | TMPL_INST(nullptr, std::optional<int64_t>, maybe_arg ? std::optional{maybe_arg->getInt<int64_t>()} : std::nullopt;); |
732 | | TMPL_INST(nullptr, std::optional<std::string_view>, maybe_arg ? std::optional<std::string_view>{maybe_arg->get_str()} : std::nullopt;); |
733 | | |
734 | | // Required arg or optional arg with default value. |
735 | | TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg);); |
736 | | TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool();); |
737 | | TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>();); |
738 | | TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>();); |
739 | | TMPL_INST(CheckRequiredOrDefault, uint32_t, CHECK_NONFATAL(maybe_arg)->getInt<uint32_t>();); |
740 | | TMPL_INST(CheckRequiredOrDefault, std::string_view, CHECK_NONFATAL(maybe_arg)->get_str();); |
741 | | |
742 | | bool RPCMethod::IsValidNumArgs(size_t num_args) const |
743 | 199k | { |
744 | 199k | size_t num_required_args = 0; |
745 | 424k | for (size_t n = m_args.size(); n > 0; --n) { |
746 | 352k | if (!m_args.at(n - 1).IsOptional()) { |
747 | 128k | num_required_args = n; |
748 | 128k | break; |
749 | 128k | } |
750 | 352k | } |
751 | 199k | return num_required_args <= num_args && num_args <= m_args.size(); |
752 | 199k | } |
753 | | |
754 | | std::vector<std::pair<std::string, bool>> RPCMethod::GetArgNames() const |
755 | 168k | { |
756 | 168k | std::vector<std::pair<std::string, bool>> ret; |
757 | 168k | ret.reserve(m_args.size()); |
758 | 307k | for (const auto& arg : m_args) { |
759 | 307k | if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) { |
760 | 49.7k | for (const auto& inner : arg.m_inner) { |
761 | 49.7k | ret.emplace_back(inner.m_names, /*named_only=*/true); |
762 | 49.7k | } |
763 | 9.52k | } |
764 | 307k | ret.emplace_back(arg.m_names, /*named_only=*/false); |
765 | 307k | } |
766 | 168k | return ret; |
767 | 168k | } |
768 | | |
769 | | size_t RPCMethod::GetParamIndex(std::string_view key) const |
770 | 50.1k | { |
771 | 50.1k | auto it{std::find_if( |
772 | 103k | m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;} |
773 | 50.1k | )}; |
774 | | |
775 | 50.1k | CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time |
776 | 50.1k | return std::distance(m_args.begin(), it); |
777 | 50.1k | } |
778 | | |
779 | | std::string RPCMethod::ToString() const |
780 | 1.11k | { |
781 | 1.11k | std::string ret; |
782 | | |
783 | | // Oneline summary |
784 | 1.11k | ret += m_name; |
785 | 1.11k | bool was_optional{false}; |
786 | 1.95k | for (const auto& arg : m_args) { |
787 | 1.95k | if (arg.m_opts.hidden) break; // Any arg that follows is also hidden |
788 | 1.94k | const bool optional = arg.IsOptional(); |
789 | 1.94k | ret += " "; |
790 | 1.94k | if (optional) { |
791 | 1.09k | if (!was_optional) ret += "( "; |
792 | 1.09k | was_optional = true; |
793 | 1.09k | } else { |
794 | 853 | if (was_optional) ret += ") "; |
795 | 853 | was_optional = false; |
796 | 853 | } |
797 | 1.94k | ret += arg.ToString(/*oneline=*/true); |
798 | 1.94k | } |
799 | 1.11k | if (was_optional) ret += " )"; |
800 | | |
801 | | // Description |
802 | 1.11k | CHECK_NONFATAL(!m_description.starts_with('\n')); // Historically \n was required, but reject it for new code. |
803 | 1.11k | ret += "\n\n" + TrimString(m_description) + "\n"; |
804 | | |
805 | | // Arguments |
806 | 1.11k | Sections sections; |
807 | 1.11k | Sections named_only_sections; |
808 | 3.05k | for (size_t i{0}; i < m_args.size(); ++i) { |
809 | 1.95k | const auto& arg = m_args.at(i); |
810 | 1.95k | if (arg.m_opts.hidden) break; // Any arg that follows is also hidden |
811 | | |
812 | | // Push named argument name and description |
813 | 1.94k | sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true)); |
814 | 1.94k | sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size()); |
815 | | |
816 | | // Recursively push nested args |
817 | 1.94k | sections.Push(arg); |
818 | | |
819 | | // Push named-only argument sections |
820 | 1.94k | if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) { |
821 | 357 | for (const auto& arg_inner : arg.m_inner) { |
822 | 357 | named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)}); |
823 | 357 | named_only_sections.Push(arg_inner); |
824 | 357 | } |
825 | 69 | } |
826 | 1.94k | } |
827 | | |
828 | 1.11k | if (!sections.m_sections.empty()) ret += "\nArguments:\n"; |
829 | 1.11k | ret += sections.ToString(); |
830 | 1.11k | if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n"; |
831 | 1.11k | ret += named_only_sections.ToString(); |
832 | | |
833 | | // Result |
834 | 1.11k | ret += m_results.ToDescriptionString(); |
835 | | |
836 | | // Examples |
837 | 1.11k | ret += m_examples.ToDescriptionString(); |
838 | | |
839 | 1.11k | return ret; |
840 | 1.11k | } |
841 | | |
842 | | UniValue RPCMethod::GetArgMap() const |
843 | 350 | { |
844 | 350 | UniValue arr{UniValue::VARR}; |
845 | | |
846 | 906 | auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) { |
847 | 906 | UniValue map{UniValue::VARR}; |
848 | 906 | map.push_back(rpc_name); |
849 | 906 | map.push_back(pos); |
850 | 906 | map.push_back(arg_name); |
851 | 906 | map.push_back(type == RPCArg::Type::STR || |
852 | 906 | type == RPCArg::Type::STR_HEX); |
853 | 906 | arr.push_back(std::move(map)); |
854 | 906 | }; |
855 | | |
856 | 1.04k | for (int i{0}; i < int(m_args.size()); ++i) { |
857 | 696 | const auto& arg = m_args.at(i); |
858 | 696 | std::vector<std::string> arg_names = SplitString(arg.m_names, '|'); |
859 | 700 | for (const auto& arg_name : arg_names) { |
860 | 700 | push_back_arg_info(m_name, i, arg_name, arg.m_type); |
861 | 700 | if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) { |
862 | 206 | for (const auto& inner : arg.m_inner) { |
863 | 206 | std::vector<std::string> inner_names = SplitString(inner.m_names, '|'); |
864 | 206 | for (const std::string& inner_name : inner_names) { |
865 | 206 | push_back_arg_info(m_name, i, inner_name, inner.m_type); |
866 | 206 | } |
867 | 206 | } |
868 | 30 | } |
869 | 700 | } |
870 | 696 | } |
871 | 350 | return arr; |
872 | 350 | } |
873 | | |
874 | | static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type) |
875 | 203k | { |
876 | 203k | using Type = RPCArg::Type; |
877 | 203k | switch (type) { |
878 | 73.0k | case Type::STR_HEX: |
879 | 124k | case Type::STR: { |
880 | 124k | return UniValue::VSTR; |
881 | 73.0k | } |
882 | 46.6k | case Type::NUM: { |
883 | 46.6k | return UniValue::VNUM; |
884 | 73.0k | } |
885 | 21.5k | case Type::AMOUNT: { |
886 | | // VNUM or VSTR, checked inside AmountFromValue() |
887 | 21.5k | return std::nullopt; |
888 | 73.0k | } |
889 | 80 | case Type::RANGE: { |
890 | | // VNUM or VARR, checked inside ParseRange() |
891 | 80 | return std::nullopt; |
892 | 73.0k | } |
893 | 3.62k | case Type::BOOL: { |
894 | 3.62k | return UniValue::VBOOL; |
895 | 73.0k | } |
896 | 599 | case Type::OBJ: |
897 | 1.51k | case Type::OBJ_NAMED_PARAMS: |
898 | 1.59k | case Type::OBJ_USER_KEYS: { |
899 | 1.59k | return UniValue::VOBJ; |
900 | 1.51k | } |
901 | 5.72k | case Type::ARR: { |
902 | 5.72k | return UniValue::VARR; |
903 | 1.51k | } |
904 | 203k | } // no default case, so the compiler can warn about missing cases |
905 | 203k | NONFATAL_UNREACHABLE(); |
906 | 203k | } |
907 | | |
908 | | UniValue RPCArg::MatchesType(const UniValue& request) const |
909 | 393k | { |
910 | 393k | if (m_opts.skip_type_check) return true; |
911 | 383k | if (IsOptional() && request.isNull()) return true; |
912 | 203k | const auto exp_type{ExpectedType(m_type)}; |
913 | 203k | if (!exp_type) return true; // nothing to check |
914 | | |
915 | 181k | if (*exp_type != request.getType()) { |
916 | 31 | return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type)); |
917 | 31 | } |
918 | 181k | return true; |
919 | 181k | } |
920 | | |
921 | | std::string RPCArg::GetFirstName() const |
922 | 5.83k | { |
923 | 5.83k | return m_names.substr(0, m_names.find('|')); |
924 | 5.83k | } |
925 | | |
926 | | std::string RPCArg::GetName() const |
927 | 103k | { |
928 | 103k | CHECK_NONFATAL(std::string::npos == m_names.find('|')); |
929 | 103k | return m_names; |
930 | 103k | } |
931 | | |
932 | | bool RPCArg::IsOptional() const |
933 | 738k | { |
934 | 738k | if (m_fallback.index() != 0) { |
935 | 410k | return true; |
936 | 410k | } else { |
937 | 327k | return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback); |
938 | 327k | } |
939 | 738k | } |
940 | | |
941 | | std::string RPCArg::ToDescriptionString(bool is_named_arg) const |
942 | 3.24k | { |
943 | 3.24k | std::string ret; |
944 | 3.24k | ret += "("; |
945 | 3.24k | if (m_opts.type_str.size() != 0) { |
946 | 32 | ret += m_opts.type_str.at(1); |
947 | 3.20k | } else { |
948 | 3.20k | switch (m_type) { |
949 | 486 | case Type::STR_HEX: |
950 | 1.33k | case Type::STR: { |
951 | 1.33k | ret += "string"; |
952 | 1.33k | break; |
953 | 486 | } |
954 | 572 | case Type::NUM: { |
955 | 572 | ret += "numeric"; |
956 | 572 | break; |
957 | 486 | } |
958 | 147 | case Type::AMOUNT: { |
959 | 147 | ret += "numeric or string"; |
960 | 147 | break; |
961 | 486 | } |
962 | 60 | case Type::RANGE: { |
963 | 60 | ret += "numeric or array"; |
964 | 60 | break; |
965 | 486 | } |
966 | 481 | case Type::BOOL: { |
967 | 481 | ret += "boolean"; |
968 | 481 | break; |
969 | 486 | } |
970 | 176 | case Type::OBJ: |
971 | 245 | case Type::OBJ_NAMED_PARAMS: |
972 | 285 | case Type::OBJ_USER_KEYS: { |
973 | 285 | ret += "json object"; |
974 | 285 | break; |
975 | 245 | } |
976 | 332 | case Type::ARR: { |
977 | 332 | ret += "json array"; |
978 | 332 | break; |
979 | 245 | } |
980 | 3.20k | } // no default case, so the compiler can warn about missing cases |
981 | 3.20k | } |
982 | 3.24k | if (m_fallback.index() == 1) { |
983 | 386 | ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback); |
984 | 2.85k | } else if (m_fallback.index() == 2) { |
985 | 926 | ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write(); |
986 | 1.92k | } else { |
987 | 1.92k | switch (std::get<RPCArg::Optional>(m_fallback)) { |
988 | 787 | case RPCArg::Optional::OMITTED: { |
989 | 787 | if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise, |
990 | | // nothing to do. Element is treated as if not present and has no default value |
991 | 787 | break; |
992 | 0 | } |
993 | 1.14k | case RPCArg::Optional::NO: { |
994 | 1.14k | ret += ", required"; |
995 | 1.14k | break; |
996 | 0 | } |
997 | 1.92k | } // no default case, so the compiler can warn about missing cases |
998 | 1.92k | } |
999 | 3.24k | ret += ")"; |
1000 | 3.24k | if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below."; |
1001 | 3.24k | ret += m_description.empty() ? "" : " " + m_description; |
1002 | 3.24k | return ret; |
1003 | 3.24k | } |
1004 | | |
1005 | | // NOLINTNEXTLINE(misc-no-recursion) |
1006 | | void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const |
1007 | 13.1k | { |
1008 | | // Indentation |
1009 | 13.1k | const std::string indent(current_indent, ' '); |
1010 | 13.1k | const std::string indent_next(current_indent + 2, ' '); |
1011 | | |
1012 | | // Elements in a JSON structure (dictionary or array) are separated by a comma |
1013 | 13.1k | const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""}; |
1014 | | |
1015 | | // The key name if recursed into a dictionary |
1016 | 13.1k | const std::string maybe_key{ |
1017 | 13.1k | outer_type == OuterType::OBJ ? |
1018 | 10.5k | "\"" + this->m_key_name + "\" : " : |
1019 | 13.1k | ""}; |
1020 | | |
1021 | | // Format description with type |
1022 | 13.1k | const auto Description = [&](const std::string& type) { |
1023 | 12.0k | return "(" + type + (this->m_optional ? ", optional" : "") + ")" + |
1024 | 12.0k | (this->m_description.empty() ? "" : " " + this->m_description); |
1025 | 12.0k | }; |
1026 | | |
1027 | | // Ensure at least one visible field exists when elision is used |
1028 | 13.1k | const auto elision_has_description{[](const std::vector<RPCResult>& inner) { |
1029 | 3.06k | return std::ranges::any_of(inner, [](const auto& res) { |
1030 | 3.06k | return !std::holds_alternative<HelpElisionSkip>(res.m_opts.print_elision); |
1031 | 3.06k | }); |
1032 | 3.00k | }}; |
1033 | | |
1034 | 13.1k | if (const auto* text = std::get_if<std::string>(&m_opts.print_elision)) { |
1035 | 95 | sections.PushSection({indent + "..." + maybe_separator, *text}); |
1036 | 95 | return; |
1037 | 95 | } |
1038 | 13.0k | if (std::holds_alternative<HelpElisionSkip>(m_opts.print_elision)) { |
1039 | 1.00k | return; |
1040 | 1.00k | } |
1041 | | |
1042 | 12.0k | switch (m_type) { |
1043 | 36 | case Type::ANY: { |
1044 | 36 | sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("any")}); |
1045 | 36 | return; |
1046 | 0 | } |
1047 | 139 | case Type::NONE: { |
1048 | 139 | sections.PushSection({indent + "null" + maybe_separator, Description("json null")}); |
1049 | 139 | return; |
1050 | 0 | } |
1051 | 2.09k | case Type::STR: { |
1052 | 2.09k | sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")}); |
1053 | 2.09k | return; |
1054 | 0 | } |
1055 | 595 | case Type::STR_AMOUNT: { |
1056 | 595 | sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")}); |
1057 | 595 | return; |
1058 | 0 | } |
1059 | 1.93k | case Type::STR_HEX: { |
1060 | 1.93k | sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")}); |
1061 | 1.93k | return; |
1062 | 0 | } |
1063 | 3.10k | case Type::NUM: { |
1064 | 3.10k | sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")}); |
1065 | 3.10k | return; |
1066 | 0 | } |
1067 | 357 | case Type::NUM_TIME: { |
1068 | 357 | sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")}); |
1069 | 357 | return; |
1070 | 0 | } |
1071 | 728 | case Type::BOOL: { |
1072 | 728 | sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")}); |
1073 | 728 | return; |
1074 | 0 | } |
1075 | 17 | case Type::ARR_FIXED: |
1076 | 1.13k | case Type::ARR: { |
1077 | 1.13k | sections.PushSection({indent + maybe_key + "[", Description("json array")}); |
1078 | 1.20k | for (const auto& i : m_inner) { |
1079 | 1.20k | i.ToSections(sections, OuterType::ARR, current_indent + 2); |
1080 | 1.20k | } |
1081 | 1.13k | CHECK_NONFATAL(!m_inner.empty()); |
1082 | 1.13k | CHECK_NONFATAL(elision_has_description(m_inner)); |
1083 | 1.13k | if (m_type == Type::ARR && !std::holds_alternative<std::string>(m_inner.back().m_opts.print_elision)) { |
1084 | 1.11k | sections.PushSection({indent_next + "...", ""}); |
1085 | 1.11k | } else { |
1086 | | // Remove final comma, which would be invalid JSON |
1087 | 20 | sections.m_sections.back().m_left.pop_back(); |
1088 | 20 | } |
1089 | 1.13k | sections.PushSection({indent + "]" + maybe_separator, ""}); |
1090 | 1.13k | return; |
1091 | 17 | } |
1092 | 213 | case Type::OBJ_DYN: |
1093 | 1.88k | case Type::OBJ: { |
1094 | 1.88k | if (m_inner.empty()) { |
1095 | 18 | sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")}); |
1096 | 18 | return; |
1097 | 18 | } |
1098 | 1.86k | CHECK_NONFATAL(elision_has_description(m_inner)); |
1099 | 1.86k | sections.PushSection({indent + maybe_key + "{", Description("json object")}); |
1100 | 10.5k | for (const auto& i : m_inner) { |
1101 | 10.5k | i.ToSections(sections, OuterType::OBJ, current_indent + 2); |
1102 | 10.5k | } |
1103 | 1.86k | if (m_type == Type::OBJ_DYN) { |
1104 | | // If the dictionary keys are dynamic, use three dots for continuation |
1105 | 213 | sections.PushSection({indent_next + "...", ""}); |
1106 | 1.65k | } else { |
1107 | | // Remove final comma, which would be invalid JSON |
1108 | 1.65k | sections.m_sections.back().m_left.pop_back(); |
1109 | 1.65k | } |
1110 | 1.86k | sections.PushSection({indent + "}" + maybe_separator, ""}); |
1111 | 1.86k | return; |
1112 | 1.88k | } |
1113 | 12.0k | } // no default case, so the compiler can warn about missing cases |
1114 | 12.0k | NONFATAL_UNREACHABLE(); |
1115 | 12.0k | } |
1116 | | |
1117 | | static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type) |
1118 | 5.35M | { |
1119 | 5.35M | using Type = RPCResult::Type; |
1120 | 5.35M | switch (type) { |
1121 | 201 | case Type::ANY: { |
1122 | 201 | return std::nullopt; |
1123 | 0 | } |
1124 | 16.1k | case Type::NONE: { |
1125 | 16.1k | return UniValue::VNULL; |
1126 | 0 | } |
1127 | 614k | case Type::STR: |
1128 | 2.12M | case Type::STR_HEX: { |
1129 | 2.12M | return UniValue::VSTR; |
1130 | 614k | } |
1131 | 1.52M | case Type::NUM: |
1132 | 1.83M | case Type::STR_AMOUNT: |
1133 | 2.04M | case Type::NUM_TIME: { |
1134 | 2.04M | return UniValue::VNUM; |
1135 | 1.83M | } |
1136 | 386k | case Type::BOOL: { |
1137 | 386k | return UniValue::VBOOL; |
1138 | 1.83M | } |
1139 | 1.61k | case Type::ARR_FIXED: |
1140 | 256k | case Type::ARR: { |
1141 | 256k | return UniValue::VARR; |
1142 | 1.61k | } |
1143 | 31.1k | case Type::OBJ_DYN: |
1144 | 519k | case Type::OBJ: { |
1145 | 519k | return UniValue::VOBJ; |
1146 | 31.1k | } |
1147 | 5.35M | } // no default case, so the compiler can warn about missing cases |
1148 | 5.35M | NONFATAL_UNREACHABLE(); |
1149 | 5.35M | } |
1150 | | |
1151 | | // NOLINTNEXTLINE(misc-no-recursion) |
1152 | | UniValue RPCResult::MatchesType(const UniValue& result) const |
1153 | 5.35M | { |
1154 | 5.35M | if (m_opts.skip_type_check) { |
1155 | 461 | return true; |
1156 | 461 | } |
1157 | | |
1158 | 5.35M | const auto exp_type = ExpectedType(m_type); |
1159 | 5.35M | if (!exp_type) return true; // can be any type, so nothing to check |
1160 | | |
1161 | 5.35M | if (*exp_type != result.getType()) { |
1162 | 10.7k | return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type)); |
1163 | 10.7k | } |
1164 | | |
1165 | 5.33M | if (UniValue::VARR == result.getType()) { |
1166 | 254k | UniValue errors(UniValue::VOBJ); |
1167 | 1.26M | for (size_t i{0}; i < result.get_array().size(); ++i) { |
1168 | | // If there are more results than documented, reuse the last doc_inner. |
1169 | 1.00M | const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))}; |
1170 | 1.00M | UniValue match{doc_inner.MatchesType(result.get_array()[i])}; |
1171 | 1.00M | if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match)); |
1172 | 1.00M | } |
1173 | 254k | if (errors.empty()) return true; // empty result array is valid |
1174 | 404 | return errors; |
1175 | 254k | } |
1176 | | |
1177 | 5.08M | if (UniValue::VOBJ == result.getType()) { |
1178 | 519k | UniValue errors(UniValue::VOBJ); |
1179 | 519k | if (m_type == Type::OBJ_DYN) { |
1180 | 31.1k | const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first |
1181 | 324k | for (size_t i{0}; i < result.get_obj().size(); ++i) { |
1182 | 293k | UniValue match{doc_inner.MatchesType(result.get_obj()[i])}; |
1183 | 293k | if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match)); |
1184 | 293k | } |
1185 | 31.1k | if (errors.empty()) return true; // empty result obj is valid |
1186 | 5 | return errors; |
1187 | 31.1k | } |
1188 | 487k | std::set<std::string> doc_keys; |
1189 | 4.16M | for (const auto& doc_entry : m_inner) { |
1190 | 4.16M | doc_keys.insert(doc_entry.m_key_name); |
1191 | 4.16M | } |
1192 | 487k | std::map<std::string, UniValue> result_obj; |
1193 | 487k | result.getObjMap(result_obj); |
1194 | 3.84M | for (const auto& result_entry : result_obj) { |
1195 | 3.84M | if (!doc_keys.contains(result_entry.first)) { |
1196 | 30 | errors.pushKV(result_entry.first, "key returned that was not in doc"); |
1197 | 30 | } |
1198 | 3.84M | } |
1199 | | |
1200 | 4.16M | for (const auto& doc_entry : m_inner) { |
1201 | 4.16M | const auto result_it{result_obj.find(doc_entry.m_key_name)}; |
1202 | 4.16M | if (result_it == result_obj.end()) { |
1203 | 318k | if (!doc_entry.m_optional) { |
1204 | 0 | errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc"); |
1205 | 0 | } |
1206 | 318k | continue; |
1207 | 318k | } |
1208 | 3.84M | UniValue match{doc_entry.MatchesType(result_it->second)}; |
1209 | 3.84M | if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match)); |
1210 | 3.84M | } |
1211 | 487k | if (errors.empty()) return true; |
1212 | 388 | return errors; |
1213 | 487k | } |
1214 | | |
1215 | 4.56M | return true; |
1216 | 5.08M | } |
1217 | | |
1218 | | void RPCResult::CheckInnerDoc() const |
1219 | 6.53M | { |
1220 | 6.53M | if (m_type == Type::OBJ) { |
1221 | | // May or may not be empty |
1222 | 782k | return; |
1223 | 782k | } |
1224 | | // Everything else must either be empty or not |
1225 | 5.74M | const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN}; |
1226 | 5.74M | CHECK_NONFATAL(inner_needed != m_inner.empty()); |
1227 | 5.74M | } |
1228 | | |
1229 | | // NOLINTNEXTLINE(misc-no-recursion) |
1230 | | std::string RPCArg::ToStringObj(const bool oneline) const |
1231 | 841 | { |
1232 | 841 | std::string res; |
1233 | 841 | res += "\""; |
1234 | 841 | res += GetFirstName(); |
1235 | 841 | if (oneline) { |
1236 | 398 | res += "\":"; |
1237 | 443 | } else { |
1238 | 443 | res += "\": "; |
1239 | 443 | } |
1240 | 841 | switch (m_type) { |
1241 | 138 | case Type::STR: |
1242 | 138 | return res + "\"str\""; |
1243 | 259 | case Type::STR_HEX: |
1244 | 259 | return res + "\"hex\""; |
1245 | 211 | case Type::NUM: |
1246 | 211 | return res + "n"; |
1247 | 69 | case Type::RANGE: |
1248 | 69 | return res + "n or [n,n]"; |
1249 | 98 | case Type::AMOUNT: |
1250 | 98 | return res + "amount"; |
1251 | 48 | case Type::BOOL: |
1252 | 48 | return res + "bool"; |
1253 | 18 | case Type::ARR: |
1254 | 18 | res += "["; |
1255 | 27 | for (const auto& i : m_inner) { |
1256 | 27 | res += i.ToString(oneline) + ","; |
1257 | 27 | } |
1258 | 18 | return res + "...]"; |
1259 | 0 | case Type::OBJ: |
1260 | 0 | case Type::OBJ_NAMED_PARAMS: |
1261 | 0 | case Type::OBJ_USER_KEYS: |
1262 | | // Currently unused, so avoid writing dead code |
1263 | 0 | NONFATAL_UNREACHABLE(); |
1264 | 841 | } // no default case, so the compiler can warn about missing cases |
1265 | 841 | NONFATAL_UNREACHABLE(); |
1266 | 841 | } |
1267 | | |
1268 | | // NOLINTNEXTLINE(misc-no-recursion) |
1269 | | std::string RPCArg::ToString(const bool oneline) const |
1270 | 2.49k | { |
1271 | 2.49k | if (oneline && !m_opts.oneline_description.empty()) { |
1272 | 86 | if (m_opts.oneline_description[0] == '\"' && m_type != Type::STR_HEX && m_type != Type::STR && gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) { |
1273 | 0 | throw std::runtime_error{ |
1274 | 0 | STR_INTERNAL_BUG(strprintf("non-string RPC arg \"%s\" quotes oneline_description:\n%s", |
1275 | 0 | m_names, m_opts.oneline_description) |
1276 | 0 | )}; |
1277 | 0 | } |
1278 | 86 | return m_opts.oneline_description; |
1279 | 86 | } |
1280 | | |
1281 | 2.40k | switch (m_type) { |
1282 | 408 | case Type::STR_HEX: |
1283 | 1.22k | case Type::STR: { |
1284 | 1.22k | return "\"" + GetFirstName() + "\""; |
1285 | 408 | } |
1286 | 398 | case Type::NUM: |
1287 | 407 | case Type::RANGE: |
1288 | 469 | case Type::AMOUNT: |
1289 | 788 | case Type::BOOL: { |
1290 | 788 | return GetFirstName(); |
1291 | 469 | } |
1292 | 116 | case Type::OBJ: |
1293 | 146 | case Type::OBJ_NAMED_PARAMS: |
1294 | 180 | case Type::OBJ_USER_KEYS: { |
1295 | | // NOLINTNEXTLINE(misc-no-recursion) |
1296 | 398 | const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); }); |
1297 | 180 | if (m_type == Type::OBJ) { |
1298 | 116 | return "{" + res + "}"; |
1299 | 116 | } else { |
1300 | 64 | return "{" + res + ",...}"; |
1301 | 64 | } |
1302 | 180 | } |
1303 | 210 | case Type::ARR: { |
1304 | 210 | std::string res; |
1305 | 259 | for (const auto& i : m_inner) { |
1306 | 259 | res += i.ToString(oneline) + ","; |
1307 | 259 | } |
1308 | 210 | return "[" + res + "...]"; |
1309 | 180 | } |
1310 | 2.40k | } // no default case, so the compiler can warn about missing cases |
1311 | 2.40k | NONFATAL_UNREACHABLE(); |
1312 | 2.40k | } |
1313 | | |
1314 | | static std::pair<int64_t, int64_t> ParseRange(const UniValue& value) |
1315 | 303 | { |
1316 | 303 | if (value.isNum()) { |
1317 | 86 | return {0, value.getInt<int64_t>()}; |
1318 | 86 | } |
1319 | 217 | if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) { |
1320 | 217 | int64_t low = value[0].getInt<int64_t>(); |
1321 | 217 | int64_t high = value[1].getInt<int64_t>(); |
1322 | 217 | if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end"); |
1323 | 213 | return {low, high}; |
1324 | 217 | } |
1325 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]"); |
1326 | 217 | } |
1327 | | |
1328 | | std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value) |
1329 | 303 | { |
1330 | 303 | int64_t low, high; |
1331 | 303 | std::tie(low, high) = ParseRange(value); |
1332 | 303 | if (low < 0) { |
1333 | 4 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0"); |
1334 | 4 | } |
1335 | 299 | if ((high >> 31) != 0) { |
1336 | 6 | throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high"); |
1337 | 6 | } |
1338 | 293 | if (high >= low + 1000000) { |
1339 | 4 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large"); |
1340 | 4 | } |
1341 | 289 | return {low, high}; |
1342 | 293 | } |
1343 | | |
1344 | | std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv) |
1345 | 1.65k | { |
1346 | 1.65k | std::string desc_str; |
1347 | 1.65k | std::pair<int64_t, int64_t> range = {0, 1000}; |
1348 | 1.65k | if (scanobject.isStr()) { |
1349 | 1.54k | desc_str = scanobject.get_str(); |
1350 | 1.54k | } else if (scanobject.isObject()) { |
1351 | 109 | const UniValue& desc_uni{scanobject.find_value("desc")}; |
1352 | 109 | if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object"); |
1353 | 109 | desc_str = desc_uni.get_str(); |
1354 | 109 | const UniValue& range_uni{scanobject.find_value("range")}; |
1355 | 109 | if (!range_uni.isNull()) { |
1356 | 100 | range = ParseDescriptorRange(range_uni); |
1357 | 100 | } |
1358 | 109 | } else { |
1359 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object"); |
1360 | 0 | } |
1361 | | |
1362 | 1.65k | std::string error; |
1363 | 1.65k | auto descs = Parse(desc_str, provider, error); |
1364 | 1.65k | if (descs.empty()) { |
1365 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); |
1366 | 1 | } |
1367 | 1.64k | if (!descs.at(0)->IsRange()) { |
1368 | 1.54k | range.first = 0; |
1369 | 1.54k | range.second = 0; |
1370 | 1.54k | } |
1371 | 1.64k | std::vector<CScript> ret; |
1372 | 23.4k | for (int64_t i = range.first; i <= range.second; ++i) { |
1373 | 21.7k | for (const auto& desc : descs) { |
1374 | 21.7k | std::vector<CScript> scripts; |
1375 | 21.7k | if (!desc->Expand(i, provider, scripts, provider)) { |
1376 | 0 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str)); |
1377 | 0 | } |
1378 | 21.7k | if (expand_priv) { |
1379 | 2.11k | desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider); |
1380 | 2.11k | } |
1381 | 21.7k | std::move(scripts.begin(), scripts.end(), std::back_inserter(ret)); |
1382 | 21.7k | } |
1383 | 21.7k | } |
1384 | 1.64k | return ret; |
1385 | 1.64k | } |
1386 | | |
1387 | | std::vector<uint32_t> ParsePathBIP32(const std::string& path) |
1388 | 30 | { |
1389 | 30 | std::vector<uint32_t> out; |
1390 | 30 | if (!ParseHDKeypath(path, out)) { |
1391 | 3 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid BIP32 keypath"); |
1392 | 3 | } |
1393 | 27 | return out; |
1394 | 30 | } |
1395 | | |
1396 | | /** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */ |
1397 | | [[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings) |
1398 | 14 | { |
1399 | 14 | CHECK_NONFATAL(!bilingual_strings.empty()); |
1400 | 14 | UniValue result{UniValue::VARR}; |
1401 | 14 | for (const auto& s : bilingual_strings) { |
1402 | 14 | result.push_back(s.original); |
1403 | 14 | } |
1404 | 14 | return result; |
1405 | 14 | } |
1406 | | |
1407 | | void PushWarnings(const UniValue& warnings, UniValue& obj) |
1408 | 848 | { |
1409 | 848 | if (warnings.empty()) return; |
1410 | 392 | obj.pushKV("warnings", warnings); |
1411 | 392 | } |
1412 | | |
1413 | | void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj) |
1414 | 1.16k | { |
1415 | 1.16k | if (warnings.empty()) return; |
1416 | 14 | obj.pushKV("warnings", BilingualStringsToUniValue(warnings)); |
1417 | 14 | } |
1418 | | |
1419 | 53.7k | std::vector<RPCResult> ScriptPubKeyDoc() { |
1420 | 53.7k | return |
1421 | 53.7k | { |
1422 | 53.7k | {RPCResult::Type::STR, "asm", "Disassembly of the output script"}, |
1423 | 53.7k | {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"}, |
1424 | 53.7k | {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"}, |
1425 | 53.7k | {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"}, |
1426 | 53.7k | {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"}, |
1427 | 53.7k | }; |
1428 | 53.7k | } |
1429 | | |
1430 | | uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit) |
1431 | 20.9k | { |
1432 | 20.9k | arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))}; |
1433 | 20.9k | return ArithToUint256(target); |
1434 | 20.9k | } |
1435 | | |
1436 | | std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary) |
1437 | 33.8k | { |
1438 | 33.8k | if (fields.empty()) return fields; |
1439 | 33.8k | std::vector<RPCResult> result; |
1440 | 33.8k | result.reserve(fields.size()); |
1441 | 264k | for (size_t i = 0; i < fields.size(); ++i) { |
1442 | 230k | RPCResultOptions opts = fields[i].m_opts; |
1443 | 230k | if (i == 0) { |
1444 | 33.8k | opts.print_elision = summary; |
1445 | 197k | } else { |
1446 | 197k | opts.print_elision = HelpElisionSkip{}; |
1447 | 197k | } |
1448 | 230k | result.emplace_back(fields[i], std::move(opts)); |
1449 | 230k | } |
1450 | 33.8k | return result; |
1451 | 33.8k | } |