LCOV - code coverage report
Current view: top level - src/rpc - util.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 77.5 % 845 655
Test Date: 2025-08-22 17:03:49 Functions: 82.9 % 82 68
Branches: 49.5 % 1694 838

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

Generated by: LCOV version 2.0-1