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