LCOV - code coverage report
Current view: top level - src/rpc - util.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.9 % 830 771
Test Date: 2024-07-04 05:05:02 Functions: 96.2 % 78 75
Branches: 59.9 % 1564 937

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

Generated by: LCOV version 2.0-1