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