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 <memory>
34 : : #include <ranges>
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 : 1096 : std::string GetAllOutputTypes()
53 : : {
54 : 1096 : std::vector<std::string> ret;
55 : 1096 : using U = std::underlying_type_t<TxoutType>;
56 [ + + ]: 13152 : for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
57 [ + - + - ]: 24112 : ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
58 : : }
59 [ + - ]: 2192 : return Join(ret, ", ");
60 : 1096 : }
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 : 151 : CAmount AmountFromValue(const UniValue& value, int decimals)
105 : : {
106 [ + + - + ]: 151 : if (!value.isNum() && !value.isStr())
107 [ # # # # ]: 0 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
108 : 151 : int64_t amount;
109 [ - + + + ]: 151 : if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
110 [ + - + - ]: 18 : throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
111 [ + + ]: 142 : if (!MoneyRange(amount))
112 [ + - + - ]: 2 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
113 : 141 : 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 : 93 : std::string ShellQuote(const std::string& s)
158 : : {
159 [ - + ]: 93 : std::string result;
160 [ - + + - ]: 93 : result.reserve(s.size() * 2);
161 [ - + + + ]: 7717 : for (const char ch: s) {
162 [ + + ]: 7624 : if (ch == '\'') {
163 [ + - ]: 1 : result += "'\''";
164 : : } else {
165 [ + - ]: 15247 : result += ch;
166 : : }
167 : : }
168 [ + - ]: 186 : return "'" + result + "'";
169 : 93 : }
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 : 326 : std::string ShellQuoteIfNeeded(const std::string& s)
177 : : {
178 [ - + + + ]: 2051 : for (const char ch: s) {
179 [ + + + + ]: 1818 : if (ch == ' ' || ch == '\'' || ch == '"') {
180 : 93 : return ShellQuote(s);
181 : : }
182 : : }
183 : :
184 [ - + ]: 233 : return s;
185 : : }
186 : :
187 : : }
188 : :
189 : 15188 : std::string HelpExampleCli(const std::string& methodname, const std::string& args)
190 : : {
191 [ + - + - ]: 45564 : return "> bitcoin-cli " + methodname + " " + args + "\n";
192 : : }
193 : :
194 : 152 : std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
195 : : {
196 : 152 : std::string result = "> bitcoin-cli -named " + methodname;
197 [ + + ]: 478 : for (const auto& argpair: args) {
198 [ + + ]: 326 : const auto& value = argpair.second.isStr()
199 [ + + + - : 326 : ? argpair.second.get_str()
- + ]
200 [ + - ]: 135 : : argpair.second.write();
201 [ + - + - : 978 : result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
+ - ]
202 : 326 : }
203 [ + - ]: 152 : result += '\n';
204 : 152 : return result;
205 : 0 : }
206 : :
207 : 10935 : std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
208 : : {
209 : 10935 : return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
210 [ + - + - ]: 32805 : "\"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 [ + - ]: 282 : 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 : 12816 : RPCMethod::RPCMethod(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
557 : 12824 : : m_name{std::move(name)},
558 : 12824 : m_fun{std::move(fun)},
559 : 12824 : m_description{std::move(description)},
560 [ + - ]: 12816 : m_args{std::move(args)},
561 [ + - ]: 12824 : m_results{std::move(results)},
562 [ - + ]: 12824 : 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 : 12816 : enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
568 : 12816 : std::map<std::string, int> param_names;
569 : :
570 [ + + ]: 33310 : for (const auto& arg : m_args) {
571 [ - + + - ]: 20502 : std::vector<std::string> names = SplitString(arg.m_names, '|');
572 : : // Should have unique named arguments
573 [ + + ]: 41182 : for (const std::string& name : names) {
574 [ + - ]: 20682 : auto& param_type = param_names[name];
575 [ + + ]: 20682 : CHECK_NONFATAL(!(param_type & POSITIONAL));
576 [ + + ]: 20681 : CHECK_NONFATAL(!(param_type & NAMED_ONLY));
577 : 20680 : param_type |= POSITIONAL;
578 : : }
579 [ + + ]: 20500 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
580 [ + + ]: 2576 : for (const auto& inner : arg.m_inner) {
581 [ - + + - ]: 2059 : std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
582 [ + + ]: 4281 : for (const std::string& inner_name : inner_names) {
583 [ + - ]: 2228 : auto& param_type = param_names[inner_name];
584 [ + + + + : 2230 : CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
+ + ]
585 [ + + ]: 2226 : CHECK_NONFATAL(!(param_type & NAMED));
586 [ + + ]: 2224 : CHECK_NONFATAL(!(param_type & NAMED_ONLY));
587 [ + + ]: 4294 : param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
588 : : }
589 : 2059 : }
590 : : }
591 : : // Default value type should match argument type only when defined
592 [ + + ]: 20494 : if (arg.m_fallback.index() == 2) {
593 : 5717 : const RPCArg::Type type = arg.m_type;
594 : 11434 : [&]() {
595 [ - + - + : 5717 : 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 : 1148 : case UniValue::VSTR:
603 [ + + - + ]: 1148 : CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
604 : 1148 : return;
605 : 2211 : case UniValue::VNUM:
606 [ - + - - ]: 2211 : CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
607 : 2211 : return;
608 : 2330 : case UniValue::VBOOL:
609 : 2330 : CHECK_NONFATAL(type == RPCArg::Type::BOOL);
610 : 2330 : 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 [ + - ]: 5717 : }();
617 : : }
618 : 20502 : }
619 : 12848 : }
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 : 61 : static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
697 : : {
698 [ - + ]: 61 : CHECK_NONFATAL(i < params.size());
699 : 61 : const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
700 : 61 : const RPCArg& param{params.at(i)};
701 [ + + ]: 61 : if (check) check(param);
702 : :
703 [ + + ]: 61 : if (!arg.isNull()) return &arg;
704 [ + + ]: 25 : if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
705 : 23 : return &std::get<RPCArg::Default>(param.m_fallback);
706 : : }
707 : :
708 : 57 : static void CheckRequiredOrDefault(const RPCArg& param)
709 : : {
710 : : // Must use `Arg<Type>(key)` to get the argument or its default value.
711 : 57 : const bool required{
712 [ + + - + ]: 57 : std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
713 : 57 : };
714 [ + + + - ]: 86 : CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
715 : 57 : }
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 : 2 : TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg););
737 : 9 : TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
738 : 0 : TMPL_INST(CheckRequiredOrDefault, double, CHECK_NONFATAL(maybe_arg)->get_real(););
739 : 2 : TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
740 : 7 : TMPL_INST(CheckRequiredOrDefault, int64_t, CHECK_NONFATAL(maybe_arg)->getInt<int64_t>(););
741 : 2 : TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
742 : 7 : TMPL_INST(CheckRequiredOrDefault, uint32_t, CHECK_NONFATAL(maybe_arg)->getInt<uint32_t>(););
743 [ - + ]: 28 : TMPL_INST(CheckRequiredOrDefault, std::string_view, CHECK_NONFATAL(maybe_arg)->get_str(););
744 : :
745 : 57 : bool RPCMethod::IsValidNumArgs(size_t num_args) const
746 : : {
747 : 57 : size_t num_required_args = 0;
748 [ - + + + ]: 143 : for (size_t n = m_args.size(); n > 0; --n) {
749 [ + + ]: 126 : if (!m_args.at(n - 1).IsOptional()) {
750 : : num_required_args = n;
751 : : break;
752 : : }
753 : : }
754 [ + + - + : 57 : return num_required_args <= num_args && num_args <= m_args.size();
+ + ]
755 : : }
756 : :
757 : 6367 : std::vector<std::pair<std::string, bool>> RPCMethod::GetArgNames() const
758 : : {
759 : 6367 : std::vector<std::pair<std::string, bool>> ret;
760 [ - + + - ]: 6367 : ret.reserve(m_args.size());
761 [ + + ]: 16525 : for (const auto& arg : m_args) {
762 [ + + ]: 10158 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
763 [ + + ]: 1270 : for (const auto& inner : arg.m_inner) {
764 [ + - ]: 1017 : ret.emplace_back(inner.m_names, /*named_only=*/true);
765 : : }
766 : : }
767 [ + - ]: 10158 : ret.emplace_back(arg.m_names, /*named_only=*/false);
768 : : }
769 : 6367 : return ret;
770 : 0 : }
771 : :
772 : 63 : size_t RPCMethod::GetParamIndex(std::string_view key) const
773 : : {
774 : : // Use only the first name, so that callers are uniform and legacy aliases can be removed.
775 [ - + ]: 259 : auto it{std::ranges::find_if(m_args, [&key](const auto& arg) { return arg.GetFirstName() == key; })};
776 : :
777 : 63 : CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time
778 : 61 : return std::distance(m_args.begin(), it);
779 : : }
780 : :
781 : 6 : std::string RPCMethod::ToString() const
782 : : {
783 [ - + ]: 6 : std::string ret;
784 : :
785 : : // Oneline summary
786 [ - + ]: 6 : ret += m_name;
787 : 6 : bool was_optional{false};
788 [ + + ]: 25 : for (const auto& arg : m_args) {
789 [ + - ]: 19 : if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
790 [ + - ]: 19 : const bool optional = arg.IsOptional();
791 [ + - ]: 19 : ret += ' ';
792 [ + + ]: 19 : if (optional) {
793 [ + + + - ]: 11 : if (!was_optional) ret += "( ";
794 : : was_optional = true;
795 : : } else {
796 [ - + - - ]: 8 : if (was_optional) ret += ") ";
797 : : was_optional = false;
798 : : }
799 [ + - ]: 38 : ret += arg.ToString(/*oneline=*/true);
800 : : }
801 [ + - + - ]: 6 : if (was_optional) ret += " )";
802 : :
803 : : // Description
804 [ - + + - ]: 12 : CHECK_NONFATAL(!m_description.starts_with('\n')); // Historically \n was required, but reject it for new code.
805 [ - + + - : 18 : ret += "\n\n" + TrimString(m_description) + "\n";
+ - - + ]
806 : :
807 : : // Arguments
808 : 6 : Sections sections;
809 : 6 : Sections named_only_sections;
810 [ - + + + ]: 25 : for (size_t i{0}; i < m_args.size(); ++i) {
811 [ + - ]: 19 : const auto& arg = m_args.at(i);
812 [ + - ]: 19 : if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
813 : :
814 : : // Push named argument name and description
815 [ + - + - : 57 : sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
+ - + - +
- ]
816 [ - + + + ]: 19 : sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
817 : :
818 : : // Recursively push nested args
819 [ + - ]: 19 : sections.Push(arg);
820 : :
821 : : // Push named-only argument sections
822 [ - + ]: 19 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
823 [ # # ]: 0 : for (const auto& arg_inner : arg.m_inner) {
824 [ # # # # : 0 : named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
# # # # ]
825 [ # # ]: 0 : named_only_sections.Push(arg_inner);
826 : : }
827 : : }
828 : : }
829 : :
830 [ + - + - ]: 6 : if (!sections.m_sections.empty()) ret += "\nArguments:\n";
831 [ + - ]: 12 : ret += sections.ToString();
832 [ - + - - ]: 6 : if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
833 [ + - ]: 12 : ret += named_only_sections.ToString();
834 : :
835 : : // Result
836 [ + - ]: 12 : ret += m_results.ToDescriptionString();
837 : :
838 : : // Examples
839 [ + - ]: 12 : ret += m_examples.ToDescriptionString();
840 : :
841 : 6 : return ret;
842 : 6 : }
843 : :
844 : 0 : UniValue RPCMethod::GetArgMap() const
845 : : {
846 : 0 : UniValue arr{UniValue::VARR};
847 : :
848 : 0 : auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
849 : 0 : UniValue map{UniValue::VARR};
850 [ # # # # ]: 0 : map.push_back(rpc_name);
851 [ # # # # ]: 0 : map.push_back(pos);
852 [ # # # # ]: 0 : map.push_back(arg_name);
853 [ # # # # ]: 0 : map.push_back(type == RPCArg::Type::STR ||
854 : : type == RPCArg::Type::STR_HEX);
855 [ # # ]: 0 : arr.push_back(std::move(map));
856 : 0 : };
857 : :
858 [ # # # # ]: 0 : for (int i{0}; i < int(m_args.size()); ++i) {
859 [ # # ]: 0 : const auto& arg = m_args.at(i);
860 [ # # # # ]: 0 : std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
861 [ # # ]: 0 : for (const auto& arg_name : arg_names) {
862 [ # # ]: 0 : push_back_arg_info(m_name, i, arg_name, arg.m_type);
863 [ # # ]: 0 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
864 [ # # ]: 0 : for (const auto& inner : arg.m_inner) {
865 [ # # # # ]: 0 : std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
866 [ # # ]: 0 : for (const std::string& inner_name : inner_names) {
867 [ # # ]: 0 : push_back_arg_info(m_name, i, inner_name, inner.m_type);
868 : : }
869 : 0 : }
870 : : }
871 : : }
872 : 0 : }
873 : 0 : return arr;
874 : 0 : }
875 : :
876 : 61 : static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
877 : : {
878 : 61 : using Type = RPCArg::Type;
879 [ + + - - : 61 : switch (type) {
+ - + - ]
880 : 37 : case Type::STR_HEX:
881 : 37 : case Type::STR: {
882 : 37 : return UniValue::VSTR;
883 : : }
884 : 6 : case Type::NUM: {
885 : 6 : return UniValue::VNUM;
886 : : }
887 : 0 : case Type::AMOUNT: {
888 : : // VNUM or VSTR, checked inside AmountFromValue()
889 : 0 : return std::nullopt;
890 : : }
891 : 0 : case Type::RANGE: {
892 : : // VNUM or VARR, checked inside ParseRange()
893 : 0 : return std::nullopt;
894 : : }
895 : 5 : case Type::BOOL: {
896 : 5 : return UniValue::VBOOL;
897 : : }
898 : 0 : case Type::OBJ:
899 : 0 : case Type::OBJ_NAMED_PARAMS:
900 : 0 : case Type::OBJ_USER_KEYS: {
901 : 0 : return UniValue::VOBJ;
902 : : }
903 : 13 : case Type::ARR: {
904 : 13 : return UniValue::VARR;
905 : : }
906 : : } // no default case, so the compiler can warn about missing cases
907 : 0 : NONFATAL_UNREACHABLE();
908 : : }
909 : :
910 : 134 : UniValue RPCArg::MatchesType(const UniValue& request) const
911 : : {
912 [ + + ]: 134 : if (m_opts.skip_type_check) return true;
913 [ + + + + ]: 124 : if (IsOptional() && request.isNull()) return true;
914 : 61 : const auto exp_type{ExpectedType(m_type)};
915 [ - + ]: 61 : if (!exp_type) return true; // nothing to check
916 : :
917 [ + + ]: 61 : if (*exp_type != request.getType()) {
918 [ + - ]: 4 : return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type));
919 : : }
920 : 59 : return true;
921 : : }
922 : :
923 : 244 : std::string RPCArg::GetFirstName() const
924 : : {
925 : 244 : return m_names.substr(0, m_names.find('|'));
926 : : }
927 : :
928 : 0 : std::string RPCArg::GetName() const
929 : : {
930 : 0 : CHECK_NONFATAL(std::string::npos == m_names.find('|'));
931 [ # # ]: 0 : return m_names;
932 : : }
933 : :
934 : 271 : bool RPCArg::IsOptional() const
935 : : {
936 [ + + ]: 271 : if (m_fallback.index() != 0) {
937 : : return true;
938 : : } else {
939 : 114 : return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
940 : : }
941 : : }
942 : :
943 : 27 : std::string RPCArg::ToDescriptionString(bool is_named_arg) const
944 : : {
945 [ + - ]: 27 : std::string ret;
946 [ + - ]: 27 : ret += '(';
947 [ - + - + ]: 27 : if (m_opts.type_str.size() != 0) {
948 [ # # # # ]: 0 : ret += m_opts.type_str.at(1);
949 : : } else {
950 [ + + + - : 27 : switch (m_type) {
+ + + - ]
951 : 9 : case Type::STR_HEX:
952 : 9 : case Type::STR: {
953 [ + - ]: 9 : ret += "string";
954 : : break;
955 : : }
956 : 6 : case Type::NUM: {
957 [ + - ]: 6 : ret += "numeric";
958 : : break;
959 : : }
960 : 3 : case Type::AMOUNT: {
961 [ + - ]: 3 : ret += "numeric or string";
962 : : break;
963 : : }
964 : 0 : case Type::RANGE: {
965 [ # # ]: 0 : ret += "numeric or array";
966 : : break;
967 : : }
968 : 4 : case Type::BOOL: {
969 [ + - ]: 4 : ret += "boolean";
970 : : break;
971 : : }
972 : 3 : case Type::OBJ:
973 : 3 : case Type::OBJ_NAMED_PARAMS:
974 : 3 : case Type::OBJ_USER_KEYS: {
975 [ + - ]: 3 : ret += "json object";
976 : : break;
977 : : }
978 : 2 : case Type::ARR: {
979 [ + - + + ]: 27 : ret += "json array";
980 : : break;
981 : : }
982 : : } // no default case, so the compiler can warn about missing cases
983 : : }
984 [ + + ]: 27 : if (m_fallback.index() == 1) {
985 [ + - ]: 6 : ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
986 [ + + ]: 24 : } else if (m_fallback.index() == 2) {
987 [ + - + - ]: 16 : ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
988 : : } else {
989 [ - + + + : 16 : switch (std::get<RPCArg::Optional>(m_fallback)) {
- ]
990 : 4 : case RPCArg::Optional::OMITTED: {
991 [ + + + - ]: 4 : if (is_named_arg) ret += ", optional"; // Default value is "null" in dicts. Otherwise,
992 : : // nothing to do. Element is treated as if not present and has no default value
993 : : break;
994 : : }
995 : 12 : case RPCArg::Optional::NO: {
996 [ + - ]: 12 : ret += ", required";
997 : : break;
998 : : }
999 : : } // no default case, so the compiler can warn about missing cases
1000 : : }
1001 [ + - ]: 27 : ret += ')';
1002 [ - + - - ]: 27 : if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
1003 [ + + + - : 54 : ret += m_description.empty() ? "" : " " + m_description;
+ - ]
1004 : 27 : return ret;
1005 : 0 : }
1006 : :
1007 : : // NOLINTNEXTLINE(misc-no-recursion)
1008 : 133 : void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1009 : : {
1010 : : // Indentation
1011 [ + - ]: 133 : const std::string indent(current_indent, ' ');
1012 [ + - + + ]: 133 : const std::string indent_next(current_indent + 2, ' ');
1013 : :
1014 : : // Elements in a JSON structure (dictionary or array) are separated by a comma
1015 [ + + + - ]: 141 : const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1016 : :
1017 : : // The key name if recursed into a dictionary
1018 : 133 : const std::string maybe_key{
1019 [ + + ]: 133 : outer_type == OuterType::OBJ ?
1020 [ + - - - ]: 115 : "\"" + this->m_key_name + "\" : " :
1021 [ + - + - ]: 248 : ""};
1022 : :
1023 : : // Format description with type
1024 : 245 : const auto Description = [&](const std::string& type) {
1025 [ + + + - : 421 : return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
+ - ]
1026 [ + + + - ]: 336 : (this->m_description.empty() ? "" : " " + this->m_description);
1027 : 133 : };
1028 : :
1029 : : // Ensure at least one visible field exists when elision is used
1030 : 162 : const auto elision_has_description{[](const std::vector<RPCResult>& inner) {
1031 : 58 : return std::ranges::any_of(inner, [](const auto& res) {
1032 [ - + ]: 29 : return !std::holds_alternative<HelpElisionSkip>(res.m_opts.print_elision);
1033 : : });
1034 : : }};
1035 : :
1036 : 133 : if (const auto* text = std::get_if<std::string>(&m_opts.print_elision)) {
1037 [ + - + - : 4 : sections.PushSection({indent + "..." + maybe_separator, *text});
+ - + - ]
1038 : 2 : return;
1039 : : }
1040 [ + + ]: 131 : if (std::holds_alternative<HelpElisionSkip>(m_opts.print_elision)) {
1041 : : return;
1042 : : }
1043 : :
1044 [ - + + + : 112 : switch (m_type) {
+ + + + +
+ - ]
1045 : 0 : case Type::ANY: {
1046 [ # # # # : 0 : sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("any")});
# # # # #
# # # ]
1047 : 0 : return;
1048 : : }
1049 : 1 : case Type::NONE: {
1050 [ + - + - : 2 : sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
+ - + - +
- + - ]
1051 : 1 : return;
1052 : : }
1053 : 20 : case Type::STR: {
1054 [ + - + - : 60 : sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
+ - + - +
- + - ]
1055 : 20 : return;
1056 : : }
1057 : 4 : case Type::STR_AMOUNT: {
1058 [ + - + - : 12 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1059 : 4 : return;
1060 : : }
1061 : 26 : case Type::STR_HEX: {
1062 [ + - + - : 78 : sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
+ - + - +
- + - ]
1063 : 26 : return;
1064 : : }
1065 : 26 : case Type::NUM: {
1066 [ + - + - : 78 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1067 : 26 : return;
1068 : : }
1069 : 4 : case Type::NUM_TIME: {
1070 [ + - + - : 12 : sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1071 : 4 : return;
1072 : : }
1073 : 2 : case Type::BOOL: {
1074 [ + - + - : 6 : sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
+ - + - +
- + - ]
1075 : 2 : return;
1076 : : }
1077 : 10 : case Type::ARR_FIXED:
1078 : 10 : case Type::ARR: {
1079 [ + - + - : 30 : sections.PushSection({indent + maybe_key + "[", Description("json array")});
+ - + - +
- ]
1080 [ + + ]: 20 : for (const auto& i : m_inner) {
1081 [ + - ]: 10 : i.ToSections(sections, OuterType::ARR, current_indent + 2);
1082 : : }
1083 [ + - ]: 10 : CHECK_NONFATAL(!m_inner.empty());
1084 [ + - ]: 10 : CHECK_NONFATAL(elision_has_description(m_inner));
1085 [ + - - + ]: 10 : if (m_type == Type::ARR && !std::holds_alternative<std::string>(m_inner.back().m_opts.print_elision)) {
1086 [ + - + - : 20 : sections.PushSection({indent_next + "...", ""});
+ - + - ]
1087 : : } else {
1088 : : // Remove final comma, which would be invalid JSON
1089 : 0 : sections.m_sections.back().m_left.pop_back();
1090 : : }
1091 [ + - + - : 20 : sections.PushSection({indent + "]" + maybe_separator, ""});
+ - + - +
- ]
1092 : 10 : return;
1093 : : }
1094 : 19 : case Type::OBJ_DYN:
1095 : 19 : case Type::OBJ: {
1096 [ - + ]: 19 : if (m_inner.empty()) {
1097 [ # # # # : 0 : sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
# # # # #
# ]
1098 : 0 : return;
1099 : : }
1100 [ + - ]: 19 : CHECK_NONFATAL(elision_has_description(m_inner));
1101 [ + - + - : 57 : sections.PushSection({indent + maybe_key + "{", Description("json object")});
+ - + - +
- ]
1102 [ + + ]: 134 : for (const auto& i : m_inner) {
1103 [ + - ]: 115 : i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1104 : : }
1105 [ - + ]: 19 : if (m_type == Type::OBJ_DYN) {
1106 : : // If the dictionary keys are dynamic, use three dots for continuation
1107 [ # # # # : 0 : sections.PushSection({indent_next + "...", ""});
# # # # ]
1108 : : } else {
1109 : : // Remove final comma, which would be invalid JSON
1110 : 19 : sections.m_sections.back().m_left.pop_back();
1111 : : }
1112 [ + - + - : 38 : sections.PushSection({indent + "}" + maybe_separator, ""});
+ - + - +
- ]
1113 : 19 : return;
1114 : : }
1115 : : } // no default case, so the compiler can warn about missing cases
1116 : 0 : NONFATAL_UNREACHABLE();
1117 : 133 : }
1118 : :
1119 : 0 : static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1120 : : {
1121 : 0 : using Type = RPCResult::Type;
1122 [ # # # # : 0 : switch (type) {
# # # # ]
1123 : 0 : case Type::ANY: {
1124 : 0 : return std::nullopt;
1125 : : }
1126 : 0 : case Type::NONE: {
1127 : 0 : return UniValue::VNULL;
1128 : : }
1129 : 0 : case Type::STR:
1130 : 0 : case Type::STR_HEX: {
1131 : 0 : return UniValue::VSTR;
1132 : : }
1133 : 0 : case Type::NUM:
1134 : 0 : case Type::STR_AMOUNT:
1135 : 0 : case Type::NUM_TIME: {
1136 : 0 : return UniValue::VNUM;
1137 : : }
1138 : 0 : case Type::BOOL: {
1139 : 0 : return UniValue::VBOOL;
1140 : : }
1141 : 0 : case Type::ARR_FIXED:
1142 : 0 : case Type::ARR: {
1143 : 0 : return UniValue::VARR;
1144 : : }
1145 : 0 : case Type::OBJ_DYN:
1146 : 0 : case Type::OBJ: {
1147 : 0 : return UniValue::VOBJ;
1148 : : }
1149 : : } // no default case, so the compiler can warn about missing cases
1150 : 0 : NONFATAL_UNREACHABLE();
1151 : : }
1152 : :
1153 : : // NOLINTNEXTLINE(misc-no-recursion)
1154 : 0 : UniValue RPCResult::MatchesType(const UniValue& result) const
1155 : : {
1156 [ # # ]: 0 : if (m_opts.skip_type_check) {
1157 : 0 : return true;
1158 : : }
1159 : :
1160 : 0 : const auto exp_type = ExpectedType(m_type);
1161 [ # # ]: 0 : if (!exp_type) return true; // can be any type, so nothing to check
1162 : :
1163 [ # # ]: 0 : if (*exp_type != result.getType()) {
1164 [ # # ]: 0 : return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1165 : : }
1166 : :
1167 [ # # ]: 0 : if (UniValue::VARR == result.getType()) {
1168 : 0 : UniValue errors(UniValue::VOBJ);
1169 [ # # # # : 0 : for (size_t i{0}; i < result.get_array().size(); ++i) {
# # ]
1170 : : // If there are more results than documented, reuse the last doc_inner.
1171 [ # # # # : 0 : const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
# # ]
1172 [ # # # # : 0 : UniValue match{doc_inner.MatchesType(result.get_array()[i])};
# # ]
1173 [ # # # # : 0 : if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
# # ]
1174 : 0 : }
1175 [ # # # # : 0 : if (errors.empty()) return true; // empty result array is valid
# # ]
1176 : 0 : return errors;
1177 : 0 : }
1178 : :
1179 [ # # ]: 0 : if (UniValue::VOBJ == result.getType()) {
1180 : 0 : UniValue errors(UniValue::VOBJ);
1181 [ # # ]: 0 : if (m_type == Type::OBJ_DYN) {
1182 [ # # ]: 0 : const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first
1183 [ # # # # : 0 : for (size_t i{0}; i < result.get_obj().size(); ++i) {
# # ]
1184 [ # # # # : 0 : UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
# # ]
1185 [ # # # # : 0 : if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match));
# # # # ]
1186 : 0 : }
1187 [ # # # # : 0 : if (errors.empty()) return true; // empty result obj is valid
# # ]
1188 : 0 : return errors;
1189 : : }
1190 : 0 : std::set<std::string> doc_keys;
1191 [ # # ]: 0 : for (const auto& doc_entry : m_inner) {
1192 [ # # ]: 0 : doc_keys.insert(doc_entry.m_key_name);
1193 : : }
1194 [ # # ]: 0 : std::map<std::string, UniValue> result_obj;
1195 [ # # ]: 0 : result.getObjMap(result_obj);
1196 [ # # ]: 0 : for (const auto& result_entry : result_obj) {
1197 [ # # ]: 0 : if (!doc_keys.contains(result_entry.first)) {
1198 [ # # # # : 0 : errors.pushKV(result_entry.first, "key returned that was not in doc");
# # ]
1199 : : }
1200 : : }
1201 : :
1202 [ # # ]: 0 : for (const auto& doc_entry : m_inner) {
1203 : 0 : const auto result_it{result_obj.find(doc_entry.m_key_name)};
1204 [ # # ]: 0 : if (result_it == result_obj.end()) {
1205 [ # # ]: 0 : if (!doc_entry.m_optional) {
1206 [ # # # # : 0 : errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc");
# # ]
1207 : : }
1208 : 0 : continue;
1209 : : }
1210 [ # # ]: 0 : UniValue match{doc_entry.MatchesType(result_it->second)};
1211 [ # # # # : 0 : if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match));
# # ]
1212 : 0 : }
1213 [ # # # # : 0 : if (errors.empty()) return true;
# # ]
1214 : 0 : return errors;
1215 : 0 : }
1216 : :
1217 : 0 : return true;
1218 : : }
1219 : :
1220 : 145309 : void RPCResult::CheckInnerDoc() const
1221 : : {
1222 [ + + ]: 145309 : if (m_type == Type::OBJ) {
1223 : : // May or may not be empty
1224 : : return;
1225 : : }
1226 : : // Everything else must either be empty or not
1227 [ + + + + ]: 124810 : const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
1228 : 124810 : CHECK_NONFATAL(inner_needed != m_inner.empty());
1229 : : }
1230 : :
1231 : : // NOLINTNEXTLINE(misc-no-recursion)
1232 : 10 : std::string RPCArg::ToStringObj(const bool oneline) const
1233 : : {
1234 [ + - ]: 10 : std::string res;
1235 [ + - ]: 10 : res += '\"';
1236 [ + - ]: 20 : res += GetFirstName();
1237 [ + + ]: 10 : if (oneline) {
1238 [ + - ]: 5 : res += "\":";
1239 : : } else {
1240 [ + - ]: 5 : res += "\": ";
1241 : : }
1242 [ - + + - : 10 : switch (m_type) {
+ - - -
- ]
1243 : 0 : case Type::STR:
1244 [ # # ]: 0 : return res + "\"str\"";
1245 : 4 : case Type::STR_HEX:
1246 [ + - ]: 4 : return res + "\"hex\"";
1247 : 4 : case Type::NUM:
1248 [ + - ]: 4 : return res + "n";
1249 : 0 : case Type::RANGE:
1250 [ # # ]: 0 : return res + "n or [n,n]";
1251 : 2 : case Type::AMOUNT:
1252 [ + - ]: 2 : return res + "amount";
1253 : 0 : case Type::BOOL:
1254 [ # # ]: 0 : return res + "bool";
1255 : 0 : case Type::ARR:
1256 [ # # ]: 0 : res += '[';
1257 [ # # ]: 0 : for (const auto& i : m_inner) {
1258 [ # # # # ]: 0 : res += i.ToString(oneline) + ",";
1259 : : }
1260 [ # # ]: 0 : return res + "...]";
1261 : 0 : case Type::OBJ:
1262 : 0 : case Type::OBJ_NAMED_PARAMS:
1263 : 0 : case Type::OBJ_USER_KEYS:
1264 : : // Currently unused, so avoid writing dead code
1265 : 0 : NONFATAL_UNREACHABLE();
1266 : : } // no default case, so the compiler can warn about missing cases
1267 : 0 : NONFATAL_UNREACHABLE();
1268 : 10 : }
1269 : :
1270 : : // NOLINTNEXTLINE(misc-no-recursion)
1271 : 22 : std::string RPCArg::ToString(const bool oneline) const
1272 : : {
1273 [ + - - + ]: 22 : if (oneline && !m_opts.oneline_description.empty()) {
1274 [ # # # # : 0 : if (m_opts.oneline_description[0] == '\"' && m_type != Type::STR_HEX && m_type != Type::STR && gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
# # # # #
# # # ]
1275 : 0 : throw std::runtime_error{
1276 [ # # # # ]: 0 : STR_INTERNAL_BUG(strprintf("non-string RPC arg \"%s\" quotes oneline_description:\n%s",
1277 : : m_names, m_opts.oneline_description)
1278 [ # # ]: 0 : )};
1279 : : }
1280 [ # # ]: 0 : return m_opts.oneline_description;
1281 : : }
1282 : :
1283 [ + + + + : 22 : switch (m_type) {
- ]
1284 : 7 : case Type::STR_HEX:
1285 : 7 : case Type::STR: {
1286 [ + - ]: 14 : return "\"" + GetFirstName() + "\"";
1287 : : }
1288 : 10 : case Type::NUM:
1289 : 10 : case Type::RANGE:
1290 : 10 : case Type::AMOUNT:
1291 : 10 : case Type::BOOL: {
1292 : 10 : return GetFirstName();
1293 : : }
1294 : 3 : case Type::OBJ:
1295 : 3 : case Type::OBJ_NAMED_PARAMS:
1296 : 3 : case Type::OBJ_USER_KEYS: {
1297 : : // NOLINTNEXTLINE(misc-no-recursion)
1298 [ + - ]: 8 : const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
1299 [ + + ]: 3 : if (m_type == Type::OBJ) {
1300 [ + - ]: 4 : return "{" + res + "}";
1301 : : } else {
1302 [ + - ]: 2 : return "{" + res + ",...}";
1303 : : }
1304 : 3 : }
1305 : 2 : case Type::ARR: {
1306 : 2 : std::string res;
1307 [ + + ]: 5 : for (const auto& i : m_inner) {
1308 [ + - - + ]: 9 : res += i.ToString(oneline) + ",";
1309 : : }
1310 [ + - ]: 4 : return "[" + res + "...]";
1311 : 2 : }
1312 : : } // no default case, so the compiler can warn about missing cases
1313 : 0 : NONFATAL_UNREACHABLE();
1314 : : }
1315 : :
1316 : 0 : static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
1317 : : {
1318 [ # # ]: 0 : if (value.isNum()) {
1319 : 0 : return {0, value.getInt<int64_t>()};
1320 : : }
1321 [ # # # # : 0 : if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
# # # # ]
1322 : 0 : int64_t low = value[0].getInt<int64_t>();
1323 : 0 : int64_t high = value[1].getInt<int64_t>();
1324 : 0 : return {low, high};
1325 : : }
1326 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1327 : : }
1328 : :
1329 : 0 : std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1330 : : {
1331 : 0 : int64_t low, high;
1332 : 0 : std::tie(low, high) = ParseRange(value);
1333 [ # # ]: 0 : if (auto res = CheckDescriptorRangeBounds(low, high); !res) {
1334 [ # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, res.error());
1335 : 0 : }
1336 : 0 : return {low, high};
1337 : : }
1338 : :
1339 : 0 : std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1340 : : {
1341 [ # # ]: 0 : std::string desc_str;
1342 : 0 : std::pair<int64_t, int64_t> range = {0, 1000};
1343 [ # # ]: 0 : if (scanobject.isStr()) {
1344 [ # # # # ]: 0 : desc_str = scanobject.get_str();
1345 [ # # ]: 0 : } else if (scanobject.isObject()) {
1346 [ # # ]: 0 : const UniValue& desc_uni{scanobject.find_value("desc")};
1347 [ # # # # : 0 : if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
# # ]
1348 [ # # # # ]: 0 : desc_str = desc_uni.get_str();
1349 [ # # ]: 0 : const UniValue& range_uni{scanobject.find_value("range")};
1350 [ # # ]: 0 : if (!range_uni.isNull()) {
1351 [ # # ]: 0 : range = ParseDescriptorRange(range_uni);
1352 : : }
1353 : : } else {
1354 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1355 : : }
1356 : :
1357 [ # # ]: 0 : std::string error;
1358 [ # # # # ]: 0 : auto descs = Parse(desc_str, provider, error);
1359 [ # # ]: 0 : if (descs.empty()) {
1360 [ # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1361 : : }
1362 [ # # # # : 0 : if (!descs.at(0)->IsRange()) {
# # ]
1363 : 0 : range.first = 0;
1364 : 0 : range.second = 0;
1365 : : }
1366 : 0 : std::vector<CScript> ret;
1367 [ # # ]: 0 : for (int64_t i = range.first; i <= range.second; ++i) {
1368 [ # # ]: 0 : for (const auto& desc : descs) {
1369 : 0 : std::vector<CScript> scripts;
1370 [ # # # # ]: 0 : if (!desc->Expand(i, provider, scripts, provider)) {
1371 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
1372 : : }
1373 [ # # ]: 0 : if (expand_priv) {
1374 [ # # ]: 0 : desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1375 : : }
1376 [ # # ]: 0 : std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1377 : 0 : }
1378 : : }
1379 : 0 : return ret;
1380 : 0 : }
1381 : :
1382 : 0 : std::vector<uint32_t> ParsePathBIP32(const std::string& path)
1383 : : {
1384 : 0 : std::vector<uint32_t> out;
1385 [ # # # # ]: 0 : if (!ParseHDKeypath(path, out)) {
1386 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid BIP32 keypath");
1387 : : }
1388 : 0 : return out;
1389 : 0 : }
1390 : :
1391 : : /** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */
1392 : 0 : [[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1393 : : {
1394 : 0 : CHECK_NONFATAL(!bilingual_strings.empty());
1395 : 0 : UniValue result{UniValue::VARR};
1396 [ # # ]: 0 : for (const auto& s : bilingual_strings) {
1397 [ # # # # ]: 0 : result.push_back(s.original);
1398 : : }
1399 : 0 : return result;
1400 : 0 : }
1401 : :
1402 : 0 : void PushWarnings(const UniValue& warnings, UniValue& obj)
1403 : : {
1404 [ # # # # ]: 0 : if (warnings.empty()) return;
1405 [ # # # # ]: 0 : obj.pushKV("warnings", warnings);
1406 : : }
1407 : :
1408 : 0 : void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1409 : : {
1410 [ # # ]: 0 : if (warnings.empty()) return;
1411 [ # # # # ]: 0 : obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1412 : : }
1413 : :
1414 : 1008 : std::vector<RPCResult> ScriptPubKeyDoc() {
1415 : 1008 : return
1416 : : {
1417 [ + - + - ]: 2016 : {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
1418 [ + - + - ]: 2016 : {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
1419 [ + - + - ]: 2016 : {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
1420 [ + - + - ]: 2016 : {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
1421 [ + - + - : 2016 : {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
+ - ]
1422 [ + - + + : 13104 : };
- - ]
1423 [ + - + - : 10080 : }
+ - + - +
- - - ]
1424 : :
1425 : 0 : uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit)
1426 : : {
1427 : 0 : arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))};
1428 : 0 : return ArithToUint256(target);
1429 : : }
1430 : :
1431 : 766 : std::vector<RPCResult> ElideGroup(std::vector<RPCResult> fields, std::string summary)
1432 : : {
1433 [ - + ]: 766 : if (fields.empty()) return fields;
1434 : 766 : std::vector<RPCResult> result;
1435 [ - + + - ]: 766 : result.reserve(fields.size());
1436 [ - + + + ]: 5684 : for (size_t i = 0; i < fields.size(); ++i) {
1437 [ + - ]: 4918 : RPCResultOptions opts = fields[i].m_opts;
1438 [ + + ]: 4918 : if (i == 0) {
1439 [ + - ]: 766 : opts.print_elision = summary;
1440 : : } else {
1441 : 4152 : opts.print_elision = HelpElisionSkip{};
1442 : : }
1443 [ + - ]: 4918 : result.emplace_back(fields[i], std::move(opts));
1444 : 4918 : }
1445 : 766 : return result;
1446 : 766 : }
|