LCOV - code coverage report
Current view: top level - src/wallet/rpc - wallet.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 97.9 % 750 734
Test Date: 2026-11-29 07:05:02 Functions: 100.0 % 29 29
Branches: 51.5 % 2764 1424

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <bitcoin-build-config.h>
       7                 :             : 
       8                 :             : #include <wallet/rpc/wallet.h>
       9                 :             : 
      10                 :             : #include <coins.h>
      11                 :             : #include <core_io.h>
      12                 :             : #include <key.h>
      13                 :             : #include <key_io.h>
      14                 :             : #include <rpc/server.h>
      15                 :             : #include <rpc/util.h>
      16                 :             : #include <univalue.h>
      17                 :             : #include <util/bip32.h>
      18                 :             : #include <util/translation.h>
      19                 :             : #include <wallet/context.h>
      20                 :             : #include <wallet/export.h>
      21                 :             : #include <wallet/migration.h>
      22                 :             : #include <wallet/receive.h>
      23                 :             : #include <wallet/rpc/util.h>
      24                 :             : #include <wallet/scan.h>
      25                 :             : #include <wallet/wallet.h>
      26                 :             : #include <wallet/walletutil.h>
      27                 :             : 
      28                 :             : #include <algorithm>
      29                 :             : #include <optional>
      30                 :             : #include <string_view>
      31                 :             : 
      32                 :             : 
      33                 :             : namespace wallet {
      34                 :             : 
      35                 :             : using HDPubKeyMap = CWallet::HDPubKeyMap;
      36                 :             : using HDKeyFilter = CWallet::HDKeyFilter;
      37                 :             : 
      38                 :             : static const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS{
      39                 :             :     {WALLET_FLAG_AVOID_REUSE,
      40                 :             :      "You need to rescan the blockchain in order to correctly mark used "
      41                 :             :      "destinations in the past. Until this is done, some destinations may "
      42                 :             :      "be considered unused, even if the opposite is the case."},
      43                 :             : };
      44                 :             : 
      45                 :        1361 : static RPCMethod getwalletinfo()
      46                 :             : {
      47                 :        1361 :     return RPCMethod{"getwalletinfo",
      48         [ +  - ]:        2722 :                 "Returns an object containing various wallet state info.\n",
      49                 :             :                 {},
      50         [ +  - ]:        2722 :                 RPCResult{
      51         [ +  - ]:        2722 :                     RPCResult::Type::OBJ, "", "",
      52                 :             :                     {
      53                 :             :                         {
      54   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::STR, "walletname", "the wallet name"},
      55   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM, "walletversion", "(DEPRECATED) only related to unsupported legacy wallet, returns the latest version 169900 for backwards compatibility"},
      56   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::STR, "format", "the database format (only sqlite)"},
      57   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM, "txcount", "the total number of transactions in the wallet"},
      58   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM, "keypoolsize", "how many new keys are pre-generated (only counts external keys)"},
      59   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM, "keypoolsize_hd_internal", "how many new keys are pre-generated for internal use (used for change outputs; 0 if external keys are used for change)"},
      60   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM_TIME, "unlocked_until", /*optional=*/true, "the " + UNIX_EPOCH_TIME + " until which the wallet is unlocked for transfers, or 0 if the wallet is locked (only present for passphrase-encrypted wallets)"},
      61   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::BOOL, "private_keys_enabled", "false if privatekeys are disabled for this wallet (enforced watch-only wallet)"},
      62   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::BOOL, "avoid_reuse", "whether this wallet tracks clean/dirty coins in terms of reuse"},
      63   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::OBJ, "scanning", "current scanning details, or false if no scan is in progress",
      64                 :             :                         {
      65   [ +  -  +  - ]:        2722 :                             {RPCResult::Type::NUM, "duration", "elapsed seconds since scan start"},
      66   [ +  -  +  - ]:        2722 :                             {RPCResult::Type::NUM, "progress", "scanning progress percentage [0.0, 1.0]"},
      67                 :             :                         }, {.skip_type_check=true}, },
      68   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::BOOL, "descriptors", "whether this wallet uses descriptors for output script management"},
      69   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::BOOL, "external_signer", "whether this wallet is configured to use an external signer such as a hardware wallet"},
      70   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::BOOL, "blank", "Whether this wallet intentionally does not contain any keys, scripts, or descriptors"},
      71   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::NUM_TIME, "birthtime", /*optional=*/true, "The start time for blocks scanning. It could be modified by (re)importing any descriptor with an earlier timestamp."},
      72   [ +  -  +  - ]:        2722 :                         {RPCResult::Type::ARR, "flags", "The flags currently set on the wallet",
      73                 :             :                         {
      74   [ +  -  +  - ]:        2722 :                             {RPCResult::Type::STR, "flag", "The name of the flag"},
      75                 :             :                         }},
      76                 :             :                         RESULT_LAST_PROCESSED_BLOCK,
      77                 :             :                     }},
      78   [ +  -  +  -  :       55801 :                 },
          +  -  +  -  +  
          +  +  +  +  +  
          -  -  -  -  -  
                      - ]
      79                 :        1361 :                 RPCExamples{
      80   [ +  -  +  -  :        2722 :                     HelpExampleCli("getwalletinfo", "")
                   +  - ]
      81   [ +  -  +  -  :        5444 :             + HelpExampleRpc("getwalletinfo", "")
             +  -  +  - ]
      82         [ +  - ]:        1361 :                 },
      83                 :        1361 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
      84                 :             : {
      85         [ -  + ]:         464 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
      86         [ -  + ]:         454 :     if (!pwallet) return UniValue::VNULL;
      87                 :             : 
      88                 :             :     // Make sure the results are valid at least up to the most recent block
      89                 :             :     // the user could have gotten from another RPC command prior to now
      90         [ +  - ]:         454 :     pwallet->BlockUntilSyncedToCurrentChain();
      91                 :             : 
      92         [ +  - ]:         454 :     LOCK(pwallet->cs_wallet);
      93                 :             : 
      94                 :         454 :     UniValue obj(UniValue::VOBJ);
      95                 :             : 
      96                 :         454 :     const int latest_legacy_wallet_minversion{169900};
      97                 :             : 
      98         [ +  - ]:         454 :     size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
      99   [ +  -  +  -  :         908 :     obj.pushKV("walletname", pwallet->GetName());
                   +  - ]
     100   [ +  -  +  -  :         908 :     obj.pushKV("walletversion", latest_legacy_wallet_minversion);
                   +  - ]
     101   [ +  -  +  -  :         908 :     obj.pushKV("format", pwallet->GetDatabase().Format());
             +  -  +  - ]
     102   [ +  -  +  -  :         908 :     obj.pushKV("txcount", pwallet->mapWallet.size());
                   +  - ]
     103   [ +  -  +  -  :         908 :     obj.pushKV("keypoolsize", kpExternalSize);
                   +  - ]
     104   [ +  -  +  -  :         908 :     obj.pushKV("keypoolsize_hd_internal", pwallet->GetKeyPoolSize() - kpExternalSize);
             +  -  +  - ]
     105                 :             : 
     106   [ +  -  +  + ]:         454 :     if (pwallet->HasEncryptionKeys()) {
     107   [ +  -  +  -  :          72 :         obj.pushKV("unlocked_until", pwallet->nRelockTime);
                   +  - ]
     108                 :             :     }
     109   [ +  -  +  -  :         908 :     obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
             +  -  +  - ]
     110   [ +  -  +  -  :         908 :     obj.pushKV("avoid_reuse", pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE));
             +  -  +  - ]
     111   [ +  -  -  + ]:         454 :     if (pwallet->Scanner().IsScanning()) {
     112                 :           0 :         UniValue scanning(UniValue::VOBJ);
     113   [ #  #  #  #  :           0 :         scanning.pushKV("duration", Ticks<std::chrono::seconds>(pwallet->Scanner().ScanningDuration()));
             #  #  #  # ]
     114   [ #  #  #  #  :           0 :         scanning.pushKV("progress", pwallet->Scanner().ScanningProgress());
             #  #  #  # ]
     115   [ #  #  #  # ]:           0 :         obj.pushKV("scanning", std::move(scanning));
     116                 :           0 :     } else {
     117   [ +  -  +  -  :         908 :         obj.pushKV("scanning", false);
                   +  - ]
     118                 :             :     }
     119   [ +  -  +  -  :         908 :     obj.pushKV("descriptors", pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
             +  -  +  - ]
     120   [ +  -  +  -  :         908 :     obj.pushKV("external_signer", pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER));
             +  -  +  - ]
     121   [ +  -  +  -  :         908 :     obj.pushKV("blank", pwallet->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
             +  -  +  - ]
     122         [ +  + ]:         454 :     if (int64_t birthtime = pwallet->GetBirthTime(); birthtime != UNKNOWN_TIME) {
     123   [ +  -  +  -  :         818 :         obj.pushKV("birthtime", birthtime);
                   +  - ]
     124                 :             :     }
     125                 :             : 
     126                 :             :     // Push known flags
     127                 :         454 :     UniValue flags(UniValue::VARR);
     128         [ +  - ]:         454 :     uint64_t wallet_flags = pwallet->GetWalletFlags();
     129         [ +  + ]:       29510 :     for (uint64_t i = 0; i < 64; ++i) {
     130                 :       29056 :         uint64_t flag = uint64_t{1} << i;
     131         [ +  + ]:       29056 :         if (flag & wallet_flags) {
     132         [ +  - ]:        1142 :             if (flag & KNOWN_WALLET_FLAGS) {
     133   [ +  -  +  -  :        1142 :                 flags.push_back(WALLET_FLAG_TO_STRING.at(WalletFlags{flag}));
                   +  - ]
     134                 :             :             } else {
     135   [ #  #  #  #  :           0 :                 flags.push_back(strprintf("unknown_flag_%u", i));
                   #  # ]
     136                 :             :             }
     137                 :             :         }
     138                 :             :     }
     139   [ +  -  +  -  :         908 :     obj.pushKV("flags", flags);
                   +  - ]
     140                 :             : 
     141         [ +  - ]:         454 :     AppendLastProcessedBlock(obj, *pwallet);
     142                 :         454 :     return obj;
     143         [ +  - ]:        1362 : },
     144   [ +  -  +  - ]:        5444 :     };
     145   [ +  -  +  -  :       48996 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
                -  -  - ]
     146                 :             : 
     147                 :         973 : static RPCMethod listwalletdir()
     148                 :             : {
     149                 :         973 :     return RPCMethod{"listwalletdir",
     150         [ +  - ]:        1946 :                 "Returns a list of wallets in the wallet directory.\n",
     151                 :             :                 {},
     152         [ +  - ]:        1946 :                 RPCResult{
     153         [ +  - ]:        1946 :                     RPCResult::Type::OBJ, "", "",
     154                 :             :                     {
     155   [ +  -  +  - ]:        1946 :                         {RPCResult::Type::ARR, "wallets", "",
     156                 :             :                         {
     157   [ +  -  +  - ]:        1946 :                             {RPCResult::Type::OBJ, "", "",
     158                 :             :                             {
     159   [ +  -  +  - ]:        1946 :                                 {RPCResult::Type::STR, "name", "The wallet name"},
     160   [ +  -  +  - ]:        1946 :                                 {RPCResult::Type::ARR, "warnings", "Warning messages related to loading the wallet (may be empty).",
     161                 :             :                                 {
     162   [ +  -  +  - ]:        1946 :                                     {RPCResult::Type::STR, "", ""},
     163                 :             :                                 }},
     164                 :             :                             }},
     165                 :             :                         }},
     166                 :             :                     }
     167   [ +  -  +  -  :       14595 :                 },
          +  -  +  -  +  
          -  +  +  +  +  
          +  +  +  +  -  
          -  -  -  -  -  
                   -  - ]
     168                 :         973 :                 RPCExamples{
     169   [ +  -  +  -  :        1946 :                     HelpExampleCli("listwalletdir", "")
                   +  - ]
     170   [ +  -  +  -  :        3892 :             + HelpExampleRpc("listwalletdir", "")
             +  -  +  - ]
     171         [ +  - ]:         973 :                 },
     172                 :         973 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     173                 :             : {
     174                 :          76 :     UniValue wallets(UniValue::VARR);
     175   [ +  -  +  -  :        1928 :     for (const auto& [path, db_type] : ListDatabases(GetWalletDir())) {
                   +  + ]
     176                 :        1776 :         UniValue wallet(UniValue::VOBJ);
     177   [ +  -  +  -  :        3552 :         wallet.pushKV("name", path.utf8string());
             +  -  +  - ]
     178                 :        1776 :                 UniValue warnings(UniValue::VARR);
     179         [ +  + ]:        1776 :         if (db_type == "bdb") {
     180   [ +  -  +  - ]:         283 :             warnings.push_back("This wallet is a legacy wallet and will need to be migrated with migratewallet before it can be loaded");
     181                 :             :         }
     182   [ +  -  +  -  :        3552 :         wallet.pushKV("warnings", warnings);
                   +  - ]
     183         [ +  - ]:        1776 :         wallets.push_back(std::move(wallet));
     184                 :        1852 :     }
     185                 :             : 
     186                 :          76 :     UniValue result(UniValue::VOBJ);
     187   [ +  -  +  - ]:         152 :     result.pushKV("wallets", std::move(wallets));
     188                 :          76 :     return result;
     189                 :          76 : },
     190   [ +  -  +  - ]:        3892 :     };
     191   [ +  -  +  -  :        9730 : }
          +  -  +  -  +  
                -  -  - ]
     192                 :             : 
     193                 :         976 : static RPCMethod listwallets()
     194                 :             : {
     195                 :         976 :     return RPCMethod{"listwallets",
     196         [ +  - ]:        1952 :                 "Returns a list of currently loaded wallets.\n"
     197                 :             :                 "For full information on the wallet, use \"getwalletinfo\"\n",
     198                 :             :                 {},
     199         [ +  - ]:        1952 :                 RPCResult{
     200         [ +  - ]:        1952 :                     RPCResult::Type::ARR, "", "",
     201                 :             :                     {
     202   [ +  -  +  - ]:        1952 :                         {RPCResult::Type::STR, "walletname", "the wallet name"},
     203                 :             :                     }
     204   [ +  -  +  -  :        3904 :                 },
             +  +  -  - ]
     205                 :         976 :                 RPCExamples{
     206   [ +  -  +  -  :        1952 :                     HelpExampleCli("listwallets", "")
                   +  - ]
     207   [ +  -  +  -  :        3904 :             + HelpExampleRpc("listwallets", "")
             +  -  +  - ]
     208         [ +  - ]:         976 :                 },
     209                 :         976 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     210                 :             : {
     211                 :          79 :     UniValue obj(UniValue::VARR);
     212                 :             : 
     213         [ +  - ]:          79 :     WalletContext& context = EnsureWalletContext(request.context);
     214   [ +  -  +  + ]:         679 :     for (const std::shared_ptr<CWallet>& wallet : GetWallets(context)) {
     215         [ +  - ]:         600 :         LOCK(wallet->cs_wallet);
     216   [ +  -  +  -  :         600 :         obj.push_back(wallet->GetName());
                   +  - ]
     217                 :         679 :     }
     218                 :             : 
     219                 :          79 :     return obj;
     220                 :           0 : },
     221   [ +  -  +  - ]:        3904 :     };
     222         [ +  - ]:        1952 : }
     223                 :             : 
     224                 :        1103 : static RPCMethod loadwallet()
     225                 :             : {
     226                 :        1103 :     return RPCMethod{
     227                 :        1103 :         "loadwallet",
     228         [ +  - ]:        2206 :         "Loads a wallet from a wallet file or directory."
     229                 :             :                 "\nNote that all wallet command-line options used when starting bitcoind will be"
     230                 :             :                 "\napplied to the new wallet.\n",
     231                 :             :                 {
     232   [ +  -  +  - ]:        2206 :                     {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The path to the directory of the wallet to be loaded, either absolute or relative to the \"wallets\" directory. The \"wallets\" directory is set by the -walletdir option and defaults to the \"wallets\" folder within the data directory."},
     233   [ +  -  +  - ]:        2206 :                     {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
     234                 :             :                 },
     235         [ +  - ]:        2206 :                 RPCResult{
     236   [ +  -  +  - ]:        2206 :                     RPCResult::Type::OBJ, "", "",
     237                 :             :                     {
     238   [ +  -  +  - ]:        2206 :                         {RPCResult::Type::STR, "name", "The wallet name if loaded successfully."},
     239   [ +  -  +  - ]:        2206 :                         {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to loading the wallet.",
     240                 :             :                         {
     241   [ +  -  +  - ]:        2206 :                             {RPCResult::Type::STR, "", ""},
     242                 :             :                         }},
     243                 :             :                     }
     244   [ +  -  +  -  :        9927 :                 },
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     245                 :        1103 :                 RPCExamples{
     246                 :             :                     "\nLoad wallet from the wallet dir:\n"
     247   [ +  -  +  -  :        2206 :                     + HelpExampleCli("loadwallet", "\"walletname\"")
             +  -  +  - ]
     248   [ +  -  +  -  :        4412 :                     + HelpExampleRpc("loadwallet", "\"walletname\"")
             +  -  +  - ]
     249                 :        1103 :                     + "\nLoad wallet using absolute path (Unix):\n"
     250   [ +  -  +  -  :        4412 :                     + HelpExampleCli("loadwallet", "\"/path/to/walletname/\"")
             +  -  +  - ]
     251   [ +  -  +  -  :        4412 :                     + HelpExampleRpc("loadwallet", "\"/path/to/walletname/\"")
             +  -  +  - ]
     252                 :        1103 :                     + "\nLoad wallet using absolute path (Windows):\n"
     253   [ +  -  +  -  :        4412 :                     + HelpExampleCli("loadwallet", "\"DriveLetter:\\path\\to\\walletname\\\"")
             +  -  +  - ]
     254   [ +  -  +  -  :        4412 :                     + HelpExampleRpc("loadwallet", R"("DriveLetter:\\path\\to\\walletname")")
             +  -  +  - ]
     255         [ +  - ]:        1103 :                 },
     256                 :        1103 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     257                 :             : {
     258                 :         206 :     WalletContext& context = EnsureWalletContext(request.context);
     259         [ -  + ]:         206 :     const std::string name(request.params[0].get_str());
     260                 :             : 
     261         [ +  - ]:         206 :     DatabaseOptions options;
     262                 :         206 :     DatabaseStatus status;
     263         [ +  - ]:         206 :     ReadDatabaseArgs(*context.args, options);
     264                 :         206 :     options.require_existing = true;
     265         [ +  - ]:         206 :     bilingual_str error;
     266                 :         206 :     std::vector<bilingual_str> warnings;
     267   [ +  -  +  +  :         206 :     std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool());
             +  -  +  - ]
     268                 :             : 
     269                 :         206 :     {
     270         [ +  - ]:         206 :         LOCK(context.wallets_mutex);
     271   [ +  +  +  + ]:        1039 :         if (std::any_of(context.wallets.begin(), context.wallets.end(), [&name](const auto& wallet) { return wallet->GetName() == name; })) {
     272   [ +  -  +  - ]:           6 :             throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded.");
     273                 :             :         }
     274                 :           2 :     }
     275                 :             : 
     276         [ +  - ]:         204 :     std::shared_ptr<CWallet> const wallet = LoadWallet(context, name, load_on_start, options, status, error, warnings);
     277                 :             : 
     278         [ +  + ]:         204 :     HandleWalletError(wallet, status, error);
     279                 :             : 
     280                 :         185 :     UniValue obj(UniValue::VOBJ);
     281   [ +  -  +  -  :         370 :     obj.pushKV("name", wallet->GetName());
                   +  - ]
     282         [ +  - ]:         185 :     PushWarnings(warnings, obj);
     283                 :             : 
     284         [ +  - ]:         185 :     return obj;
     285                 :         433 : },
     286   [ +  -  +  -  :        6618 :     };
             +  +  -  - ]
     287   [ +  -  +  -  :       11030 : }
          +  -  +  -  +  
             -  -  -  -  
                      - ]
     288                 :             : 
     289                 :         905 : static RPCMethod setwalletflag()
     290                 :             : {
     291                 :         905 :             std::string flags;
     292         [ +  + ]:        7240 :             for (auto& it : STRING_TO_WALLET_FLAG)
     293         [ +  + ]:        6335 :                 if (it.second & MUTABLE_WALLET_FLAGS)
     294   [ -  +  +  - ]:        1810 :                     flags += (flags == "" ? "" : ", ") + it.first;
     295                 :             : 
     296                 :         905 :     return RPCMethod{
     297         [ +  - ]:        1810 :         "setwalletflag",
     298         [ +  - ]:        1810 :         "Change the state of the given wallet flag for a wallet.\n",
     299                 :             :                 {
     300   [ +  -  +  - ]:        1810 :                     {"flag", RPCArg::Type::STR, RPCArg::Optional::NO, "The name of the flag to change. Current available flags: " + flags},
     301   [ +  -  +  -  :        2715 :                     {"value", RPCArg::Type::BOOL, RPCArg::Default{true}, "The new state."},
                   +  - ]
     302                 :             :                 },
     303         [ +  - ]:        1810 :                 RPCResult{
     304   [ +  -  +  - ]:        1810 :                     RPCResult::Type::OBJ, "", "",
     305                 :             :                     {
     306   [ +  -  +  - ]:        1810 :                         {RPCResult::Type::STR, "flag_name", "The name of the flag that was modified"},
     307   [ +  -  +  - ]:        1810 :                         {RPCResult::Type::BOOL, "flag_state", "The new state of the flag"},
     308   [ +  -  +  - ]:        1810 :                         {RPCResult::Type::STR, "warnings", /*optional=*/true, "Any warnings associated with the change"},
     309                 :             :                     }
     310   [ +  -  +  -  :        7240 :                 },
             +  +  -  - ]
     311                 :         905 :                 RPCExamples{
     312   [ +  -  +  -  :        1810 :                     HelpExampleCli("setwalletflag", "avoid_reuse")
                   +  - ]
     313   [ +  -  +  -  :        3620 :                   + HelpExampleRpc("setwalletflag", "\"avoid_reuse\"")
             +  -  +  - ]
     314         [ +  - ]:         905 :                 },
     315                 :         905 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     316                 :             : {
     317                 :           8 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     318         [ -  + ]:           8 :     if (!pwallet) return UniValue::VNULL;
     319                 :             : 
     320   [ +  -  +  -  :           8 :     std::string flag_str = request.params[0].get_str();
                   -  + ]
     321         [ +  - ]:           8 :     const bool value{self.Arg<bool>("value")};
     322                 :             : 
     323         [ +  + ]:           8 :     if (!STRING_TO_WALLET_FLAG.contains(flag_str)) {
     324   [ +  -  +  - ]:           2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unknown wallet flag: %s", flag_str));
     325                 :             :     }
     326                 :             : 
     327         [ +  - ]:           7 :     auto flag = STRING_TO_WALLET_FLAG.at(flag_str);
     328                 :             : 
     329         [ +  + ]:           7 :     if (!(flag & MUTABLE_WALLET_FLAGS)) {
     330   [ +  -  +  - ]:           6 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is immutable: %s", flag_str));
     331                 :             :     }
     332                 :             : 
     333                 :           4 :     UniValue res(UniValue::VOBJ);
     334                 :             : 
     335   [ +  -  +  + ]:           4 :     if (pwallet->IsWalletFlagSet(flag) == value) {
     336   [ +  +  +  -  :           5 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is already set to %s: %s", value ? "true" : "false", flag_str));
                   +  - ]
     337                 :             :     }
     338                 :             : 
     339   [ +  -  +  -  :           4 :     res.pushKV("flag_name", flag_str);
                   +  - ]
     340   [ +  -  +  -  :           4 :     res.pushKV("flag_state", value);
                   +  - ]
     341                 :             : 
     342         [ +  + ]:           2 :     if (value) {
     343         [ +  - ]:           1 :         pwallet->SetWalletFlag(flag);
     344                 :             :     } else {
     345         [ +  - ]:           1 :         pwallet->UnsetWalletFlag(flag);
     346                 :             :     }
     347                 :             : 
     348   [ +  -  +  +  :           2 :     if (flag && value && WALLET_FLAG_CAVEATS.contains(flag)) {
                   +  - ]
     349   [ +  -  +  -  :           2 :         res.pushKV("warnings", WALLET_FLAG_CAVEATS.at(flag));
             +  -  +  - ]
     350                 :             :     }
     351                 :             : 
     352                 :           2 :     return res;
     353                 :          12 : },
     354   [ +  -  +  -  :        4525 :     };
             +  +  -  - ]
     355   [ +  -  +  -  :        9955 : }
          +  -  +  -  +  
             -  -  -  -  
                      - ]
     356                 :             : 
     357                 :        1584 : static RPCMethod createwallet()
     358                 :             : {
     359                 :        1584 :     return RPCMethod{
     360                 :        1584 :         "createwallet",
     361         [ +  - ]:        3168 :         "Creates and loads a new wallet.\n",
     362                 :             :         {
     363   [ +  -  +  - ]:        3168 :             {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name for the new wallet. If this is a path, the wallet will be created at the path location."},
     364   [ +  -  +  -  :        4752 :             {"disable_private_keys", RPCArg::Type::BOOL, RPCArg::Default{false}, "Disable the possibility of private keys (only watchonlys are possible in this mode)."},
                   +  - ]
     365   [ +  -  +  -  :        4752 :             {"blank", RPCArg::Type::BOOL, RPCArg::Default{false}, "Create a blank wallet. A blank wallet has no keys."},
                   +  - ]
     366   [ +  -  +  - ]:        3168 :             {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Encrypt the wallet with this passphrase."},
     367   [ +  -  +  -  :        4752 :             {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{false}, "Keep track of coin reuse, and treat dirty and clean coins differently with privacy considerations in mind."},
                   +  - ]
     368   [ +  -  +  -  :        4752 :             {"descriptors", RPCArg::Type::BOOL, RPCArg::Default{true}, "If set, must be \"true\""},
                   +  - ]
     369   [ +  -  +  - ]:        3168 :             {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
     370   [ +  -  +  -  :        4752 :             {"external_signer", RPCArg::Type::BOOL, RPCArg::Default{false}, "Use an external signer such as a hardware wallet. Requires -signer to be configured. Wallet creation will fail if keys cannot be fetched. Requires disable_private_keys and descriptors set to true."},
                   +  - ]
     371                 :             :         },
     372         [ +  - ]:        3168 :         RPCResult{
     373   [ +  -  +  - ]:        3168 :             RPCResult::Type::OBJ, "", "",
     374                 :             :             {
     375   [ +  -  +  - ]:        3168 :                 {RPCResult::Type::STR, "name", "The wallet name if created successfully. If the wallet was created using a full path, the wallet_name will be the full path."},
     376   [ +  -  +  - ]:        3168 :                 {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to creating and loading the wallet.",
     377                 :             :                 {
     378   [ +  -  +  - ]:        3168 :                     {RPCResult::Type::STR, "", ""},
     379                 :             :                 }},
     380                 :             :             }
     381   [ +  -  +  -  :       14256 :         },
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     382                 :        1584 :         RPCExamples{
     383   [ +  -  +  -  :        3168 :             HelpExampleCli("createwallet", "\"testwallet\"")
                   +  - ]
     384   [ +  -  +  -  :        6336 :             + HelpExampleRpc("createwallet", "\"testwallet\"")
             +  -  +  - ]
     385   [ +  -  +  -  :       11088 :             + HelpExampleCliNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"load_on_startup", true}})
          +  -  +  -  +  
                +  -  - ]
     386   [ +  -  +  -  :       11088 :             + HelpExampleRpcNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"load_on_startup", true}})
          +  -  +  -  +  
                +  -  - ]
     387         [ +  - ]:        1584 :         },
     388                 :        1584 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     389                 :             : {
     390                 :         687 :     WalletContext& context = EnsureWalletContext(request.context);
     391                 :         687 :     uint64_t flags = 0;
     392         [ +  + ]:         687 :     if (self.Arg<bool>("disable_private_keys")) {
     393                 :         115 :         flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS;
     394                 :             :     }
     395                 :             : 
     396         [ +  + ]:         687 :     if (self.Arg<bool>("blank")) {
     397                 :         177 :         flags |= WALLET_FLAG_BLANK_WALLET;
     398                 :             :     }
     399         [ +  - ]:         687 :     SecureString passphrase;
     400         [ +  - ]:         687 :     passphrase.reserve(100);
     401                 :         687 :     std::vector<bilingual_str> warnings;
     402   [ +  -  +  + ]:         687 :     if (!request.params[3].isNull()) {
     403   [ +  -  +  -  :          25 :         passphrase = std::string_view{request.params[3].get_str()};
             -  +  +  - ]
     404         [ +  + ]:          25 :         if (passphrase.empty()) {
     405                 :             :             // Empty string means unencrypted
     406   [ +  -  +  -  :           8 :             warnings.emplace_back(Untranslated("Empty string given as passphrase, wallet will not be encrypted."));
                   +  - ]
     407                 :             :         }
     408                 :             :     }
     409                 :             : 
     410   [ +  -  +  + ]:         687 :     if (self.Arg<bool>("avoid_reuse")) {
     411                 :           5 :         flags |= WALLET_FLAG_AVOID_REUSE;
     412                 :             :     }
     413                 :         687 :     flags |= WALLET_FLAG_DESCRIPTORS;
     414   [ +  -  +  + ]:         687 :     if (!self.Arg<bool>("descriptors")) {
     415   [ +  -  +  - ]:           4 :         throw JSONRPCError(RPC_WALLET_ERROR, "descriptors argument must be set to \"true\"; it is no longer possible to create a legacy wallet.");
     416                 :             :     }
     417   [ +  -  +  + ]:         685 :     if (self.Arg<bool>("external_signer")) {
     418                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
     419                 :           6 :         flags |= WALLET_FLAG_EXTERNAL_SIGNER;
     420                 :             : #else
     421                 :             :         throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without external signing support (required for external signing)");
     422                 :             : #endif
     423                 :             :     }
     424                 :             : 
     425         [ +  - ]:         685 :     DatabaseOptions options;
     426                 :         685 :     DatabaseStatus status;
     427         [ +  - ]:         685 :     ReadDatabaseArgs(*context.args, options);
     428                 :         685 :     options.require_create = true;
     429                 :         685 :     options.create_flags = flags;
     430         [ +  - ]:         685 :     options.create_passphrase = passphrase;
     431         [ +  - ]:         685 :     bilingual_str error;
     432   [ +  -  +  +  :         685 :     std::optional<bool> load_on_start = request.params[6].isNull() ? std::nullopt : std::optional<bool>(request.params[6].get_bool());
             +  -  +  - ]
     433   [ +  -  +  -  :         685 :     const std::shared_ptr<CWallet> wallet = CreateWallet(context, request.params[0].get_str(), load_on_start, options, status, error, warnings);
                   +  + ]
     434         [ +  + ]:         682 :     HandleWalletError(wallet, status, error);
     435                 :             : 
     436                 :         646 :     UniValue obj(UniValue::VOBJ);
     437   [ +  -  +  -  :        1292 :     obj.pushKV("name", wallet->GetName());
                   +  - ]
     438         [ +  - ]:         646 :     PushWarnings(warnings, obj);
     439                 :             : 
     440         [ +  - ]:         646 :     return obj;
     441                 :        1408 : },
     442   [ +  -  +  -  :       19008 :     };
             +  +  -  - ]
     443   [ +  -  +  -  :       38016 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
                -  -  - ]
     444                 :             : 
     445                 :        1269 : static RPCMethod unloadwallet()
     446                 :             : {
     447                 :        1269 :     return RPCMethod{"unloadwallet",
     448         [ +  - ]:        2538 :                 "Unloads the wallet referenced by the request endpoint or the wallet_name argument.\n"
     449                 :             :                 "If both are specified, they must be identical.",
     450                 :             :                 {
     451   [ +  -  +  -  :        3807 :                     {"wallet_name", RPCArg::Type::STR, RPCArg::DefaultHint{"the wallet name from the RPC endpoint"}, "The name of the wallet to unload. If provided both here and in the RPC endpoint, the two must be identical."},
                   +  - ]
     452   [ +  -  +  - ]:        2538 :                     {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
     453                 :             :                 },
     454   [ +  -  +  -  :        5076 :                 RPCResult{RPCResult::Type::OBJ, "", "", {
                   +  - ]
     455   [ +  -  +  - ]:        2538 :                     {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to unloading the wallet.",
     456                 :             :                     {
     457   [ +  -  +  - ]:        2538 :                         {RPCResult::Type::STR, "", ""},
     458                 :             :                     }},
     459   [ +  -  +  -  :        8883 :                 }},
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     460                 :        1269 :                 RPCExamples{
     461   [ +  -  +  -  :        2538 :                     HelpExampleCli("unloadwallet", "wallet_name")
                   +  - ]
     462   [ +  -  +  -  :        5076 :             + HelpExampleRpc("unloadwallet", R"("wallet_name")")
             +  -  +  - ]
     463         [ +  - ]:        1269 :                 },
     464                 :        1269 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     465                 :             : {
     466                 :         372 :     const std::string wallet_name{EnsureUniqueWalletName(request, self.MaybeArg<std::string_view>("wallet_name"))};
     467                 :             : 
     468         [ +  - ]:         368 :     WalletContext& context = EnsureWalletContext(request.context);
     469         [ +  - ]:         368 :     std::shared_ptr<CWallet> wallet = GetWallet(context, wallet_name);
     470         [ +  + ]:         368 :     if (!wallet) {
     471   [ +  -  +  - ]:           8 :         throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
     472                 :             :     }
     473                 :             : 
     474                 :         364 :     std::vector<bilingual_str> warnings;
     475                 :         364 :     {
     476         [ +  - ]:         364 :         WalletRescanReserver reserver(*wallet);
     477   [ +  -  -  + ]:         364 :         if (!reserver.reserve()) {
     478   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
     479                 :             :         }
     480                 :             : 
     481                 :             :         // Release the "main" shared pointer and prevent further notifications.
     482                 :             :         // Note that any attempt to load the same wallet would fail until the wallet
     483                 :             :         // is destroyed (see CheckUniqueFileid).
     484         [ +  - ]:         364 :         std::optional<bool> load_on_start{self.MaybeArg<bool>("load_on_startup")};
     485   [ +  -  -  + ]:         364 :         if (!RemoveWallet(context, wallet, load_on_start, warnings)) {
     486   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded");
     487                 :             :         }
     488                 :         364 :     }
     489                 :             : 
     490         [ +  - ]:         364 :     WaitForDeleteWallet(std::move(wallet));
     491                 :             : 
     492                 :         364 :     UniValue result(UniValue::VOBJ);
     493         [ +  - ]:         364 :     PushWarnings(warnings, result);
     494                 :             : 
     495                 :         728 :     return result;
     496         [ -  + ]:         368 : },
     497   [ +  -  +  -  :        7614 :     };
             +  +  -  - ]
     498   [ +  -  +  -  :       10152 : }
          +  -  +  -  -  
                      - ]
     499                 :             : 
     500                 :         923 : RPCMethod simulaterawtransaction()
     501                 :             : {
     502                 :         923 :     return RPCMethod{
     503                 :         923 :         "simulaterawtransaction",
     504         [ +  - ]:        1846 :         "Calculate the balance change resulting in the signing and broadcasting of the given transaction(s).\n",
     505                 :             :         {
     506   [ +  -  +  - ]:        1846 :             {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings of raw transactions.\n",
     507                 :             :                 {
     508   [ +  -  +  - ]:        1846 :                     {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
     509                 :             :                 },
     510                 :             :             },
     511   [ +  -  +  - ]:        1846 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
     512                 :             :                 {
     513   [ +  -  +  -  :        2769 :                     {"include_watchonly", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
                   +  - ]
     514                 :             :                 },
     515                 :             :             },
     516                 :             :         },
     517         [ +  - ]:        1846 :         RPCResult{
     518   [ +  -  +  - ]:        1846 :             RPCResult::Type::OBJ, "", "",
     519                 :             :             {
     520   [ +  -  +  - ]:        1846 :                 {RPCResult::Type::STR_AMOUNT, "balance_change", "The wallet balance change (negative means decrease)."},
     521                 :             :             }
     522   [ +  -  +  -  :        3692 :         },
             +  +  -  - ]
     523                 :         923 :         RPCExamples{
     524   [ +  -  +  -  :        1846 :             HelpExampleCli("simulaterawtransaction", "[\"myhex\"]")
                   +  - ]
     525   [ +  -  +  -  :        3692 :             + HelpExampleRpc("simulaterawtransaction", "[\"myhex\"]")
             +  -  +  - ]
     526         [ +  - ]:         923 :         },
     527                 :         923 :     [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     528                 :             : {
     529         [ -  + ]:          26 :     const std::shared_ptr<const CWallet> rpc_wallet = GetWalletForJSONRPCRequest(request);
     530         [ -  + ]:          26 :     if (!rpc_wallet) return UniValue::VNULL;
     531         [ +  - ]:          26 :     const CWallet& wallet = *rpc_wallet;
     532                 :             : 
     533         [ +  - ]:          26 :     LOCK(wallet.cs_wallet);
     534                 :             : 
     535   [ +  -  +  - ]:          26 :     const auto& txs = request.params[0].get_array();
     536                 :          26 :     CAmount changes{0};
     537                 :          26 :     std::map<COutPoint, CAmount> new_utxos; // UTXO:s that were made available in transaction array
     538                 :          26 :     std::set<COutPoint> spent;
     539                 :             : 
     540   [ -  +  +  + ]:          54 :     for (size_t i = 0; i < txs.size(); ++i) {
     541         [ +  - ]:          38 :         CMutableTransaction mtx;
     542   [ +  -  +  -  :          38 :         if (!DecodeHexTx(mtx, txs[i].get_str(), /*try_no_witness=*/ true, /*try_witness=*/ true)) {
             +  -  -  + ]
     543   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Transaction hex string decoding failure.");
     544                 :             :         }
     545                 :             : 
     546                 :             :         // Fetch previous transactions (inputs)
     547                 :          38 :         std::map<COutPoint, Coin> coins;
     548         [ +  + ]:          67 :         for (const CTxIn& txin : mtx.vin) {
     549         [ +  - ]:          29 :             coins[txin.prevout]; // Create empty map entry keyed by prevout.
     550                 :             :         }
     551         [ +  - ]:          38 :         wallet.chain().findCoins(coins);
     552                 :             : 
     553                 :             :         // Fetch debit; we are *spending* these; if the transaction is signed and
     554                 :             :         // broadcast, we will lose everything in these
     555         [ +  + ]:          57 :         for (const auto& txin : mtx.vin) {
     556                 :          29 :             const auto& outpoint = txin.prevout;
     557         [ +  + ]:          29 :             if (spent.contains(outpoint)) {
     558   [ +  -  +  - ]:           6 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction(s) are spending the same output more than once");
     559                 :             :             }
     560         [ +  + ]:          26 :             if (new_utxos.contains(outpoint)) {
     561         [ +  - ]:           6 :                 changes -= new_utxos.at(outpoint);
     562                 :           6 :                 new_utxos.erase(outpoint);
     563                 :             :             } else {
     564   [ +  -  +  + ]:          20 :                 if (coins.at(outpoint).IsSpent()) {
     565   [ +  -  +  - ]:          14 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more transaction inputs are missing or have been spent already");
     566                 :             :                 }
     567         [ +  - ]:          13 :                 changes -= wallet.GetDebit(txin);
     568                 :             :             }
     569         [ +  - ]:          19 :             spent.insert(outpoint);
     570                 :             :         }
     571                 :             : 
     572                 :             :         // Iterate over outputs; we are *receiving* these, if the wallet considers
     573                 :             :         // them "mine"; if the transaction is signed and broadcast, we will receive
     574                 :             :         // everything in these
     575                 :             :         // Also populate new_utxos in case these are spent in later transactions
     576                 :             : 
     577         [ +  - ]:          28 :         const auto& hash = mtx.GetHash();
     578   [ -  +  +  + ]:          69 :         for (size_t i = 0; i < mtx.vout.size(); ++i) {
     579         [ +  - ]:          41 :             const auto& txout = mtx.vout[i];
     580         [ +  - ]:          41 :             bool is_mine = wallet.IsMine(txout);
     581   [ +  +  +  - ]:          41 :             changes += new_utxos[COutPoint(hash, i)] = is_mine ? txout.nValue : 0;
     582                 :             :         }
     583                 :          76 :     }
     584                 :             : 
     585                 :          16 :     UniValue result(UniValue::VOBJ);
     586   [ +  -  +  -  :          32 :     result.pushKV("balance_change", ValueFromAmount(changes));
                   +  - ]
     587                 :             : 
     588                 :          16 :     return result;
     589         [ +  - ]:          78 : }
     590   [ +  -  +  -  :       11076 :     };
          +  -  +  -  +  
          +  +  +  +  +  
          -  -  -  -  -  
                      - ]
     591   [ +  -  +  -  :        9230 : }
          +  -  +  -  +  
                -  -  - ]
     592                 :             : 
     593                 :         957 : static RPCMethod migratewallet()
     594                 :             : {
     595                 :         957 :     return RPCMethod{
     596                 :         957 :         "migratewallet",
     597         [ +  - ]:        1914 :         "Migrate the wallet to a descriptor wallet.\n"
     598                 :             :         "A new wallet backup will need to be made.\n"
     599                 :             :         "\nThe migration process will create a backup of the wallet before migrating. This backup\n"
     600                 :             :         "file will be named <wallet name>-<timestamp>.legacy.bak and can be found in the directory\n"
     601                 :             :         "for this wallet. In the event of an incorrect migration, the backup can be restored using restorewallet."
     602                 :             :         "\nEncrypted wallets must have the passphrase provided as an argument to this call.\n"
     603                 :             :         "\nThis RPC may take a long time to complete. Increasing the RPC client timeout is recommended.",
     604                 :             :         {
     605   [ +  -  +  -  :        2871 :             {"wallet_name", RPCArg::Type::STR, RPCArg::DefaultHint{"the wallet name from the RPC endpoint"}, "The name of the wallet to migrate. If provided both here and in the RPC endpoint, the two must be identical."},
                   +  - ]
     606   [ +  -  +  - ]:        1914 :             {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "The wallet passphrase"},
     607   [ +  -  +  -  :        2871 :             {"load_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "Load the wallet after migration."},
                   +  - ]
     608                 :             :         },
     609         [ +  - ]:        1914 :         RPCResult{
     610   [ +  -  +  - ]:        1914 :             RPCResult::Type::OBJ, "", "",
     611                 :             :             {
     612   [ +  -  +  - ]:        1914 :                 {RPCResult::Type::STR, "wallet_name", "The name of the primary migrated wallet"},
     613   [ +  -  +  - ]:        1914 :                 {RPCResult::Type::STR, "watchonly_name", /*optional=*/true, "The name of the migrated wallet containing the watchonly scripts"},
     614   [ +  -  +  - ]:        1914 :                 {RPCResult::Type::STR, "solvables_name", /*optional=*/true, "The name of the migrated wallet containing solvable but not watched scripts"},
     615   [ +  -  +  - ]:        1914 :                 {RPCResult::Type::STR, "backup_path", "The location of the backup of the original wallet"},
     616                 :             :             }
     617   [ +  -  +  -  :        9570 :         },
             +  +  -  - ]
     618                 :         957 :         RPCExamples{
     619   [ +  -  +  -  :        1914 :             HelpExampleCli("migratewallet", "")
                   +  - ]
     620   [ +  -  +  -  :        3828 :             + HelpExampleRpc("migratewallet", "")
             +  -  +  - ]
     621         [ +  - ]:         957 :         },
     622                 :         957 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     623                 :             :         {
     624                 :          60 :             const std::string wallet_name{EnsureUniqueWalletName(request, self.MaybeArg<std::string_view>("wallet_name"))};
     625                 :             : 
     626         [ +  - ]:          58 :             SecureString wallet_pass;
     627         [ +  - ]:          58 :             wallet_pass.reserve(100);
     628   [ +  -  +  + ]:          58 :             if (!request.params[1].isNull()) {
     629   [ +  -  +  -  :           5 :                 wallet_pass = std::string_view{request.params[1].get_str()};
             -  +  +  - ]
     630                 :             :             }
     631                 :             : 
     632         [ +  - ]:          58 :             const bool loadwallet = self.Arg<bool>("load_wallet");
     633                 :             : 
     634         [ +  - ]:          58 :             WalletContext& context = EnsureWalletContext(request.context);
     635         [ +  - ]:          58 :             util::Result<MigrationResult> res = MigrateLegacyToDescriptor(wallet_name, wallet_pass, context, loadwallet);
     636         [ +  + ]:          58 :             if (!res) {
     637   [ +  -  +  - ]:          28 :                 throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(res).original);
     638                 :             :             }
     639                 :             : 
     640                 :          44 :             UniValue r{UniValue::VOBJ};
     641   [ +  -  +  -  :          88 :             r.pushKV("wallet_name", res->wallet_name);
                   +  - ]
     642         [ +  + ]:          44 :             if (res->watchonly_wallet_name.has_value()) {
     643   [ +  -  +  -  :          24 :                 r.pushKV("watchonly_name", res->watchonly_wallet_name.value());
                   +  - ]
     644                 :             :             }
     645         [ +  + ]:          44 :             if (res->solvables_wallet_name.has_value()) {
     646   [ +  -  +  -  :          12 :                 r.pushKV("solvables_name", res->solvables_wallet_name.value());
                   +  - ]
     647                 :             :             }
     648   [ +  -  +  -  :          88 :             r.pushKV("backup_path", res->backup_path.utf8string());
             +  -  +  - ]
     649                 :             : 
     650                 :          44 :             return r;
     651                 :          72 :         },
     652   [ +  -  +  -  :        6699 :     };
             +  +  -  - ]
     653   [ +  -  +  -  :       13398 : }
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
     654                 :             : 
     655                 :         939 : RPCMethod gethdkeys()
     656                 :             : {
     657                 :         939 :     return RPCMethod{
     658                 :         939 :         "gethdkeys",
     659         [ +  - ]:        1878 :         "List all BIP 32 HD keys in the wallet and which descriptors use them.\n",
     660                 :             :         {
     661   [ +  -  +  - ]:        1878 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
     662   [ +  -  +  -  :        2817 :                 {"active_only", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show the keys for only active descriptors"},
                   +  - ]
     663   [ +  -  +  -  :        2817 :                 {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private keys"}
                   +  - ]
     664                 :             :             }},
     665                 :             :         },
     666   [ +  -  +  -  :        3756 :         RPCResult{RPCResult::Type::ARR, "", "", {
                   +  - ]
     667                 :             :             {
     668   [ +  -  +  - ]:        1878 :                 {RPCResult::Type::OBJ, "", "", {
     669   [ +  -  +  - ]:        1878 :                     {RPCResult::Type::STR, "xpub", "The extended public key"},
     670   [ +  -  +  - ]:        1878 :                     {RPCResult::Type::BOOL, "has_private", "Whether the wallet has the private key for this xpub"},
     671   [ +  -  +  - ]:        1878 :                     {RPCResult::Type::STR, "xprv", /*optional=*/true, "The extended private key if \"private\" is true"},
     672   [ +  -  +  - ]:        1878 :                     {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects that use this HD key",
     673                 :             :                     {
     674   [ +  -  +  - ]:        1878 :                         {RPCResult::Type::OBJ, "", "", {
     675   [ +  -  +  - ]:        1878 :                             {RPCResult::Type::STR, "desc", "Descriptor string public representation"},
     676   [ +  -  +  - ]:        1878 :                             {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"},
     677                 :             :                         }},
     678                 :             :                     }},
     679                 :             :                 }},
     680                 :             :             }
     681   [ +  -  +  -  :       19719 :         }},
          +  -  +  -  +  
          -  +  +  +  +  
          +  +  +  +  -  
          -  -  -  -  -  
                   -  - ]
     682                 :         939 :         RPCExamples{
     683   [ +  -  +  -  :        1878 :             HelpExampleCli("gethdkeys", "") + HelpExampleRpc("gethdkeys", "")
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     684   [ +  -  +  -  :        9390 :             + HelpExampleCliNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}}) + HelpExampleRpcNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}})
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     685         [ +  - ]:         939 :         },
     686                 :         939 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     687                 :             :         {
     688         [ -  + ]:          42 :             const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
     689         [ -  + ]:          42 :             if (!wallet) return UniValue::VNULL;
     690                 :             : 
     691         [ +  - ]:          42 :             LOCK(wallet->cs_wallet);
     692                 :             : 
     693   [ +  -  +  +  :          42 :             UniValue options{request.params[0].isNull() ? UniValue::VOBJ : request.params[0]};
             +  -  +  - ]
     694   [ +  -  +  +  :          92 :             const bool active_only{options.exists("active_only") ? options["active_only"].get_bool() : false};
          +  -  +  -  +  
                      - ]
     695   [ +  -  +  +  :          96 :             const bool priv{options.exists("private") ? options["private"].get_bool() : false};
          +  -  +  -  +  
                      - ]
     696         [ +  + ]:          42 :             if (priv) {
     697         [ +  + ]:          12 :                 EnsureWalletIsUnlocked(*wallet);
     698                 :             :             }
     699                 :             : 
     700         [ +  + ]:          41 :             std::map<CExtPubKey, std::set<std::tuple<std::string, bool, bool>>> wallet_xpubs;
     701                 :          41 :             std::map<CExtPubKey, CExtKey> wallet_xprvs;
     702   [ +  +  +  -  :         120 :             for (const auto& [xpub, spkms] : wallet->GetHDPubKeys(active_only ? HDKeyFilter::Active : HDKeyFilter::All)) {
                   +  + ]
     703         [ +  + ]:         326 :                 for (auto* desc_spkm : spkms) {
     704         [ +  - ]:         280 :                     LOCK(desc_spkm->cs_desc_man);
     705         [ +  - ]:         280 :                     std::string desc_str;
     706         [ +  - ]:         280 :                     bool ok = desc_spkm->GetDescriptorString(desc_str, /*priv=*/false);
     707         [ +  - ]:         280 :                     CHECK_NONFATAL(ok);
     708   [ +  -  +  -  :         280 :                     wallet_xpubs[xpub].emplace(desc_str, wallet->IsActiveScriptPubKeyMan(*desc_spkm), desc_spkm->HasPrivKey(xpub.pubkey.GetID()));
          +  -  +  -  +  
                      - ]
     709   [ +  +  +  -  :         280 :                     if (std::optional<CKey> key = priv ? desc_spkm->GetKey(xpub.pubkey.GetID()) : std::nullopt) {
             +  -  +  + ]
     710   [ +  -  +  - ]:          89 :                         wallet_xprvs[xpub] = CExtKey(xpub, *key);
     711                 :         280 :                     }
     712         [ +  - ]:         560 :                 }
     713                 :           0 :             }
     714                 :             : 
     715                 :          41 :             UniValue response(UniValue::VARR);
     716         [ +  + ]:          87 :             for (const auto& [xpub, descs] : wallet_xpubs) {
     717                 :          46 :                 bool has_xprv = false;
     718                 :          46 :                 UniValue descriptors(UniValue::VARR);
     719         [ +  + ]:         326 :                 for (const auto& [desc, active, has_priv] : descs) {
     720                 :         280 :                     UniValue d(UniValue::VOBJ);
     721   [ +  -  +  -  :         560 :                     d.pushKV("desc", desc);
                   +  - ]
     722   [ +  -  +  -  :         560 :                     d.pushKV("active", active);
                   +  - ]
     723                 :         280 :                     has_xprv |= has_priv;
     724                 :             : 
     725         [ +  - ]:         280 :                     descriptors.push_back(std::move(d));
     726                 :         280 :                 }
     727                 :          46 :                 UniValue xpub_info(UniValue::VOBJ);
     728   [ +  -  +  -  :          92 :                 xpub_info.pushKV("xpub", EncodeExtPubKey(xpub));
             +  -  +  - ]
     729   [ +  -  +  -  :          92 :                 xpub_info.pushKV("has_private", has_xprv);
                   +  - ]
     730   [ +  +  +  + ]:          46 :                 if (priv && has_xprv) {
     731   [ +  -  +  -  :          22 :                     xpub_info.pushKV("xprv", EncodeExtKey(wallet_xprvs.at(xpub)));
          +  -  +  -  +  
                      - ]
     732                 :             :                 }
     733   [ +  -  +  - ]:          92 :                 xpub_info.pushKV("descriptors", std::move(descriptors));
     734                 :             : 
     735         [ +  - ]:          46 :                 response.push_back(std::move(xpub_info));
     736                 :          46 :             }
     737                 :             : 
     738                 :          41 :             return response;
     739         [ +  - ]:         125 :         },
     740   [ +  -  +  -  :        8451 :     };
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     741   [ +  -  +  -  :       22536 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  -  -  
          -  -  -  -  -  
                      - ]
     742                 :             : 
     743                 :         911 : static RPCMethod createwalletdescriptor()
     744                 :             : {
     745                 :         911 :     return RPCMethod{"createwalletdescriptor",
     746                 :             :         "Creates the wallet's descriptor for the given address type. "
     747                 :             :         "The address type must be one that the wallet does not already have a descriptor for."
     748         [ +  - ]:        1822 :         + HELP_REQUIRING_PASSPHRASE,
     749                 :             :         {
     750   [ +  -  +  -  :        1822 :             {"type", RPCArg::Type::STR, RPCArg::Optional::NO, "The address type the descriptor will produce. Options are " + FormatAllOutputTypes() + "."},
                   +  - ]
     751   [ +  -  +  - ]:        1822 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
     752   [ +  -  +  -  :        2733 :                 {"internal", RPCArg::Type::BOOL, RPCArg::DefaultHint{"Both external and internal will be generated unless this parameter is specified"}, "Whether to only make one descriptor that is internal (if parameter is true) or external (if parameter is false)"},
                   +  - ]
     753   [ +  -  +  -  :        2733 :                 {"hdkey", RPCArg::Type::STR, RPCArg::DefaultHint{"The HD key used by all other active descriptors"}, "The HD key that the wallet knows the private key of, listed using 'gethdkeys', to use for this descriptor's key"},
                   +  - ]
     754                 :             :             }},
     755                 :             :         },
     756         [ +  - ]:        1822 :         RPCResult{
     757   [ +  -  +  - ]:        1822 :             RPCResult::Type::OBJ, "", "",
     758                 :             :             {
     759   [ +  -  +  - ]:        1822 :                 {RPCResult::Type::ARR, "descs", "The public descriptors that were added to the wallet",
     760   [ +  -  +  - ]:        1822 :                     {{RPCResult::Type::STR, "", ""}}
     761                 :             :                 }
     762                 :             :             },
     763   [ +  -  +  -  :        6377 :         },
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     764                 :         911 :         RPCExamples{
     765   [ +  -  +  -  :        1822 :             HelpExampleCli("createwalletdescriptor", "bech32m")
                   +  - ]
     766   [ +  -  +  -  :        3644 :             + HelpExampleRpc("createwalletdescriptor", R"("bech32m")")
             +  -  +  - ]
     767         [ +  - ]:         911 :         },
     768                 :         911 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     769                 :             :         {
     770                 :          14 :             std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     771         [ -  + ]:          14 :             if (!pwallet) return UniValue::VNULL;
     772                 :             : 
     773   [ +  -  +  -  :          14 :             std::optional<OutputType> output_type = ParseOutputType(request.params[0].get_str());
             -  +  +  - ]
     774         [ +  + ]:          14 :             if (!output_type) {
     775   [ +  -  +  -  :           2 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
             +  -  +  - ]
     776                 :             :             }
     777                 :             : 
     778   [ +  -  +  +  :          13 :             UniValue options{request.params[1].isNull() ? UniValue::VOBJ : request.params[1]};
             +  -  +  - ]
     779   [ +  -  +  -  :          13 :             UniValue internal_only{options["internal"]};
                   +  - ]
     780   [ +  -  +  -  :          13 :             UniValue hdkey{options["hdkey"]};
                   +  - ]
     781                 :             : 
     782                 :          13 :             std::vector<bool> internals;
     783         [ +  + ]:          13 :             if (internal_only.isNull()) {
     784         [ +  - ]:          11 :                 internals.push_back(false);
     785         [ +  - ]:          11 :                 internals.push_back(true);
     786                 :             :             } else {
     787   [ +  -  +  - ]:           2 :                 internals.push_back(internal_only.get_bool());
     788                 :             :             }
     789                 :             : 
     790         [ +  - ]:          13 :             LOCK(pwallet->cs_wallet);
     791         [ +  + ]:          13 :             EnsureWalletIsUnlocked(*pwallet);
     792                 :             : 
     793         [ +  + ]:          12 :             CExtPubKey xpub;
     794         [ +  + ]:          12 :             if (hdkey.isNull()) {
     795         [ +  - ]:           7 :                 HDPubKeyMap active_xpubs = pwallet->GetHDPubKeys(HDKeyFilter::Active);
     796         [ +  + ]:           7 :                 if (active_xpubs.size() != 1) {
     797   [ +  -  +  - ]:           4 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to determine which HD key to use from active descriptors. Please specify with 'hdkey'");
     798                 :             :                 }
     799                 :           5 :                 xpub = active_xpubs.begin()->first;
     800                 :           7 :             } else {
     801   [ +  -  -  +  :           5 :                 xpub = DecodeExtPubKey(hdkey.get_str());
                   +  - ]
     802         [ +  + ]:           5 :                 if (!xpub.pubkey.IsValid()) {
     803   [ +  -  +  - ]:           2 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to parse HD key. Please provide a valid xpub");
     804                 :             :                 }
     805                 :             :             }
     806                 :             : 
     807   [ +  -  +  - ]:           9 :             std::optional<CKey> key = pwallet->GetKey(xpub.pubkey.GetID());
     808         [ +  + ]:           9 :             if (!key) {
     809   [ +  -  +  -  :           2 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Private key for %s is not known", EncodeExtPubKey(xpub)));
                   +  - ]
     810                 :             :             }
     811         [ +  - ]:           8 :             CExtKey active_hdkey(xpub, *key);
     812                 :             : 
     813                 :           8 :             std::vector<std::reference_wrapper<DescriptorScriptPubKeyMan>> spkms;
     814         [ +  - ]:           8 :             WalletBatch batch{pwallet->GetDatabase()};
     815   [ +  -  -  +  :          44 :             for (bool internal : internals) {
                   -  + ]
     816         [ +  - ]:          14 :                 WalletDescriptor w_desc = GenerateWalletDescriptor(xpub, *output_type, internal);
     817   [ +  -  +  + ]:          14 :                 if (!pwallet->GetDescriptorScriptPubKeyMan(w_desc)) {
     818   [ +  -  +  - ]:          12 :                     spkms.emplace_back(pwallet->SetupDescriptorScriptPubKeyMan(batch, active_hdkey, *output_type, internal));
     819                 :             :                 }
     820                 :          14 :             }
     821         [ +  + ]:           8 :             if (spkms.empty()) {
     822   [ +  -  +  - ]:           2 :                 throw JSONRPCError(RPC_WALLET_ERROR, "Descriptor already exists");
     823                 :             :             }
     824                 :             : 
     825                 :             :             // Fetch each descspkm from the wallet in order to get the descriptor strings
     826                 :           7 :             UniValue descs{UniValue::VARR};
     827         [ +  + ]:          19 :             for (const auto& spkm : spkms) {
     828         [ +  - ]:          12 :                 std::string desc_str;
     829         [ +  - ]:          12 :                 bool ok = spkm.get().GetDescriptorString(desc_str, false);
     830         [ +  - ]:          12 :                 CHECK_NONFATAL(ok);
     831   [ +  -  +  - ]:          12 :                 descs.push_back(desc_str);
     832                 :          12 :             }
     833                 :           7 :             UniValue out{UniValue::VOBJ};
     834   [ +  -  +  - ]:          14 :             out.pushKV("descs", std::move(descs));
     835                 :           7 :             return out;
     836         [ +  - ]:          61 :         }
     837   [ +  -  +  -  :        9110 :     };
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     838   [ +  -  +  -  :       10932 : }
          +  -  +  -  +  
          -  +  -  -  -  
                   -  - ]
     839                 :             : 
     840                 :         910 : RPCMethod addhdkey()
     841                 :             : {
     842                 :         910 :     return RPCMethod{
     843                 :         910 :         "addhdkey",
     844         [ +  - ]:        1820 :         "Add a BIP 32 HD key to the wallet that can be used with 'createwalletdescriptor'\n",
     845                 :             :         {
     846   [ +  -  +  -  :        2730 :             {"hdkey", RPCArg::Type::STR, RPCArg::DefaultHint{"Automatically generated new key"}, "The BIP 32 extended private key to add. If none is provided, a randomly generated one will be added."},
                   +  - ]
     847                 :             :         },
     848         [ +  - ]:        1820 :         RPCResult{
     849   [ +  -  +  - ]:        1820 :             RPCResult::Type::OBJ, "", "",
     850                 :             :             {
     851   [ +  -  +  - ]:        1820 :                 {RPCResult::Type::STR, "xpub", "The xpub of the HD key that was added to the wallet"}
     852                 :             :             },
     853   [ +  -  +  -  :        3640 :         },
             +  +  -  - ]
     854                 :         910 :         RPCExamples{
     855   [ +  -  +  -  :        1820 :             HelpExampleCli("addhdkey", "xprv") + HelpExampleRpc("addhdkey", R"("xprv")")
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     856         [ +  - ]:         910 :         },
     857                 :         910 :         [&](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     858                 :             :         {
     859                 :          13 :             std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
     860         [ -  + ]:          13 :             if (!wallet) return UniValue::VNULL;
     861                 :             : 
     862   [ +  -  +  + ]:          13 :             if (wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     863   [ +  -  +  - ]:           2 :                 throw JSONRPCError(RPC_WALLET_ERROR, "addhdkey is not available for wallets without private keys");
     864                 :             :             }
     865                 :             : 
     866         [ +  + ]:          12 :             EnsureWalletIsUnlocked(*wallet);
     867                 :             : 
     868                 :          11 :             std::optional<CExtKey> hdkey;
     869   [ +  -  +  + ]:          11 :             if (!request.params[0].isNull()) {
     870   [ +  -  +  -  :           4 :                 hdkey = DecodeExtKey(request.params[0].get_str());
             -  +  +  - ]
     871         [ +  + ]:           4 :                 if (!hdkey->key.IsValid()) {
     872                 :             :                     // Check if the user gave us an xpub and give a more descriptive error if so
     873   [ +  -  +  -  :           2 :                     CExtPubKey xpub = DecodeExtPubKey(request.params[0].get_str());
             -  +  +  - ]
     874         [ +  + ]:           2 :                     if (xpub.pubkey.IsValid()) {
     875   [ +  -  +  - ]:           2 :                         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Extended public key (xpub) provided, but extended private key (xprv) is required");
     876                 :             :                     } else {
     877   [ +  -  +  - ]:           2 :                         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Could not parse HD key");
     878                 :             :                     }
     879                 :           2 :                 }
     880                 :             :             }
     881                 :             : 
     882         [ +  - ]:           9 :             auto res = wallet->AddHDKey(hdkey);
     883         [ +  + ]:           9 :             if (!res) {
     884         [ -  + ]:           1 :                 if (res.error().code == wallet::WalletErrorCode::UnlockNeeded) {
     885         [ #  # ]:           0 :                     throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, res.error().message.original);
     886                 :             :                 }
     887         [ +  - ]:           1 :                 throw JSONRPCError(RPC_WALLET_ERROR, res.error().message.original);
     888                 :             :             }
     889                 :             : 
     890                 :           8 :             UniValue response(UniValue::VOBJ);
     891   [ +  -  +  -  :          16 :             response.pushKV("xpub", EncodeExtPubKey(*res));
             +  -  +  - ]
     892                 :           8 :             return response;
     893                 :          20 :         },
     894   [ +  -  +  -  :        4550 :     };
             +  +  -  - ]
     895   [ +  -  +  - ]:        4550 : }
     896                 :             : 
     897                 :         909 : static RPCMethod exportwatchonlywallet()
     898                 :             : {
     899                 :         909 :     return RPCMethod{"exportwatchonlywallet",
     900         [ +  - ]:        1818 :         "Creates a wallet file at the specified destination containing a watchonly version "
     901                 :             :         "of the current wallet. This watchonly wallet contains the wallet's public descriptors, "
     902                 :             :         "its transactions, and address book data. Descriptors that use hardened derivation will "
     903                 :             :         "only have a limited number of derived keys included in the export due to hardened "
     904                 :             :         "derivation requiring private keys. Descriptors with unhardened derivation do not have "
     905                 :             :         "this limitation. The watchonly wallet can be imported into another node using 'restorewallet'.",
     906                 :             :         {
     907   [ +  -  +  - ]:        1818 :             {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The path to the filename the exported watchonly wallet will be saved to"},
     908                 :             :         },
     909         [ +  - ]:        1818 :         RPCResult{
     910   [ +  -  +  - ]:        1818 :             RPCResult::Type::OBJ, "", "",
     911                 :             :             {
     912   [ +  -  +  - ]:        1818 :                 {RPCResult::Type::STR, "exported_file", "The full path that the file has been exported to"},
     913                 :             :             },
     914   [ +  -  +  -  :        3636 :         },
             +  +  -  - ]
     915                 :         909 :         RPCExamples{
     916   [ +  -  +  -  :        1818 :             HelpExampleCli("exportwatchonlywallet", "\"/path/to/export.dat\"")
                   +  - ]
     917   [ +  -  +  -  :        3636 :             + HelpExampleRpc("exportwatchonlywallet", "\"/path/to/export.dat\"")
             +  -  +  - ]
     918         [ +  - ]:         909 :         },
     919                 :         909 :         [&](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     920                 :             :         {
     921                 :          12 :             std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     922         [ -  + ]:          12 :             if (!pwallet) return UniValue::VNULL;
     923         [ +  - ]:          12 :             WalletContext& context = EnsureWalletContext(request.context);
     924                 :             : 
     925   [ +  -  +  -  :          12 :             std::string dest = request.params[0].get_str();
                   -  + ]
     926                 :             : 
     927         [ +  - ]:          12 :             LOCK(pwallet->cs_wallet);
     928         [ +  - ]:          12 :             pwallet->TopUpKeyPool();
     929   [ +  -  +  - ]:          12 :             util::Result<std::string> exported = ExportWatchOnlyWallet(*pwallet, fs::PathFromString(dest), context);
     930         [ +  + ]:          12 :             if (!exported) {
     931   [ +  -  +  - ]:          10 :                 throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(exported).original);
     932                 :             :             }
     933                 :           7 :             UniValue out{UniValue::VOBJ};
     934   [ +  -  +  -  :          14 :             out.pushKV("exported_file", *exported);
                   +  - ]
     935                 :           7 :             return out;
     936         [ +  - ]:          36 :         }
     937   [ +  -  +  -  :        4545 :     };
             +  +  -  - ]
     938   [ +  -  +  - ]:        3636 : }
     939                 :             : 
     940                 :         928 : RPCMethod derivehdkey()
     941                 :             : {
     942                 :         928 :     return RPCMethod{
     943                 :         928 :         "derivehdkey",
     944                 :             :         "Derive extended public or private key from HD key in the wallet at a given path.\n"
     945                 :             :         "Derivation uses wallet private key material.\n"
     946         [ +  - ]:        1856 :         + HELP_REQUIRING_PASSPHRASE,
     947                 :             :         {
     948   [ +  -  +  - ]:        1856 :             {"path", RPCArg::Type::STR, RPCArg::Optional::NO, "BIP 32 derivation path with at least one hardened step."},
     949   [ +  -  +  - ]:        1856 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
     950   [ +  -  +  -  :        2784 :                 {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private key"},
                   +  - ]
     951   [ +  -  +  -  :        2784 :                 {"hdkey", RPCArg::Type::STR, RPCArg::DefaultHint{"Either the HD key of an unused(KEY) descriptor, or any other active descriptor."}, "The HD key that the wallet knows the private key of, listed using 'gethdkeys', to use for derivation"},
                   +  - ]
     952                 :             :             }},
     953                 :             :         },
     954         [ +  - ]:        1856 :         RPCResult{
     955   [ +  -  +  - ]:        1856 :             RPCResult::Type::OBJ, "", "", {
     956   [ +  -  +  - ]:        1856 :                 {RPCResult::Type::STR, "origin", "Fingerprint and path for use in descriptors"},
     957   [ +  -  +  - ]:        1856 :                 {RPCResult::Type::STR, "xpub", "The extended public key"},
     958   [ +  -  +  - ]:        1856 :                 {RPCResult::Type::STR, "xprv", /*optional=*/true, "The extended private key if \"private\" is true"},
     959                 :             :             },
     960   [ +  -  +  -  :        7424 :         },
             +  +  -  - ]
     961                 :         928 :         RPCExamples{
     962   [ +  -  +  -  :        1856 :             HelpExampleCli("derivehdkey", "m/87h/0h/0h") + HelpExampleRpc("derivehdkey", "\"m/87h/0h/0h\"")
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     963   [ +  -  +  -  :        5568 :             + HelpExampleCliNamed("derivehdkey", {{"path", "m/87h/0h/0h"}, {"private", "true"}})
          +  -  +  -  +  
                +  -  - ]
     964   [ +  -  +  -  :        5568 :             + HelpExampleRpcNamed("derivehdkey", {{"path", "m/87h/0h/0h"}, {"private", "true"}})
          +  -  +  -  +  
                +  -  - ]
     965         [ +  - ]:         928 :         },
     966                 :         928 :         [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
     967                 :             :         {
     968         [ -  + ]:          31 :             const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
     969         [ -  + ]:          31 :             if (!wallet) return UniValue::VNULL;
     970                 :             : 
     971   [ +  -  +  + ]:          31 :             if (wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     972                 :             :                 // Watch-only wallets can't contain unused(KEY) descriptors
     973   [ +  -  +  - ]:           2 :                 throw JSONRPCError(RPC_WALLET_ERROR, "derivehdkey is not available for watch-only wallets");
     974                 :             :             }
     975                 :             : 
     976   [ +  -  +  -  :          30 :             std::vector<uint32_t> path = ParsePathBIP32(request.params[0].get_str());
                   +  + ]
     977   [ +  -  +  +  :          27 :             UniValue options{request.params[1].isNull() ? UniValue::VOBJ : request.params[1]};
             +  -  +  - ]
     978   [ +  -  +  +  :          57 :             const bool priv{options.exists("private") ? options["private"].get_bool() : false};
          +  -  +  -  +  
                      - ]
     979   [ +  -  +  -  :          27 :             UniValue hdkey{options["hdkey"]};
                   +  - ]
     980   [ -  +  +  -  :          27 :             if (!HasHardenedDerivation(path)) {
                   +  + ]
     981   [ +  -  +  - ]:           4 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Derivation path requires at least one hardened step");
     982                 :             :             }
     983                 :             : 
     984         [ +  - ]:          25 :             LOCK(wallet->cs_wallet);
     985                 :             : 
     986                 :             :             // The RPC requires a hardened derivation step, so always unlock
     987                 :             :             // the wallet.
     988         [ +  + ]:          25 :             EnsureWalletIsUnlocked(*wallet);
     989                 :             : 
     990         [ +  + ]:          23 :             CExtPubKey xpub;
     991         [ +  + ]:          23 :             if (!hdkey.isNull()) {
     992   [ +  -  -  +  :           7 :                 xpub = DecodeExtPubKey(hdkey.get_str());
                   +  - ]
     993         [ +  + ]:           7 :                 if (!xpub.pubkey.IsValid()) {
     994   [ +  -  +  - ]:           2 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to parse HD key. Please provide a valid xpub");
     995                 :             :                 }
     996                 :             : 
     997                 :             :                 // Accept an xpub from an active or unused(KEY) descriptor, but
     998                 :             :                 // not from a (used) inactive one.
     999         [ +  - ]:           6 :                 std::set<CExtPubKey> xpub_candidates;
    1000   [ +  -  +  + ]:          11 :                 for (const auto& candidate : wallet->GetHDPubKeys(HDKeyFilter::UnusedKey)) {
    1001         [ +  - ]:           5 :                     xpub_candidates.insert(candidate.first);
    1002                 :           0 :                 }
    1003   [ +  -  +  + ]:           9 :                 for (const auto& candidate : wallet->GetHDPubKeys(HDKeyFilter::Active)) {
    1004         [ +  - ]:           3 :                     xpub_candidates.insert(candidate.first);
    1005                 :           0 :                 }
    1006         [ +  + ]:           6 :                 if (!xpub_candidates.contains(xpub)) {
    1007   [ +  -  +  - ]:           2 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "HD key is not used by an active or unused(KEY) descriptor");
    1008                 :             :                 }
    1009                 :           6 :             }
    1010                 :             : 
    1011                 :             :             // If hdkey was not specified, try to look it up. First consider
    1012                 :             :             // unused(KEY) descriptors. Otherwise look for active descriptors.
    1013         [ +  + ]:          21 :             if (hdkey.isNull()) {
    1014         [ +  - ]:          16 :                 HDPubKeyMap wallet_xpubs{wallet->GetHDPubKeys(HDKeyFilter::UnusedKey)};
    1015                 :             : 
    1016         [ +  + ]:          16 :                 if (wallet_xpubs.size() > 1) {
    1017   [ +  -  +  - ]:           2 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to determine which HD key to use. Please specify with 'hdkey'");
    1018         [ +  + ]:          15 :                 } else if (wallet_xpubs.size() == 1) {
    1019                 :           9 :                     xpub = wallet_xpubs.begin()->first;
    1020                 :             :                 } else {
    1021         [ +  - ]:           6 :                     HDPubKeyMap active_xpubs = wallet->GetHDPubKeys(HDKeyFilter::Active);
    1022         [ +  + ]:           6 :                     if (active_xpubs.empty()) {
    1023   [ +  -  +  - ]:           4 :                         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No active or unused(KEY) descriptor found");
    1024                 :             :                     }
    1025                 :             : 
    1026         [ -  + ]:           4 :                     if (active_xpubs.size() > 1) {
    1027   [ #  #  #  # ]:           0 :                         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to determine which HD key to use from active descriptors. Please specify with 'hdkey'");
    1028                 :             :                     }
    1029                 :             : 
    1030                 :           4 :                     xpub = active_xpubs.begin()->first;
    1031                 :           6 :                 }
    1032                 :          16 :             }
    1033                 :             : 
    1034         [ +  - ]:          18 :             std::optional<CExtKey> xprv{wallet->GetExtKey(xpub)};
    1035         [ -  + ]:          18 :             if (!xprv) {
    1036   [ #  #  #  #  :           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Private key for %s is not known", EncodeExtPubKey(xpub)));
                   #  # ]
    1037                 :             :             }
    1038                 :             : 
    1039         [ +  - ]:          18 :             std::optional<std::pair<CExtKey, KeyOriginInfo>> child{DeriveExtKey(*xprv, path)};
    1040         [ +  + ]:          18 :             if (!child) {
    1041   [ +  -  +  - ]:           2 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Unable to derive HD key at the requested path");
    1042                 :             :             }
    1043                 :             : 
    1044                 :          17 :             UniValue res{UniValue::VOBJ};
    1045                 :             : 
    1046         [ +  - ]:          17 :             const std::string fingerprint{HexStr(child->second.fingerprint)};
    1047                 :             : 
    1048   [ +  -  +  -  :          34 :             res.pushKV("origin", strprintf("[%s%s]", fingerprint, FormatHDKeypath(child->second.path)));
          +  -  +  -  +  
                      - ]
    1049   [ +  -  +  -  :          34 :             res.pushKV("xpub", EncodeExtPubKey(child->first.Neuter()));
          +  -  +  -  +  
                      - ]
    1050         [ +  + ]:          17 :             if (priv) {
    1051   [ +  -  +  -  :           4 :                 res.pushKV("xprv", EncodeExtKey(child->first));
             +  -  +  - ]
    1052                 :             :             }
    1053                 :          17 :             return res;
    1054   [ +  -  +  - ]:         106 :         },
    1055   [ +  -  +  -  :        9280 :     };
          +  -  +  +  +  
             +  -  -  -  
                      - ]
    1056   [ +  -  +  -  :       14848 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          -  -  -  -  -  
                -  -  - ]
    1057                 :             : 
    1058                 :             : // addresses
    1059                 :             : RPCMethod getaddressinfo();
    1060                 :             : RPCMethod getnewaddress();
    1061                 :             : RPCMethod getrawchangeaddress();
    1062                 :             : RPCMethod setlabel();
    1063                 :             : RPCMethod listaddressgroupings();
    1064                 :             : RPCMethod keypoolrefill();
    1065                 :             : RPCMethod getaddressesbylabel();
    1066                 :             : RPCMethod listlabels();
    1067                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
    1068                 :             : RPCMethod walletdisplayaddress();
    1069                 :             : #endif // ENABLE_EXTERNAL_SIGNER
    1070                 :             : 
    1071                 :             : // backup
    1072                 :             : RPCMethod importprunedfunds();
    1073                 :             : RPCMethod importdescriptors();
    1074                 :             : RPCMethod listdescriptors();
    1075                 :             : RPCMethod backupwallet();
    1076                 :             : RPCMethod restorewallet();
    1077                 :             : 
    1078                 :             : // coins
    1079                 :             : RPCMethod getreceivedbyaddress();
    1080                 :             : RPCMethod getreceivedbylabel();
    1081                 :             : RPCMethod getbalance();
    1082                 :             : RPCMethod lockunspent();
    1083                 :             : RPCMethod listlockunspent();
    1084                 :             : RPCMethod getbalances();
    1085                 :             : RPCMethod listunspent();
    1086                 :             : 
    1087                 :             : // encryption
    1088                 :             : RPCMethod walletpassphrase();
    1089                 :             : RPCMethod walletpassphrasechange();
    1090                 :             : RPCMethod walletlock();
    1091                 :             : RPCMethod encryptwallet();
    1092                 :             : 
    1093                 :             : // spend
    1094                 :             : RPCMethod sendtoaddress();
    1095                 :             : RPCMethod sendmany();
    1096                 :             : RPCMethod fundrawtransaction();
    1097                 :             : RPCMethod bumpfee();
    1098                 :             : RPCMethod psbtbumpfee();
    1099                 :             : RPCMethod send();
    1100                 :             : RPCMethod sendall();
    1101                 :             : RPCMethod walletprocesspsbt();
    1102                 :             : RPCMethod walletcreatefundedpsbt();
    1103                 :             : RPCMethod signrawtransactionwithwallet();
    1104                 :             : 
    1105                 :             : // signmessage
    1106                 :             : RPCMethod signmessage();
    1107                 :             : 
    1108                 :             : // transactions
    1109                 :             : RPCMethod listreceivedbyaddress();
    1110                 :             : RPCMethod listreceivedbylabel();
    1111                 :             : RPCMethod listtransactions();
    1112                 :             : RPCMethod listrawtransactions();
    1113                 :             : RPCMethod listsinceblock();
    1114                 :             : RPCMethod gettransaction();
    1115                 :             : RPCMethod abandontransaction();
    1116                 :             : RPCMethod rescanblockchain();
    1117                 :             : RPCMethod abortrescan();
    1118                 :             : 
    1119                 :         458 : std::span<const CRPCCommand> GetWalletRPCCommands()
    1120                 :             : {
    1121                 :         458 :     static const CRPCCommand commands[]{
    1122         [ +  - ]:         892 :         {"rawtransactions", &fundrawtransaction},
    1123         [ +  - ]:         892 :         {"wallet", &abandontransaction},
    1124         [ +  - ]:         892 :         {"wallet", &abortrescan},
    1125         [ +  - ]:         892 :         {"wallet", &addhdkey},
    1126         [ +  - ]:         892 :         {"wallet", &backupwallet},
    1127         [ +  - ]:         892 :         {"wallet", &bumpfee},
    1128         [ +  - ]:         892 :         {"wallet", &psbtbumpfee},
    1129         [ +  - ]:         892 :         {"wallet", &createwallet},
    1130         [ +  - ]:         892 :         {"wallet", &createwalletdescriptor},
    1131         [ +  - ]:         892 :         {"wallet", &derivehdkey},
    1132         [ +  - ]:         892 :         {"wallet", &restorewallet},
    1133         [ +  - ]:         892 :         {"wallet", &encryptwallet},
    1134         [ +  - ]:         892 :         {"wallet", &exportwatchonlywallet},
    1135         [ +  - ]:         892 :         {"wallet", &getaddressesbylabel},
    1136         [ +  - ]:         892 :         {"wallet", &getaddressinfo},
    1137         [ +  - ]:         892 :         {"wallet", &getbalance},
    1138         [ +  - ]:         892 :         {"wallet", &gethdkeys},
    1139         [ +  - ]:         892 :         {"wallet", &getnewaddress},
    1140         [ +  - ]:         892 :         {"wallet", &getrawchangeaddress},
    1141         [ +  - ]:         892 :         {"wallet", &getreceivedbyaddress},
    1142         [ +  - ]:         892 :         {"wallet", &getreceivedbylabel},
    1143         [ +  - ]:         892 :         {"wallet", &gettransaction},
    1144         [ +  - ]:         892 :         {"wallet", &getbalances},
    1145         [ +  - ]:         892 :         {"wallet", &getwalletinfo},
    1146         [ +  - ]:         892 :         {"wallet", &importdescriptors},
    1147         [ +  - ]:         892 :         {"wallet", &importprunedfunds},
    1148         [ +  - ]:         892 :         {"wallet", &keypoolrefill},
    1149         [ +  - ]:         892 :         {"wallet", &listaddressgroupings},
    1150         [ +  - ]:         892 :         {"wallet", &listdescriptors},
    1151         [ +  - ]:         892 :         {"wallet", &listlabels},
    1152         [ +  - ]:         892 :         {"wallet", &listlockunspent},
    1153         [ +  - ]:         892 :         {"wallet", &listreceivedbyaddress},
    1154         [ +  - ]:         892 :         {"wallet", &listreceivedbylabel},
    1155         [ +  - ]:         892 :         {"wallet", &listsinceblock},
    1156         [ +  - ]:         892 :         {"wallet", &listtransactions},
    1157         [ +  - ]:         892 :         {"wallet", &listrawtransactions},
    1158         [ +  - ]:         892 :         {"wallet", &listunspent},
    1159         [ +  - ]:         892 :         {"wallet", &listwalletdir},
    1160         [ +  - ]:         892 :         {"wallet", &listwallets},
    1161         [ +  - ]:         892 :         {"wallet", &loadwallet},
    1162         [ +  - ]:         892 :         {"wallet", &lockunspent},
    1163         [ +  - ]:         892 :         {"wallet", &migratewallet},
    1164         [ +  - ]:         892 :         {"wallet", &rescanblockchain},
    1165         [ +  - ]:         892 :         {"wallet", &send},
    1166         [ +  - ]:         892 :         {"wallet", &sendmany},
    1167         [ +  - ]:         892 :         {"wallet", &sendtoaddress},
    1168         [ +  - ]:         892 :         {"wallet", &setlabel},
    1169         [ +  - ]:         892 :         {"wallet", &setwalletflag},
    1170         [ +  - ]:         892 :         {"wallet", &signmessage},
    1171         [ +  - ]:         892 :         {"wallet", &signrawtransactionwithwallet},
    1172         [ +  - ]:         892 :         {"wallet", &simulaterawtransaction},
    1173         [ +  - ]:         892 :         {"wallet", &sendall},
    1174         [ +  - ]:         892 :         {"wallet", &unloadwallet},
    1175         [ +  - ]:         892 :         {"wallet", &walletcreatefundedpsbt},
    1176                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
    1177         [ +  - ]:         892 :         {"wallet", &walletdisplayaddress},
    1178                 :             : #endif // ENABLE_EXTERNAL_SIGNER
    1179         [ +  - ]:         892 :         {"wallet", &walletlock},
    1180         [ +  - ]:         892 :         {"wallet", &walletpassphrase},
    1181         [ +  - ]:         892 :         {"wallet", &walletpassphrasechange},
    1182         [ +  - ]:         892 :         {"wallet", &walletprocesspsbt},
    1183   [ +  +  +  -  :       26772 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    1184                 :         458 :     return commands;
    1185                 :             : }
    1186                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1