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