LCOV - code coverage report
Current view: top level - src/rpc - util.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.3 % 872 822
Test Date: 2026-10-23 06:14:09 Functions: 97.7 % 86 84
Branches: 60.5 % 1698 1027

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

Generated by: LCOV version 2.0-1