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