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 : 23967 : std::string GetAllOutputTypes()
50 : : {
51 : 23967 : std::vector<std::string> ret;
52 : 23967 : using U = std::underlying_type<TxoutType>::type;
53 [ + + ]: 287604 : for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
54 [ + - + - ]: 527274 : ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
55 : : }
56 [ + - ]: 47934 : return Join(ret, ", ");
57 : 23967 : }
58 : :
59 : 1192 : void RPCTypeCheckObj(const UniValue& o,
60 : : const std::map<std::string, UniValueType>& typesExpected,
61 : : bool fAllowNull,
62 : : bool fStrict)
63 : : {
64 [ + + ]: 17153 : for (const auto& t : typesExpected) {
65 : 15997 : const UniValue& v = o.find_value(t.first);
66 [ + + + + ]: 15997 : if (!fAllowNull && v.isNull())
67 [ + - + - ]: 22 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
68 : :
69 [ + + + + : 15986 : 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 [ + + ]: 1156 : if (fStrict)
74 : : {
75 [ + + ]: 2507 : for (const std::string& k : o.getKeys())
76 : : {
77 [ + + ]: 1776 : 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 : 1152 : }
85 : :
86 : 10987 : int ParseVerbosity(const UniValue& arg, int default_verbosity, bool allow_bool)
87 : : {
88 [ + + ]: 10987 : if (!arg.isNull()) {
89 [ + + ]: 9379 : if (arg.isBool()) {
90 [ + + ]: 3038 : if (!allow_bool) {
91 [ + - + - ]: 4 : throw JSONRPCError(RPC_TYPE_ERROR, "Verbosity was boolean but only integer allowed");
92 : : }
93 : 3036 : return arg.get_bool(); // true = 1
94 : : } else {
95 : 6341 : return arg.getInt<int>();
96 : : }
97 : : }
98 : : return default_verbosity;
99 : : }
100 : :
101 : 37783 : CAmount AmountFromValue(const UniValue& value, int decimals)
102 : : {
103 [ + + + + ]: 37783 : if (!value.isNum() && !value.isStr())
104 [ + - + - ]: 24 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
105 : 37771 : CAmount amount;
106 [ + + ]: 37771 : if (!ParseFixedPoint(value.getValStr(), decimals, &amount))
107 [ + - + - ]: 166 : throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
108 [ + + ]: 37688 : if (!MoneyRange(amount))
109 [ + - + - ]: 24 : throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
110 : 37676 : return amount;
111 : : }
112 : :
113 : 22581 : CFeeRate ParseFeeRate(const UniValue& json)
114 : : {
115 : 22581 : CAmount val{AmountFromValue(json)};
116 [ + + + - : 22581 : if (val >= COIN) throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee rates larger than or equal to 1BTC/kvB are not accepted");
+ - ]
117 : 22579 : return CFeeRate{val};
118 : : }
119 : :
120 : 22646 : uint256 ParseHashV(const UniValue& v, std::string_view name)
121 : : {
122 : 22646 : const std::string& strHex(v.get_str());
123 [ + + ]: 22645 : 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 : 5973 : uint256 ParseHashO(const UniValue& o, std::string_view strKey)
130 : : {
131 : 5973 : 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 : 815 : std::string ShellQuote(const std::string& s)
155 : : {
156 [ + - ]: 815 : std::string result;
157 [ + - ]: 815 : result.reserve(s.size() * 2);
158 [ + + ]: 24361 : for (const char ch: s) {
159 [ + + ]: 23546 : if (ch == '\'') {
160 [ + - ]: 1 : result += "'\''";
161 : : } else {
162 [ + - ]: 47091 : result += ch;
163 : : }
164 : : }
165 [ + - ]: 1630 : return "'" + result + "'";
166 : 815 : }
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 : 9234 : std::string ShellQuoteIfNeeded(const std::string& s)
174 : : {
175 [ + + ]: 79474 : for (const char ch: s) {
176 [ + + ]: 71055 : if (ch == ' ' || ch == '\'' || ch == '"') {
177 : 815 : return ShellQuote(s);
178 : : }
179 : : }
180 : :
181 : 8419 : return s;
182 : : }
183 : :
184 : : }
185 : :
186 : 659836 : std::string HelpExampleCli(const std::string& methodname, const std::string& args)
187 : : {
188 [ + - + - ]: 1979508 : return "> bitcoin-cli " + methodname + " " + args + "\n";
189 : : }
190 : :
191 : 2926 : std::string HelpExampleCliNamed(const std::string& methodname, const RPCArgList& args)
192 : : {
193 : 2926 : std::string result = "> bitcoin-cli -named " + methodname;
194 [ + + ]: 12160 : for (const auto& argpair: args) {
195 [ + + ]: 9234 : const auto& value = argpair.second.isStr()
196 [ + + + - ]: 9234 : ? argpair.second.get_str()
197 [ + - + - ]: 9234 : : argpair.second.write();
198 [ + - + - : 27702 : result += " " + argpair.first + "=" + ShellQuoteIfNeeded(value);
+ - ]
199 : 9234 : }
200 [ + - ]: 2926 : result += "\n";
201 : 2926 : return result;
202 : 0 : }
203 : :
204 : 446086 : std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
205 : : {
206 : 446086 : return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
207 [ + - + - ]: 1338258 : "\"method\": \"" + methodname + "\", \"params\": [" + args + "]}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
208 : : }
209 : :
210 : 2923 : std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList& args)
211 : : {
212 : 2923 : UniValue params(UniValue::VOBJ);
213 [ + + ]: 12154 : for (const auto& param: args) {
214 [ + - + - : 18462 : params.pushKV(param.first, param.second);
+ - ]
215 : : }
216 : :
217 : 2923 : return "> curl --user myusername --data-binary '{\"jsonrpc\": \"2.0\", \"id\": \"curltest\", "
218 [ + - + - : 11692 : "\"method\": \"" + methodname + "\", \"params\": " + params.write() + "}' -H 'content-type: application/json' http://127.0.0.1:8332/\n";
+ - ]
219 : 2923 : }
220 : :
221 : : // Converts a hex string to a public key if possible
222 : 758 : CPubKey HexToPubKey(const std::string& hex_in)
223 : : {
224 [ + + ]: 758 : if (!IsHex(hex_in)) {
225 [ + - + - ]: 3 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be a hex string");
226 : : }
227 [ + + + + ]: 757 : 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 : 756 : CPubKey vchPubKey(ParseHex(hex_in));
231 [ - + ]: 756 : if (!vchPubKey.IsFullyValid()) {
232 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + hex_in + "\" must be cryptographically valid.");
233 : : }
234 : 756 : return vchPubKey;
235 : : }
236 : :
237 : : // Retrieves a public key for an address from the given FillableSigningProvider
238 : 0 : CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in)
239 : : {
240 : 0 : CTxDestination dest = DecodeDestination(addr_in);
241 [ # # # # ]: 0 : if (!IsValidDestination(dest)) {
242 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr_in);
243 : : }
244 [ # # ]: 0 : CKeyID key = GetKeyForDestination(keystore, dest);
245 [ # # ]: 0 : if (key.IsNull()) {
246 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' does not refer to a key", addr_in));
247 : : }
248 [ # # ]: 0 : CPubKey vchPubKey;
249 [ # # # # ]: 0 : 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 [ # # # # ]: 0 : if (!vchPubKey.IsFullyValid()) {
253 [ # # # # ]: 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet contains an invalid public key");
254 : : }
255 : 0 : return vchPubKey;
256 : 0 : }
257 : :
258 : : // Creates a multisig address from a given list of public keys, number of signatures required, and the address type
259 : 119 : CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out)
260 : : {
261 : : // Gather public keys
262 [ - + ]: 119 : if (required < 1) {
263 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "a multisignature address must require at least one key to redeem");
264 : : }
265 [ - + ]: 119 : if ((int)pubkeys.size() < required) {
266 [ # # # # ]: 0 : 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 [ + + ]: 119 : if (pubkeys.size() > MAX_PUBKEYS_PER_MULTISIG) {
269 [ + - + - ]: 4 : 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 : 117 : script_out = GetScriptForMultisig(required, pubkeys);
273 : :
274 : : // Check if any keys are uncompressed. If so, the type is legacy
275 [ + + ]: 733 : for (const CPubKey& pk : pubkeys) {
276 [ + + ]: 652 : if (!pk.IsCompressed()) {
277 : : type = OutputType::LEGACY;
278 : : break;
279 : : }
280 : : }
281 : :
282 [ + + + - : 117 : if (type == OutputType::LEGACY && script_out.size() > MAX_SCRIPT_ELEMENT_SIZE) {
+ + ]
283 [ + - + - : 3 : 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 : 116 : CTxDestination dest = AddAndGetDestinationForScript(keystore, script_out, type);
288 : :
289 : 116 : return dest;
290 : : }
291 : :
292 : : class DescribeAddressVisitor
293 : : {
294 : : public:
295 : : explicit DescribeAddressVisitor() = default;
296 : :
297 : 0 : UniValue operator()(const CNoDestination& dest) const
298 : : {
299 : 0 : return UniValue(UniValue::VOBJ);
300 : : }
301 : :
302 : 0 : UniValue operator()(const PubKeyDestination& dest) const
303 : : {
304 : 0 : return UniValue(UniValue::VOBJ);
305 : : }
306 : :
307 : 116 : UniValue operator()(const PKHash& keyID) const
308 : : {
309 : 116 : UniValue obj(UniValue::VOBJ);
310 [ + - + - : 232 : obj.pushKV("isscript", false);
+ - ]
311 [ + - + - : 232 : obj.pushKV("iswitness", false);
+ - ]
312 : 116 : return obj;
313 : 0 : }
314 : :
315 : 156 : UniValue operator()(const ScriptHash& scriptID) const
316 : : {
317 : 156 : UniValue obj(UniValue::VOBJ);
318 [ + - + - : 312 : obj.pushKV("isscript", true);
+ - ]
319 [ + - + - : 312 : obj.pushKV("iswitness", false);
+ - ]
320 : 156 : return obj;
321 : 0 : }
322 : :
323 : 524 : UniValue operator()(const WitnessV0KeyHash& id) const
324 : : {
325 : 524 : UniValue obj(UniValue::VOBJ);
326 [ + - + - : 1048 : obj.pushKV("isscript", false);
+ - ]
327 [ + - + - : 1048 : obj.pushKV("iswitness", true);
+ - ]
328 [ + - + - : 1048 : obj.pushKV("witness_version", 0);
+ - ]
329 [ + - + - : 1048 : obj.pushKV("witness_program", HexStr(id));
+ - + - ]
330 : 524 : return obj;
331 : 0 : }
332 : :
333 : 42 : UniValue operator()(const WitnessV0ScriptHash& id) const
334 : : {
335 : 42 : UniValue obj(UniValue::VOBJ);
336 [ + - + - : 84 : obj.pushKV("isscript", true);
+ - ]
337 [ + - + - : 84 : obj.pushKV("iswitness", true);
+ - ]
338 [ + - + - : 84 : obj.pushKV("witness_version", 0);
+ - ]
339 [ + - + - : 84 : obj.pushKV("witness_program", HexStr(id));
+ - + - ]
340 : 42 : return obj;
341 : 0 : }
342 : :
343 : 118 : UniValue operator()(const WitnessV1Taproot& tap) const
344 : : {
345 : 118 : UniValue obj(UniValue::VOBJ);
346 [ + - + - : 236 : obj.pushKV("isscript", true);
+ - ]
347 [ + - + - : 236 : obj.pushKV("iswitness", true);
+ - ]
348 [ + - + - : 236 : obj.pushKV("witness_version", 1);
+ - ]
349 [ + - + - : 236 : obj.pushKV("witness_program", HexStr(tap));
+ - + - ]
350 : 118 : return obj;
351 : 0 : }
352 : :
353 : 1 : UniValue operator()(const PayToAnchor& anchor) const
354 : : {
355 : 1 : UniValue obj(UniValue::VOBJ);
356 [ + - + - : 2 : obj.pushKV("isscript", true);
+ - ]
357 [ + - + - : 2 : obj.pushKV("iswitness", true);
+ - ]
358 : 1 : return obj;
359 : 0 : }
360 : :
361 : 5 : UniValue operator()(const WitnessUnknown& id) const
362 : : {
363 : 5 : UniValue obj(UniValue::VOBJ);
364 [ + - + - : 10 : obj.pushKV("iswitness", true);
+ - ]
365 [ + - + - : 10 : obj.pushKV("witness_version", id.GetWitnessVersion());
+ - ]
366 [ + - + - : 10 : obj.pushKV("witness_program", HexStr(id.GetWitnessProgram()));
+ - + - ]
367 : 5 : return obj;
368 : 0 : }
369 : : };
370 : :
371 : 962 : UniValue DescribeAddress(const CTxDestination& dest)
372 : : {
373 : 962 : 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 : 730 : int ParseSighashString(const UniValue& sighash)
382 : : {
383 [ + + ]: 730 : if (sighash.isNull()) {
384 : : return SIGHASH_DEFAULT;
385 : : }
386 : 56 : const auto result{SighashFromStr(sighash.get_str())};
387 [ + + ]: 56 : if (!result) {
388 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, util::ErrorString(result).original);
389 : : }
390 : 52 : return result.value();
391 : 52 : }
392 : :
393 : 356 : unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
394 : : {
395 : 356 : const int target{value.getInt<int>()};
396 : 356 : const unsigned int unsigned_target{static_cast<unsigned int>(target)};
397 [ + + + + ]: 356 : if (target < 1 || unsigned_target > max_target) {
398 [ + - + - ]: 62 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
399 : : }
400 : 325 : 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 : 4241 : RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
416 : : {
417 [ + + + ]: 4241 : switch (terr) {
418 : : case TransactionError::MEMPOOL_REJECTED:
419 : : return RPC_TRANSACTION_REJECTED;
420 : 3 : case TransactionError::ALREADY_IN_UTXO_SET:
421 : 3 : return RPC_VERIFY_ALREADY_IN_UTXO_SET;
422 : 9 : default: break;
423 : : }
424 : 9 : 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 : 4241 : UniValue JSONRPCTransactionError(TransactionError terr, const std::string& err_string)
433 : : {
434 [ + + ]: 4241 : if (err_string.length() > 0) {
435 : 4231 : return JSONRPCError(RPCErrorFromTransactionError(terr), err_string);
436 : : } else {
437 [ + - + - ]: 20 : 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 : 57388 : struct Section {
446 : 18432 : Section(const std::string& left, const std::string& right)
447 [ + - ]: 18432 : : 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 : 16599 : void PushSection(const Section& s)
461 : : {
462 [ + + ]: 16599 : m_max_pad = std::max(m_max_pad, s.m_left.size());
463 : 16599 : m_sections.push_back(s);
464 : 16599 : }
465 : :
466 : : /**
467 : : * Recursive helper to translate an RPCArg into sections
468 : : */
469 : : // NOLINTNEXTLINE(misc-no-recursion)
470 : 3105 : void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NONE)
471 : : {
472 [ + - ]: 3105 : const auto indent = std::string(current_indent, ' ');
473 [ + - + + : 3105 : const auto indent_next = std::string(current_indent + 2, ' ');
+ - ]
474 : 3105 : const bool push_name{outer_type == OuterType::OBJ}; // Dictionary keys must have a name
475 : 3105 : const bool is_top_level_arg{outer_type == OuterType::NONE}; // True on the first recursion
476 : :
477 [ + + + - ]: 3105 : switch (arg.m_type) {
478 : 2560 : case RPCArg::Type::STR_HEX:
479 : 2560 : case RPCArg::Type::STR:
480 : 2560 : case RPCArg::Type::NUM:
481 : 2560 : case RPCArg::Type::AMOUNT:
482 : 2560 : case RPCArg::Type::RANGE:
483 : 2560 : case RPCArg::Type::BOOL:
484 : 2560 : case RPCArg::Type::OBJ_NAMED_PARAMS: {
485 [ + + ]: 2560 : if (is_top_level_arg) return; // Nothing more to do for non-recursive types on first recursion
486 [ + - ]: 710 : auto left = indent;
487 [ + + + - ]: 710 : if (arg.m_opts.type_str.size() != 0 && push_name) {
488 [ + - + - : 27 : left += "\"" + arg.GetName() + "\": " + arg.m_opts.type_str.at(0);
+ - + - ]
489 : : } else {
490 [ + + + - : 1402 : left += push_name ? arg.ToStringObj(/*oneline=*/false) : arg.ToString(/*oneline=*/false);
+ - ]
491 : : }
492 [ + - ]: 710 : left += ",";
493 [ + - + - : 1420 : PushSection({left, arg.ToDescriptionString(/*is_named_arg=*/push_name)});
+ - ]
494 : 710 : break;
495 : 710 : }
496 : 205 : case RPCArg::Type::OBJ:
497 : 205 : case RPCArg::Type::OBJ_USER_KEYS: {
498 [ + + + - : 205 : const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
+ - ]
499 [ - + - - : 615 : PushSection({indent + (push_name ? "\"" + arg.GetName() + "\": " : "") + "{", right});
- - - - +
- + - + -
+ - - + -
+ - - -
- ]
500 [ + + ]: 713 : for (const auto& arg_inner : arg.m_inner) {
501 [ + - ]: 508 : Push(arg_inner, current_indent + 2, OuterType::OBJ);
502 : : }
503 [ + + ]: 205 : if (arg.m_type != RPCArg::Type::OBJ) {
504 [ + - + - : 80 : PushSection({indent_next + "...", ""});
+ - + - ]
505 : : }
506 [ + + + - : 796 : PushSection({indent + "}" + (is_top_level_arg ? "" : ","), ""});
+ - + - +
- ]
507 : 205 : break;
508 : 205 : }
509 : 340 : case RPCArg::Type::ARR: {
510 [ + - ]: 340 : auto left = indent;
511 [ + + + - : 800 : left += push_name ? "\"" + arg.GetName() + "\": " : "";
+ - + - +
- + + + +
- - - - ]
512 [ + - ]: 340 : left += "[";
513 [ + + + - : 340 : const auto right = is_top_level_arg ? "" : arg.ToDescriptionString(/*is_named_arg=*/push_name);
+ - ]
514 [ + - + - ]: 340 : PushSection({left, right});
515 [ + + ]: 783 : for (const auto& arg_inner : arg.m_inner) {
516 [ + - ]: 443 : Push(arg_inner, current_indent + 2, OuterType::ARR);
517 : : }
518 [ + - + - : 680 : PushSection({indent_next + "...", ""});
+ - + - ]
519 [ + + + - : 1080 : PushSection({indent + "]" + (is_top_level_arg ? "" : ","), ""});
+ - + - +
- ]
520 : 340 : break;
521 : 340 : }
522 : : } // no default case, so the compiler can warn about missing cases
523 : 3105 : }
524 : :
525 : : /**
526 : : * Concatenate all sections with proper padding
527 : : */
528 : 3407 : std::string ToString() const
529 : : {
530 : 3407 : std::string ret;
531 : 3407 : const size_t pad = m_max_pad + 4;
532 [ + + ]: 21839 : 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 [ + - ]: 18432 : CHECK_NONFATAL(s.m_left.find('\n') == std::string::npos);
536 [ + + ]: 18432 : if (s.m_right.empty()) {
537 [ + - ]: 4912 : ret += s.m_left;
538 [ + - ]: 4912 : ret += "\n";
539 : 4912 : continue;
540 : : }
541 : :
542 [ + - ]: 13520 : std::string left = s.m_left;
543 [ + - ]: 13520 : left.resize(pad, ' ');
544 [ + - ]: 13520 : ret += left;
545 : :
546 : : // Properly pad after newlines
547 : 13520 : std::string right;
548 : 13520 : size_t begin = 0;
549 : 13520 : size_t new_line_pos = s.m_right.find_first_of('\n');
550 : 17358 : while (true) {
551 [ + - ]: 30878 : right += s.m_right.substr(begin, new_line_pos - begin);
552 [ + + ]: 15439 : if (new_line_pos == std::string::npos) {
553 : : break; //No new line
554 : : }
555 [ + - + - ]: 4222 : right += "\n" + std::string(pad, ' ');
556 : 2111 : begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);
557 [ + + ]: 2111 : if (begin == std::string::npos) {
558 : : break; // Empty line
559 : : }
560 : 1919 : new_line_pos = s.m_right.find_first_of('\n', begin + 1);
561 : : }
562 [ + - ]: 13520 : ret += right;
563 [ + - ]: 13520 : ret += "\n";
564 : 13520 : }
565 : 3407 : return ret;
566 : 0 : }
567 : : };
568 : :
569 : 19 : RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples)
570 [ + - + - : 62 : : RPCHelpMan{std::move(name), std::move(description), std::move(args), std::move(results), std::move(examples), nullptr} {}
+ + ]
571 : :
572 : 490780 : RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun)
573 : 490788 : : m_name{std::move(name)},
574 : 490788 : m_fun{std::move(fun)},
575 : 490788 : m_description{std::move(description)},
576 [ + - ]: 490780 : m_args{std::move(args)},
577 [ + - ]: 490788 : m_results{std::move(results)},
578 [ + - ]: 490788 : 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 : 490780 : enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
584 : 490780 : std::map<std::string, int> param_names;
585 : :
586 [ + + ]: 1386356 : for (const auto& arg : m_args) {
587 [ + - ]: 895584 : std::vector<std::string> names = SplitString(arg.m_names, '|');
588 : : // Should have unique named arguments
589 [ + + ]: 1806321 : for (const std::string& name : names) {
590 [ + - ]: 910739 : auto& param_type = param_names[name];
591 [ + + ]: 910739 : CHECK_NONFATAL(!(param_type & POSITIONAL));
592 [ + + ]: 910738 : CHECK_NONFATAL(!(param_type & NAMED_ONLY));
593 : 910737 : param_type |= POSITIONAL;
594 : : }
595 [ + + ]: 895582 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
596 [ + + ]: 114820 : for (const auto& inner : arg.m_inner) {
597 [ + - ]: 98350 : std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
598 [ + + ]: 196695 : for (const std::string& inner_name : inner_names) {
599 [ + - ]: 98351 : auto& param_type = param_names[inner_name];
600 [ + + + + : 98353 : CHECK_NONFATAL(!(param_type & POSITIONAL) || inner.m_opts.also_positional);
+ + ]
601 [ + + ]: 98349 : CHECK_NONFATAL(!(param_type & NAMED));
602 [ + + ]: 98347 : CHECK_NONFATAL(!(param_type & NAMED_ONLY));
603 [ + + ]: 187131 : param_type |= inner.m_opts.also_positional ? NAMED : NAMED_ONLY;
604 : : }
605 : 98350 : }
606 : : }
607 : : // Default value type should match argument type only when defined
608 [ + + ]: 895576 : if (arg.m_fallback.index() == 2) {
609 : 279939 : const RPCArg::Type type = arg.m_type;
610 [ - + + + : 279939 : 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 : 1971 : case UniValue::VARR:
615 [ + - ]: 1971 : CHECK_NONFATAL(type == RPCArg::Type::ARR);
616 : : break;
617 : 97120 : case UniValue::VSTR:
618 [ + + - + : 194240 : CHECK_NONFATAL(type == RPCArg::Type::STR || type == RPCArg::Type::STR_HEX || type == RPCArg::Type::AMOUNT);
- ]
619 : : break;
620 : 60932 : case UniValue::VNUM:
621 [ + - - + : 121864 : CHECK_NONFATAL(type == RPCArg::Type::NUM || type == RPCArg::Type::AMOUNT || type == RPCArg::Type::RANGE);
- ]
622 : : break;
623 : 119916 : case UniValue::VBOOL:
624 [ + - ]: 119916 : 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 : 895584 : }
635 : 490812 : }
636 : :
637 : 1066 : std::string RPCResults::ToDescriptionString() const
638 : : {
639 : 1066 : std::string result;
640 [ + + ]: 2351 : for (const auto& r : m_results) {
641 [ + + ]: 1285 : if (r.m_type == RPCResult::Type::ANY) continue; // for testing only
642 [ + + ]: 1275 : if (r.m_cond.empty()) {
643 [ + - ]: 938 : result += "\nResult:\n";
644 : : } else {
645 [ + - + - ]: 1011 : result += "\nResult (" + r.m_cond + "):\n";
646 : : }
647 : 1275 : Sections sections;
648 [ + - ]: 1275 : r.ToSections(sections);
649 [ + - ]: 2550 : result += sections.ToString();
650 : 1275 : }
651 : 1066 : return result;
652 : 0 : }
653 : :
654 : 1066 : std::string RPCExamples::ToDescriptionString() const
655 : : {
656 [ + + ]: 1066 : return m_examples.empty() ? m_examples : "\nExamples:\n" + m_examples;
657 : : }
658 : :
659 : 198533 : UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
660 : : {
661 [ + + ]: 198533 : if (request.mode == JSONRPCRequest::GET_ARGS) {
662 : 179 : 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 [ + + + + ]: 198354 : if (request.mode == JSONRPCRequest::GET_HELP || !IsValidNumArgs(request.params.size())) {
669 [ + - + - ]: 2126 : throw std::runtime_error(ToString());
670 : : }
671 : 197291 : UniValue arg_mismatch{UniValue::VOBJ};
672 [ + + ]: 557213 : for (size_t i{0}; i < m_args.size(); ++i) {
673 [ + - ]: 359922 : const auto& arg{m_args.at(i)};
674 [ + - + - ]: 359922 : UniValue match{arg.MatchesType(request.params[i])};
675 [ + + ]: 359922 : if (!match.isTrue()) {
676 [ + - + - ]: 60 : arg_mismatch.pushKV(strprintf("Position %s (%s)", i + 1, arg.m_names), std::move(match));
677 : : }
678 : 359922 : }
679 [ + + ]: 197291 : if (!arg_mismatch.empty()) {
680 [ + - + - : 56 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
+ - ]
681 : : }
682 [ + - ]: 197263 : CHECK_NONFATAL(m_req == nullptr);
683 : 197263 : m_req = &request;
684 [ + + ]: 197263 : UniValue ret = m_fun(*this, request);
685 : 191692 : m_req = nullptr;
686 [ + - + - : 191692 : if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
+ + ]
687 : 191651 : UniValue mismatch{UniValue::VARR};
688 [ + - ]: 209362 : for (const auto& res : m_results.m_results) {
689 [ + - ]: 209362 : UniValue match{res.MatchesType(ret)};
690 [ + + ]: 209362 : if (match.isTrue()) {
691 [ + - ]: 191651 : mismatch.setNull();
692 : 191651 : break;
693 : : }
694 [ + - ]: 17711 : mismatch.push_back(std::move(match));
695 : 209362 : }
696 [ - + ]: 191651 : 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 : 191651 : }
708 : 191692 : return ret;
709 : 197291 : }
710 : :
711 : : using CheckFn = void(const RPCArg&);
712 : 30101 : static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
713 : : {
714 : 30101 : CHECK_NONFATAL(i < params.size());
715 : 30101 : const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
716 : 30101 : const RPCArg& param{params.at(i)};
717 [ + + ]: 30101 : if (check) check(param);
718 : :
719 [ + + ]: 30101 : if (!arg.isNull()) return &arg;
720 [ + + ]: 7216 : if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
721 : 5315 : return &std::get<RPCArg::Default>(param.m_fallback);
722 : : }
723 : :
724 : 28149 : static void CheckRequiredOrDefault(const RPCArg& param)
725 : : {
726 : : // Must use `Arg<Type>(key)` to get the argument or its default value.
727 : 28149 : const bool required{
728 [ + + - + ]: 28149 : std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
729 : 52580 : };
730 [ + - ]: 52580 : CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
731 : 28149 : }
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 [ + + ]: 719 : TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
747 [ + + ]: 733 : TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
748 [ + + ]: 500 : TMPL_INST(nullptr, const std::string*, maybe_arg ? &maybe_arg->get_str() : nullptr;);
749 : :
750 : : // Required arg or optional arg with default value.
751 : 22581 : TMPL_INST(CheckRequiredOrDefault, const UniValue&, *CHECK_NONFATAL(maybe_arg););
752 : 649 : TMPL_INST(CheckRequiredOrDefault, bool, CHECK_NONFATAL(maybe_arg)->get_bool(););
753 : 1330 : TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
754 : 778 : TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
755 : 2811 : TMPL_INST(CheckRequiredOrDefault, const std::string&, CHECK_NONFATAL(maybe_arg)->get_str(););
756 : :
757 : 197332 : bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
758 : : {
759 : 197332 : size_t num_required_args = 0;
760 [ + + ]: 389196 : for (size_t n = m_args.size(); n > 0; --n) {
761 [ + + ]: 320123 : if (!m_args.at(n - 1).IsOptional()) {
762 : : num_required_args = n;
763 : : break;
764 : : }
765 : : }
766 [ + + + + ]: 197332 : return num_required_args <= num_args && num_args <= m_args.size();
767 : : }
768 : :
769 : 146114 : std::vector<std::pair<std::string, bool>> RPCHelpMan::GetArgNames() const
770 : : {
771 : 146114 : std::vector<std::pair<std::string, bool>> ret;
772 [ + - ]: 146114 : ret.reserve(m_args.size());
773 [ + + ]: 412836 : for (const auto& arg : m_args) {
774 [ + + ]: 266722 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
775 [ + + ]: 48881 : for (const auto& inner : arg.m_inner) {
776 [ + - ]: 41352 : ret.emplace_back(inner.m_names, /*named_only=*/true);
777 : : }
778 : : }
779 [ + - ]: 266722 : ret.emplace_back(arg.m_names, /*named_only=*/false);
780 : : }
781 : 146114 : return ret;
782 : 0 : }
783 : :
784 : 30101 : size_t RPCHelpMan::GetParamIndex(std::string_view key) const
785 : : {
786 : 30101 : auto it{std::find_if(
787 : 60809 : m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;}
788 : : )};
789 : :
790 : 30101 : CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time
791 : 30101 : return std::distance(m_args.begin(), it);
792 : : }
793 : :
794 : 1066 : std::string RPCHelpMan::ToString() const
795 : : {
796 [ + - ]: 1066 : std::string ret;
797 : :
798 : : // Oneline summary
799 [ + - ]: 1066 : ret += m_name;
800 : 1066 : bool was_optional{false};
801 [ + + ]: 2899 : for (const auto& arg : m_args) {
802 [ + + ]: 1842 : if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
803 [ + - ]: 1833 : const bool optional = arg.IsOptional();
804 [ + - ]: 1833 : ret += " ";
805 [ + + ]: 1833 : if (optional) {
806 [ + + + - ]: 1027 : if (!was_optional) ret += "( ";
807 : : was_optional = true;
808 : : } else {
809 [ + + + - ]: 806 : if (was_optional) ret += ") ";
810 : : was_optional = false;
811 : : }
812 [ + - ]: 3666 : ret += arg.ToString(/*oneline=*/true);
813 : : }
814 [ + + + - ]: 1066 : if (was_optional) ret += " )";
815 : :
816 : : // Description
817 [ + - + - : 3198 : ret += "\n\n" + TrimString(m_description) + "\n";
+ - ]
818 : :
819 : : // Arguments
820 : 1066 : Sections sections;
821 : 1066 : Sections named_only_sections;
822 [ + + ]: 2899 : for (size_t i{0}; i < m_args.size(); ++i) {
823 [ + - ]: 1842 : const auto& arg = m_args.at(i);
824 [ + + ]: 1842 : if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
825 : :
826 : : // Push named argument name and description
827 [ + - + - : 5499 : sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
+ - + - +
- ]
828 [ + + ]: 1833 : sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
829 : :
830 : : // Recursively push nested args
831 [ + - ]: 1833 : sections.Push(arg);
832 : :
833 : : // Push named-only argument sections
834 [ + + ]: 1833 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
835 [ + + ]: 381 : for (const auto& arg_inner : arg.m_inner) {
836 [ + - + - : 642 : named_only_sections.PushSection({arg_inner.GetFirstName(), arg_inner.ToDescriptionString(/*is_named_arg=*/true)});
+ - + - ]
837 [ + - ]: 321 : named_only_sections.Push(arg_inner);
838 : : }
839 : : }
840 : : }
841 : :
842 [ + + + - ]: 1066 : if (!sections.m_sections.empty()) ret += "\nArguments:\n";
843 [ + - ]: 2132 : ret += sections.ToString();
844 [ + + + - ]: 1066 : if (!named_only_sections.m_sections.empty()) ret += "\nNamed Arguments:\n";
845 [ + - ]: 2132 : ret += named_only_sections.ToString();
846 : :
847 : : // Result
848 [ + - ]: 2132 : ret += m_results.ToDescriptionString();
849 : :
850 : : // Examples
851 [ + - ]: 2132 : ret += m_examples.ToDescriptionString();
852 : :
853 : 1066 : return ret;
854 : 1066 : }
855 : :
856 : 179 : UniValue RPCHelpMan::GetArgMap() const
857 : : {
858 : 179 : UniValue arr{UniValue::VARR};
859 : :
860 : 630 : auto push_back_arg_info = [&arr](const std::string& rpc_name, int pos, const std::string& arg_name, const RPCArg::Type& type) {
861 : 451 : UniValue map{UniValue::VARR};
862 [ + - + - ]: 451 : map.push_back(rpc_name);
863 [ + - + - ]: 451 : map.push_back(pos);
864 [ + - + - ]: 451 : map.push_back(arg_name);
865 [ + - + - ]: 451 : map.push_back(type == RPCArg::Type::STR ||
866 : : type == RPCArg::Type::STR_HEX);
867 [ + - ]: 451 : arr.push_back(std::move(map));
868 : 451 : };
869 : :
870 [ + + ]: 531 : for (int i{0}; i < int(m_args.size()); ++i) {
871 [ + - ]: 352 : const auto& arg = m_args.at(i);
872 [ + - ]: 352 : std::vector<std::string> arg_names = SplitString(arg.m_names, '|');
873 [ + + ]: 706 : for (const auto& arg_name : arg_names) {
874 [ + - ]: 354 : push_back_arg_info(m_name, i, arg_name, arg.m_type);
875 [ + + ]: 354 : if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
876 [ + + ]: 111 : for (const auto& inner : arg.m_inner) {
877 [ + - ]: 97 : std::vector<std::string> inner_names = SplitString(inner.m_names, '|');
878 [ + + ]: 194 : for (const std::string& inner_name : inner_names) {
879 [ + - ]: 97 : push_back_arg_info(m_name, i, inner_name, inner.m_type);
880 : : }
881 : 97 : }
882 : : }
883 : : }
884 : 352 : }
885 : 179 : return arr;
886 : 0 : }
887 : :
888 : 200517 : static std::optional<UniValue::VType> ExpectedType(RPCArg::Type type)
889 : : {
890 : 200517 : using Type = RPCArg::Type;
891 [ + + + + : 200517 : switch (type) {
+ + + - ]
892 : 118847 : case Type::STR_HEX:
893 : 118847 : case Type::STR: {
894 : 118847 : return UniValue::VSTR;
895 : : }
896 : 50097 : case Type::NUM: {
897 : 50097 : return UniValue::VNUM;
898 : : }
899 : 19964 : case Type::AMOUNT: {
900 : : // VNUM or VSTR, checked inside AmountFromValue()
901 : 19964 : return std::nullopt;
902 : : }
903 : 86 : case Type::RANGE: {
904 : : // VNUM or VARR, checked inside ParseRange()
905 : 86 : return std::nullopt;
906 : : }
907 : 3583 : case Type::BOOL: {
908 : 3583 : return UniValue::VBOOL;
909 : : }
910 : 2754 : case Type::OBJ:
911 : 2754 : case Type::OBJ_NAMED_PARAMS:
912 : 2754 : case Type::OBJ_USER_KEYS: {
913 : 2754 : return UniValue::VOBJ;
914 : : }
915 : 5186 : case Type::ARR: {
916 : 5186 : return UniValue::VARR;
917 : : }
918 : : } // no default case, so the compiler can warn about missing cases
919 [ # # ]: 0 : NONFATAL_UNREACHABLE();
920 : : }
921 : :
922 : 359922 : UniValue RPCArg::MatchesType(const UniValue& request) const
923 : : {
924 [ + + ]: 359922 : if (m_opts.skip_type_check) return true;
925 [ + + + + ]: 347573 : if (IsOptional() && request.isNull()) return true;
926 : 200517 : const auto exp_type{ExpectedType(m_type)};
927 [ + + ]: 200517 : if (!exp_type) return true; // nothing to check
928 : :
929 [ + + ]: 180467 : if (*exp_type != request.getType()) {
930 [ + - ]: 60 : return strprintf("JSON value of type %s is not of expected type %s", uvTypeName(request.getType()), uvTypeName(*exp_type));
931 : : }
932 : 180437 : return true;
933 : : }
934 : :
935 : 4859 : std::string RPCArg::GetFirstName() const
936 : : {
937 : 4859 : return m_names.substr(0, m_names.find('|'));
938 : : }
939 : :
940 : 60878 : std::string RPCArg::GetName() const
941 : : {
942 : 60878 : CHECK_NONFATAL(std::string::npos == m_names.find('|'));
943 : 60878 : return m_names;
944 : : }
945 : :
946 : 669529 : bool RPCArg::IsOptional() const
947 : : {
948 [ + + ]: 669529 : if (m_fallback.index() != 0) {
949 : : return true;
950 : : } else {
951 : 320695 : return RPCArg::Optional::NO != std::get<RPCArg::Optional>(m_fallback);
952 : : }
953 : : }
954 : :
955 : 3105 : std::string RPCArg::ToDescriptionString(bool is_named_arg) const
956 : : {
957 [ + - ]: 3105 : std::string ret;
958 [ + - ]: 3105 : ret += "(";
959 [ + + ]: 3105 : if (m_opts.type_str.size() != 0) {
960 [ + - + - ]: 38 : ret += m_opts.type_str.at(1);
961 : : } else {
962 [ + + + + : 3067 : switch (m_type) {
+ + + - ]
963 : 1313 : case Type::STR_HEX:
964 : 1313 : case Type::STR: {
965 [ + - ]: 1313 : ret += "string";
966 : : break;
967 : : }
968 : 474 : case Type::NUM: {
969 [ + - ]: 474 : ret += "numeric";
970 : : break;
971 : : }
972 : 150 : case Type::AMOUNT: {
973 [ + - ]: 150 : ret += "numeric or string";
974 : : break;
975 : : }
976 : 61 : case Type::RANGE: {
977 [ + - ]: 61 : ret += "numeric or array";
978 : : break;
979 : : }
980 : 464 : case Type::BOOL: {
981 [ + - ]: 464 : ret += "boolean";
982 : : break;
983 : : }
984 : 265 : case Type::OBJ:
985 : 265 : case Type::OBJ_NAMED_PARAMS:
986 : 265 : case Type::OBJ_USER_KEYS: {
987 [ + - ]: 265 : ret += "json object";
988 : : break;
989 : : }
990 : 340 : case Type::ARR: {
991 [ + - + + ]: 3105 : ret += "json array";
992 : : break;
993 : : }
994 : : } // no default case, so the compiler can warn about missing cases
995 : : }
996 [ + + ]: 3105 : if (m_fallback.index() == 1) {
997 [ + - ]: 796 : ret += ", optional, default=" + std::get<RPCArg::DefaultHint>(m_fallback);
998 [ + + ]: 2707 : } else if (m_fallback.index() == 2) {
999 [ + - + - ]: 1618 : ret += ", optional, default=" + std::get<RPCArg::Default>(m_fallback).write();
1000 : : } else {
1001 [ - + + + : 1898 : switch (std::get<RPCArg::Optional>(m_fallback)) {
- ]
1002 : 799 : case RPCArg::Optional::OMITTED: {
1003 [ + + + - ]: 799 : 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 : 1099 : case RPCArg::Optional::NO: {
1008 [ + - ]: 1099 : ret += ", required";
1009 : : break;
1010 : : }
1011 : : } // no default case, so the compiler can warn about missing cases
1012 : : }
1013 [ + - ]: 3105 : ret += ")";
1014 [ + + + - ]: 3105 : if (m_type == Type::OBJ_NAMED_PARAMS) ret += " Options object that can be used to pass named arguments, listed below.";
1015 [ + + + - : 6210 : ret += m_description.empty() ? "" : " " + m_description;
+ - ]
1016 : 3105 : return ret;
1017 : 0 : }
1018 : :
1019 : : // NOLINTNEXTLINE(misc-no-recursion)
1020 : 10433 : void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const int current_indent) const
1021 : : {
1022 : : // Indentation
1023 [ + - ]: 10433 : const std::string indent(current_indent, ' ');
1024 [ + - + + ]: 10433 : const std::string indent_next(current_indent + 2, ' ');
1025 : :
1026 : : // Elements in a JSON structure (dictionary or array) are separated by a comma
1027 [ + + + - ]: 11708 : const std::string maybe_separator{outer_type != OuterType::NONE ? "," : ""};
1028 : :
1029 : : // The key name if recursed into a dictionary
1030 : 10433 : const std::string maybe_key{
1031 [ + + ]: 10433 : outer_type == OuterType::OBJ ?
1032 [ + - - - ]: 16286 : "\"" + this->m_key_name + "\" : " :
1033 [ + - + - ]: 18576 : ""};
1034 : :
1035 : : // Format description with type
1036 : 20771 : const auto Description = [&](const std::string& type) {
1037 [ + + + - : 39289 : return "(" + type + (this->m_optional ? ", optional" : "") + ")" +
+ - ]
1038 [ + + + - ]: 31014 : (this->m_description.empty() ? "" : " " + this->m_description);
1039 : 10433 : };
1040 : :
1041 [ + - + + : 10433 : switch (m_type) {
+ + + + +
+ + - ]
1042 : 95 : case Type::ELISION: {
1043 : : // If the inner result is empty, use three dots for elision
1044 [ + - + - : 190 : sections.PushSection({indent + "..." + maybe_separator, m_description});
+ - + - ]
1045 : 95 : return;
1046 : : }
1047 : 0 : case Type::ANY: {
1048 [ # # ]: 0 : NONFATAL_UNREACHABLE(); // Only for testing
1049 : : }
1050 : 157 : case Type::NONE: {
1051 [ + - + - : 314 : sections.PushSection({indent + "null" + maybe_separator, Description("json null")});
+ - + - +
- + - ]
1052 : 157 : return;
1053 : : }
1054 : 1834 : case Type::STR: {
1055 [ + - + - : 5502 : sections.PushSection({indent + maybe_key + "\"str\"" + maybe_separator, Description("string")});
+ - + - +
- + - ]
1056 : 1834 : return;
1057 : : }
1058 : 513 : case Type::STR_AMOUNT: {
1059 [ + - + - : 1539 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1060 : 513 : return;
1061 : : }
1062 : 1625 : case Type::STR_HEX: {
1063 [ + - + - : 4875 : sections.PushSection({indent + maybe_key + "\"hex\"" + maybe_separator, Description("string")});
+ - + - +
- + - ]
1064 : 1625 : return;
1065 : : }
1066 : 2645 : case Type::NUM: {
1067 [ + - + - : 7935 : sections.PushSection({indent + maybe_key + "n" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1068 : 2645 : return;
1069 : : }
1070 : 324 : case Type::NUM_TIME: {
1071 [ + - + - : 972 : sections.PushSection({indent + maybe_key + "xxx" + maybe_separator, Description("numeric")});
+ - + - +
- + - ]
1072 : 324 : return;
1073 : : }
1074 : 692 : case Type::BOOL: {
1075 [ + - + - : 2076 : sections.PushSection({indent + maybe_key + "true|false" + maybe_separator, Description("boolean")});
+ - + - +
- + - ]
1076 : 692 : return;
1077 : : }
1078 : 953 : case Type::ARR_FIXED:
1079 : 953 : case Type::ARR: {
1080 [ + - + - : 2859 : sections.PushSection({indent + maybe_key + "[", Description("json array")});
+ - + - +
- ]
1081 [ + + ]: 1968 : for (const auto& i : m_inner) {
1082 [ + - ]: 1015 : i.ToSections(sections, OuterType::ARR, current_indent + 2);
1083 : : }
1084 [ + - ]: 953 : CHECK_NONFATAL(!m_inner.empty());
1085 [ + + + + ]: 953 : if (m_type == Type::ARR && m_inner.back().m_type != Type::ELISION) {
1086 [ + - + - : 1866 : sections.PushSection({indent_next + "...", ""});
+ - + - ]
1087 : : } else {
1088 : : // Remove final comma, which would be invalid JSON
1089 : 20 : sections.m_sections.back().m_left.pop_back();
1090 : : }
1091 [ + - + - : 1906 : sections.PushSection({indent + "]" + maybe_separator, ""});
+ - + - +
- ]
1092 : 953 : return;
1093 : : }
1094 : 1595 : case Type::OBJ_DYN:
1095 : 1595 : case Type::OBJ: {
1096 [ + + ]: 1595 : if (m_inner.empty()) {
1097 [ + - + - : 54 : sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
+ - + - +
- ]
1098 : 18 : return;
1099 : : }
1100 [ + - + - : 4731 : sections.PushSection({indent + maybe_key + "{", Description("json object")});
+ - + - +
- ]
1101 [ + + ]: 9720 : for (const auto& i : m_inner) {
1102 [ + - ]: 8143 : i.ToSections(sections, OuterType::OBJ, current_indent + 2);
1103 : : }
1104 [ + + - + ]: 1577 : 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 [ + - + - : 404 : sections.PushSection({indent_next + "...", ""});
+ - + - ]
1107 : : } else {
1108 : : // Remove final comma, which would be invalid JSON
1109 : 1375 : sections.m_sections.back().m_left.pop_back();
1110 : : }
1111 [ + - + - : 3154 : sections.PushSection({indent + "}" + maybe_separator, ""});
+ - + - +
- ]
1112 : 1577 : return;
1113 : : }
1114 : : } // no default case, so the compiler can warn about missing cases
1115 [ # # ]: 0 : NONFATAL_UNREACHABLE();
1116 : 10433 : }
1117 : :
1118 : 4176607 : static std::optional<UniValue::VType> ExpectedType(RPCResult::Type type)
1119 : : {
1120 : 4176607 : using Type = RPCResult::Type;
1121 [ + + + + : 4176607 : switch (type) {
+ + + - ]
1122 : 15 : case Type::ELISION:
1123 : 15 : case Type::ANY: {
1124 : 15 : return std::nullopt;
1125 : : }
1126 : 36724 : case Type::NONE: {
1127 : 36724 : return UniValue::VNULL;
1128 : : }
1129 : 1667798 : case Type::STR:
1130 : 1667798 : case Type::STR_HEX: {
1131 : 1667798 : return UniValue::VSTR;
1132 : : }
1133 : 1525590 : case Type::NUM:
1134 : 1525590 : case Type::STR_AMOUNT:
1135 : 1525590 : case Type::NUM_TIME: {
1136 : 1525590 : return UniValue::VNUM;
1137 : : }
1138 : 386096 : case Type::BOOL: {
1139 : 386096 : return UniValue::VBOOL;
1140 : : }
1141 : 174062 : case Type::ARR_FIXED:
1142 : 174062 : case Type::ARR: {
1143 : 174062 : return UniValue::VARR;
1144 : : }
1145 : 386322 : case Type::OBJ_DYN:
1146 : 386322 : case Type::OBJ: {
1147 : 386322 : 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 : 4177178 : UniValue RPCResult::MatchesType(const UniValue& result) const
1155 : : {
1156 [ + + ]: 4177178 : if (m_skip_type_check) {
1157 : 571 : return true;
1158 : : }
1159 : :
1160 : 4176607 : const auto exp_type = ExpectedType(m_type);
1161 [ + + ]: 4176607 : if (!exp_type) return true; // can be any type, so nothing to check
1162 : :
1163 [ + + ]: 4176592 : if (*exp_type != result.getType()) {
1164 [ + - ]: 55312 : return strprintf("returned type is %s, but declared as %s in doc", uvTypeName(result.getType()), uvTypeName(*exp_type));
1165 : : }
1166 : :
1167 [ + + ]: 4148936 : if (UniValue::VARR == result.getType()) {
1168 : 173005 : UniValue errors(UniValue::VOBJ);
1169 [ + - + + ]: 887773 : 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 [ + + + - ]: 1429228 : const RPCResult& doc_inner{m_inner.at(std::min(m_inner.size() - 1, i))};
1172 [ + - + - : 714768 : UniValue match{doc_inner.MatchesType(result.get_array()[i])};
+ - ]
1173 [ + + + - : 724981 : if (!match.isTrue()) errors.pushKV(strprintf("%d", i), std::move(match));
+ - ]
1174 : 714768 : }
1175 [ + + + - ]: 173005 : if (errors.empty()) return true; // empty result array is valid
1176 : 269 : return errors;
1177 : 173005 : }
1178 : :
1179 [ + + ]: 3975931 : if (UniValue::VOBJ == result.getType()) {
1180 [ + + + + ]: 385854 : if (!m_inner.empty() && m_inner.at(0).m_type == Type::ELISION) return true;
1181 : 384717 : UniValue errors(UniValue::VOBJ);
1182 [ + + ]: 384717 : if (m_type == Type::OBJ_DYN) {
1183 [ + - ]: 26945 : const RPCResult& doc_inner{m_inner.at(0)}; // Assume all types are the same, randomly pick the first
1184 [ + - + + ]: 257621 : for (size_t i{0}; i < result.get_obj().size(); ++i) {
1185 [ + - + - : 230676 : UniValue match{doc_inner.MatchesType(result.get_obj()[i])};
+ - ]
1186 [ + + + - : 230708 : if (!match.isTrue()) errors.pushKV(result.getKeys()[i], std::move(match));
+ - + - ]
1187 : 230676 : }
1188 [ + + + - ]: 26945 : if (errors.empty()) return true; // empty result obj is valid
1189 : 16 : return errors;
1190 : : }
1191 : 357772 : std::set<std::string> doc_keys;
1192 [ + + ]: 3794549 : for (const auto& doc_entry : m_inner) {
1193 [ + - ]: 3436777 : doc_keys.insert(doc_entry.m_key_name);
1194 : : }
1195 [ + - ]: 357772 : std::map<std::string, UniValue> result_obj;
1196 [ + - ]: 357772 : result.getObjMap(result_obj);
1197 [ + + ]: 3380164 : for (const auto& result_entry : result_obj) {
1198 [ + + ]: 3022392 : if (doc_keys.find(result_entry.first) == doc_keys.end()) {
1199 [ + - + - : 40 : errors.pushKV(result_entry.first, "key returned that was not in doc");
+ - ]
1200 : : }
1201 : : }
1202 : :
1203 [ + + ]: 3794549 : for (const auto& doc_entry : m_inner) {
1204 : 3436777 : const auto result_it{result_obj.find(doc_entry.m_key_name)};
1205 [ + + ]: 3436777 : if (result_it == result_obj.end()) {
1206 [ - + ]: 414405 : if (!doc_entry.m_optional) {
1207 [ # # # # : 0 : errors.pushKV(doc_entry.m_key_name, "key missing, despite not being optional in doc");
# # ]
1208 : : }
1209 : 414405 : continue;
1210 : : }
1211 [ + - ]: 3022372 : UniValue match{doc_entry.MatchesType(result_it->second)};
1212 [ + + + - : 3022501 : if (!match.isTrue()) errors.pushKV(doc_entry.m_key_name, std::move(match));
+ - ]
1213 : 3022372 : }
1214 [ + + + - ]: 357772 : if (errors.empty()) return true;
1215 : 144 : return errors;
1216 : 384717 : }
1217 : :
1218 : 3590077 : return true;
1219 : : }
1220 : :
1221 : 4454363 : void RPCResult::CheckInnerDoc() const
1222 : : {
1223 [ + + ]: 4454363 : 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 [ + + + + ]: 3912795 : const bool inner_needed{m_type == Type::ARR || m_type == Type::ARR_FIXED || m_type == Type::OBJ_DYN};
1229 : 3912795 : CHECK_NONFATAL(inner_needed != m_inner.empty());
1230 : : }
1231 : :
1232 : : // NOLINTNEXTLINE(misc-no-recursion)
1233 : 780 : std::string RPCArg::ToStringObj(const bool oneline) const
1234 : : {
1235 [ + - ]: 780 : std::string res;
1236 [ + - ]: 780 : res += "\"";
1237 [ + - ]: 1560 : res += GetFirstName();
1238 [ + + ]: 780 : if (oneline) {
1239 [ + - ]: 341 : res += "\":";
1240 : : } else {
1241 [ + - ]: 439 : res += "\": ";
1242 : : }
1243 [ + + + + : 780 : switch (m_type) {
+ + + -
- ]
1244 : 121 : case Type::STR:
1245 [ + - ]: 121 : return res + "\"str\"";
1246 : 259 : case Type::STR_HEX:
1247 [ + - ]: 259 : return res + "\"hex\"";
1248 : 187 : case Type::NUM:
1249 [ + - ]: 187 : return res + "n";
1250 : 70 : case Type::RANGE:
1251 [ + - ]: 70 : return res + "n or [n,n]";
1252 : 98 : case Type::AMOUNT:
1253 [ + - ]: 98 : return res + "amount";
1254 : 27 : case Type::BOOL:
1255 [ + - ]: 27 : return res + "bool";
1256 : 18 : case Type::ARR:
1257 [ + - ]: 18 : res += "[";
1258 [ + + ]: 45 : for (const auto& i : m_inner) {
1259 [ + - + - ]: 81 : res += i.ToString(oneline) + ",";
1260 : : }
1261 [ + - ]: 18 : 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 : 780 : }
1270 : :
1271 : : // NOLINTNEXTLINE(misc-no-recursion)
1272 : 2382 : std::string RPCArg::ToString(const bool oneline) const
1273 : : {
1274 [ + + + + ]: 2382 : if (oneline && !m_opts.oneline_description.empty()) {
1275 [ + + + - : 90 : 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 : 90 : return m_opts.oneline_description;
1282 : : }
1283 : :
1284 [ + + + + : 2292 : switch (m_type) {
- ]
1285 : 1213 : case Type::STR_HEX:
1286 : 1213 : case Type::STR: {
1287 [ + - ]: 2426 : return "\"" + GetFirstName() + "\"";
1288 : : }
1289 : 712 : case Type::NUM:
1290 : 712 : case Type::RANGE:
1291 : 712 : case Type::AMOUNT:
1292 : 712 : case Type::BOOL: {
1293 : 712 : return GetFirstName();
1294 : : }
1295 : 156 : case Type::OBJ:
1296 : 156 : case Type::OBJ_NAMED_PARAMS:
1297 : 156 : case Type::OBJ_USER_KEYS: {
1298 : : // NOLINTNEXTLINE(misc-no-recursion)
1299 [ + - ]: 497 : const std::string res = Join(m_inner, ",", [&](const RPCArg& i) { return i.ToStringObj(oneline); });
1300 [ + + ]: 156 : if (m_type == Type::OBJ) {
1301 [ + - ]: 208 : return "{" + res + "}";
1302 : : } else {
1303 [ + - ]: 104 : return "{" + res + ",...}";
1304 : : }
1305 : 156 : }
1306 : 211 : case Type::ARR: {
1307 : 211 : std::string res;
1308 [ + + ]: 471 : for (const auto& i : m_inner) {
1309 [ + - + - ]: 780 : res += i.ToString(oneline) + ",";
1310 : : }
1311 [ + - ]: 422 : return "[" + res + "...]";
1312 : 211 : }
1313 : : } // no default case, so the compiler can warn about missing cases
1314 [ # # ]: 0 : NONFATAL_UNREACHABLE();
1315 : : }
1316 : :
1317 : 208 : static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
1318 : : {
1319 [ + + ]: 208 : if (value.isNum()) {
1320 : 86 : return {0, value.getInt<int64_t>()};
1321 : : }
1322 [ + - + - : 122 : if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
+ - + - ]
1323 : 122 : int64_t low = value[0].getInt<int64_t>();
1324 : 122 : int64_t high = value[1].getInt<int64_t>();
1325 [ + + + - : 126 : if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
+ - ]
1326 : 118 : return {low, high};
1327 : : }
1328 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified as end or as [begin,end]");
1329 : : }
1330 : :
1331 : 208 : std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value)
1332 : : {
1333 : 208 : int64_t low, high;
1334 [ + + ]: 208 : std::tie(low, high) = ParseRange(value);
1335 [ + + ]: 204 : if (low < 0) {
1336 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should be greater or equal than 0");
1337 : : }
1338 [ + + ]: 200 : if ((high >> 31) != 0) {
1339 [ + - + - ]: 12 : throw JSONRPCError(RPC_INVALID_PARAMETER, "End of range is too high");
1340 : : }
1341 [ + + ]: 194 : if (high >= low + 1000000) {
1342 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range is too large");
1343 : : }
1344 : 190 : return {low, high};
1345 : : }
1346 : :
1347 : 1063 : std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv)
1348 : : {
1349 [ + + ]: 1063 : std::string desc_str;
1350 : 1063 : std::pair<int64_t, int64_t> range = {0, 1000};
1351 [ + + ]: 1063 : if (scanobject.isStr()) {
1352 [ + - + - ]: 1037 : desc_str = scanobject.get_str();
1353 [ + - ]: 26 : } else if (scanobject.isObject()) {
1354 [ + - ]: 26 : const UniValue& desc_uni{scanobject.find_value("desc")};
1355 [ - + - - : 26 : if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
- - ]
1356 [ + - + - ]: 26 : desc_str = desc_uni.get_str();
1357 [ + - ]: 26 : const UniValue& range_uni{scanobject.find_value("range")};
1358 [ + + ]: 26 : if (!range_uni.isNull()) {
1359 [ + + ]: 19 : range = ParseDescriptorRange(range_uni);
1360 : : }
1361 : : } else {
1362 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
1363 : : }
1364 : :
1365 [ + - ]: 1058 : std::string error;
1366 [ + - ]: 1058 : auto descs = Parse(desc_str, provider, error);
1367 [ + + ]: 1058 : if (descs.empty()) {
1368 [ + - ]: 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
1369 : : }
1370 [ + - + - : 1057 : if (!descs.at(0)->IsRange()) {
+ + ]
1371 : 1043 : range.first = 0;
1372 : 1043 : range.second = 0;
1373 : : }
1374 : 1057 : std::vector<CScript> ret;
1375 [ + + ]: 20208 : for (int i = range.first; i <= range.second; ++i) {
1376 [ + + ]: 38303 : for (const auto& desc : descs) {
1377 : 19152 : std::vector<CScript> scripts;
1378 [ + - - + ]: 19152 : 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 [ + + ]: 19152 : if (expand_priv) {
1382 [ + - ]: 4 : desc->ExpandPrivate(/*pos=*/i, provider, /*out=*/provider);
1383 : : }
1384 [ + - ]: 19152 : std::move(scripts.begin(), scripts.end(), std::back_inserter(ret));
1385 : 19152 : }
1386 : : }
1387 : 2114 : return ret;
1388 : 1059 : }
1389 : :
1390 : : /** Convert a vector of bilingual strings to a UniValue::VARR containing their original untranslated values. */
1391 : 484 : [[nodiscard]] static UniValue BilingualStringsToUniValue(const std::vector<bilingual_str>& bilingual_strings)
1392 : : {
1393 : 484 : CHECK_NONFATAL(!bilingual_strings.empty());
1394 : 484 : UniValue result{UniValue::VARR};
1395 [ + + ]: 973 : for (const auto& s : bilingual_strings) {
1396 [ + - + - ]: 489 : result.push_back(s.original);
1397 : : }
1398 : 484 : return result;
1399 : 0 : }
1400 : :
1401 : 793 : void PushWarnings(const UniValue& warnings, UniValue& obj)
1402 : : {
1403 [ + + ]: 793 : if (warnings.empty()) return;
1404 [ + - + - ]: 638 : obj.pushKV("warnings", warnings);
1405 : : }
1406 : :
1407 : 912 : void PushWarnings(const std::vector<bilingual_str>& warnings, UniValue& obj)
1408 : : {
1409 [ + + ]: 912 : if (warnings.empty()) return;
1410 [ + - + - ]: 968 : obj.pushKV("warnings", BilingualStringsToUniValue(warnings));
1411 : : }
1412 : :
1413 : 20543 : std::vector<RPCResult> ScriptPubKeyDoc() {
1414 : 20543 : 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 [ + - + - ]: 41086 : {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
1421 [ + - + - : 184887 : };
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + + -
- ]
1422 [ + - + - : 123258 : }
+ - + - +
- + - -
- ]
1423 : :
1424 : 23903 : uint256 GetTarget(const CBlockIndex& blockindex, const uint256 pow_limit)
1425 : : {
1426 : 23903 : arith_uint256 target{*CHECK_NONFATAL(DeriveTarget(blockindex.nBits, pow_limit))};
1427 : 23903 : return ArithToUint256(target);
1428 : : }
|