LCOV - code coverage report
Current view: top level - src/rpc - util.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 56.3 % 844 475
Test Date: 2025-11-13 04:35:55 Functions: 59.0 % 83 49
Branches: 33.9 % 1702 577

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

Generated by: LCOV version 2.0-1