LCOV - code coverage report
Current view: top level - src/rpc - util.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 57.5 % 870 500
Test Date: 2026-08-07 06:33:33 Functions: 60.0 % 85 51
Branches: 34.2 % 1726 590

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

Generated by: LCOV version 2.0-1