LCOV - code coverage report
Current view: top level - src/wallet/rpc - wallet.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 27.9 % 592 165
Test Date: 2024-11-04 04:45:35 Functions: 50.0 % 28 14
Branches: 29.2 % 2902 847

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 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> // IWYU pragma: keep
       7                 :             : 
       8                 :             : #include <core_io.h>
       9                 :             : #include <key_io.h>
      10                 :             : #include <rpc/server.h>
      11                 :             : #include <rpc/util.h>
      12                 :             : #include <util/translation.h>
      13                 :             : #include <wallet/context.h>
      14                 :             : #include <wallet/receive.h>
      15                 :             : #include <wallet/rpc/wallet.h>
      16                 :             : #include <wallet/rpc/util.h>
      17                 :             : #include <wallet/wallet.h>
      18                 :             : #include <wallet/walletutil.h>
      19                 :             : 
      20                 :             : #include <optional>
      21                 :             : 
      22                 :             : #include <univalue.h>
      23                 :             : 
      24                 :             : 
      25                 :             : namespace wallet {
      26                 :             : 
      27                 :             : static const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS{
      28                 :             :     {WALLET_FLAG_AVOID_REUSE,
      29                 :             :      "You need to rescan the blockchain in order to correctly mark used "
      30                 :             :      "destinations in the past. Until this is done, some destinations may "
      31                 :             :      "be considered unused, even if the opposite is the case."},
      32                 :             : };
      33                 :             : 
      34                 :             : /** Checks if a CKey is in the given CWallet compressed or otherwise*/
      35                 :           0 : bool HaveKey(const SigningProvider& wallet, const CKey& key)
      36                 :             : {
      37                 :           0 :     CKey key2;
      38   [ #  #  #  #  :           0 :     key2.Set(key.begin(), key.end(), !key.IsCompressed());
                   #  # ]
      39   [ #  #  #  #  :           0 :     return wallet.HaveKey(key.GetPubKey().GetID()) || wallet.HaveKey(key2.GetPubKey().GetID());
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
      40                 :           0 : }
      41                 :             : 
      42                 :          10 : static RPCHelpMan getwalletinfo()
      43                 :             : {
      44                 :          10 :     return RPCHelpMan{"getwalletinfo",
      45                 :             :                 "Returns an object containing various wallet state info.\n",
      46                 :             :                 {},
      47                 :           0 :                 RPCResult{
      48                 :             :                     RPCResult::Type::OBJ, "", "",
      49                 :             :                     {
      50                 :             :                         {
      51                 :             :                         {RPCResult::Type::STR, "walletname", "the wallet name"},
      52                 :             :                         {RPCResult::Type::NUM, "walletversion", "the wallet version"},
      53                 :             :                         {RPCResult::Type::STR, "format", "the database format (bdb or sqlite)"},
      54                 :             :                         {RPCResult::Type::STR_AMOUNT, "balance", "DEPRECATED. Identical to getbalances().mine.trusted"},
      55                 :             :                         {RPCResult::Type::STR_AMOUNT, "unconfirmed_balance", "DEPRECATED. Identical to getbalances().mine.untrusted_pending"},
      56                 :             :                         {RPCResult::Type::STR_AMOUNT, "immature_balance", "DEPRECATED. Identical to getbalances().mine.immature"},
      57                 :             :                         {RPCResult::Type::NUM, "txcount", "the total number of transactions in the wallet"},
      58         [ +  - ]:          20 :                         {RPCResult::Type::NUM_TIME, "keypoololdest", /*optional=*/true, "the " + UNIX_EPOCH_TIME + " of the oldest pre-generated key in the key pool. Legacy wallets only."},
      59                 :             :                         {RPCResult::Type::NUM, "keypoolsize", "how many new keys are pre-generated (only counts external keys)"},
      60                 :             :                         {RPCResult::Type::NUM, "keypoolsize_hd_internal", /*optional=*/true, "how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)"},
      61         [ +  - ]:          20 :                         {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)"},
      62         [ +  - ]:          20 :                         {RPCResult::Type::STR_AMOUNT, "paytxfee", "the transaction fee configuration, set in " + CURRENCY_UNIT + "/kvB"},
      63                 :             :                         {RPCResult::Type::STR_HEX, "hdseedid", /*optional=*/true, "the Hash160 of the HD seed (only present when HD is enabled)"},
      64                 :             :                         {RPCResult::Type::BOOL, "private_keys_enabled", "false if privatekeys are disabled for this wallet (enforced watch-only wallet)"},
      65                 :             :                         {RPCResult::Type::BOOL, "avoid_reuse", "whether this wallet tracks clean/dirty coins in terms of reuse"},
      66                 :             :                         {RPCResult::Type::OBJ, "scanning", "current scanning details, or false if no scan is in progress",
      67                 :             :                         {
      68                 :             :                             {RPCResult::Type::NUM, "duration", "elapsed seconds since scan start"},
      69                 :             :                             {RPCResult::Type::NUM, "progress", "scanning progress percentage [0.0, 1.0]"},
      70                 :             :                         }, /*skip_type_check=*/true},
      71                 :             :                         {RPCResult::Type::BOOL, "descriptors", "whether this wallet uses descriptors for output script management"},
      72                 :             :                         {RPCResult::Type::BOOL, "external_signer", "whether this wallet is configured to use an external signer such as a hardware wallet"},
      73                 :             :                         {RPCResult::Type::BOOL, "blank", "Whether this wallet intentionally does not contain any keys, scripts, or descriptors"},
      74                 :             :                         {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."},
      75                 :             :                         RESULT_LAST_PROCESSED_BLOCK,
      76                 :             :                     }},
      77   [ +  -  +  -  :         330 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  +  +  +  -  
                -  -  - ]
      78                 :          10 :                 RPCExamples{
      79   [ +  -  +  -  :          20 :                     HelpExampleCli("getwalletinfo", "")
                   +  - ]
      80   [ +  -  +  -  :          40 :             + HelpExampleRpc("getwalletinfo", "")
             +  -  +  - ]
      81         [ +  - ]:          10 :                 },
      82                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
      83                 :             : {
      84         [ #  # ]:           0 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
      85         [ #  # ]:           0 :     if (!pwallet) return UniValue::VNULL;
      86                 :             : 
      87                 :             :     // Make sure the results are valid at least up to the most recent block
      88                 :             :     // the user could have gotten from another RPC command prior to now
      89         [ #  # ]:           0 :     pwallet->BlockUntilSyncedToCurrentChain();
      90                 :             : 
      91         [ #  # ]:           0 :     LOCK(pwallet->cs_wallet);
      92                 :             : 
      93                 :           0 :     UniValue obj(UniValue::VOBJ);
      94                 :             : 
      95         [ #  # ]:           0 :     size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
      96         [ #  # ]:           0 :     const auto bal = GetBalance(*pwallet);
      97   [ #  #  #  #  :           0 :     obj.pushKV("walletname", pwallet->GetName());
                   #  # ]
      98   [ #  #  #  #  :           0 :     obj.pushKV("walletversion", pwallet->GetVersion());
             #  #  #  # ]
      99   [ #  #  #  #  :           0 :     obj.pushKV("format", pwallet->GetDatabase().Format());
             #  #  #  # ]
     100   [ #  #  #  #  :           0 :     obj.pushKV("balance", ValueFromAmount(bal.m_mine_trusted));
                   #  # ]
     101   [ #  #  #  #  :           0 :     obj.pushKV("unconfirmed_balance", ValueFromAmount(bal.m_mine_untrusted_pending));
                   #  # ]
     102   [ #  #  #  #  :           0 :     obj.pushKV("immature_balance", ValueFromAmount(bal.m_mine_immature));
                   #  # ]
     103   [ #  #  #  #  :           0 :     obj.pushKV("txcount",       (int)pwallet->mapWallet.size());
                   #  # ]
     104         [ #  # ]:           0 :     const auto kp_oldest = pwallet->GetOldestKeyPoolTime();
     105         [ #  # ]:           0 :     if (kp_oldest.has_value()) {
     106   [ #  #  #  #  :           0 :         obj.pushKV("keypoololdest", kp_oldest.value());
                   #  # ]
     107                 :             :     }
     108   [ #  #  #  #  :           0 :     obj.pushKV("keypoolsize", (int64_t)kpExternalSize);
                   #  # ]
     109                 :             : 
     110         [ #  # ]:           0 :     LegacyScriptPubKeyMan* spk_man = pwallet->GetLegacyScriptPubKeyMan();
     111         [ #  # ]:           0 :     if (spk_man) {
     112                 :           0 :         CKeyID seed_id = spk_man->GetHDChain().seed_id;
     113         [ #  # ]:           0 :         if (!seed_id.IsNull()) {
     114   [ #  #  #  #  :           0 :             obj.pushKV("hdseedid", seed_id.GetHex());
             #  #  #  # ]
     115                 :             :         }
     116                 :             :     }
     117                 :             : 
     118   [ #  #  #  # ]:           0 :     if (pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) {
     119   [ #  #  #  #  :           0 :         obj.pushKV("keypoolsize_hd_internal",   (int64_t)(pwallet->GetKeyPoolSize() - kpExternalSize));
             #  #  #  # ]
     120                 :             :     }
     121   [ #  #  #  # ]:           0 :     if (pwallet->IsCrypted()) {
     122   [ #  #  #  #  :           0 :         obj.pushKV("unlocked_until", pwallet->nRelockTime);
                   #  # ]
     123                 :             :     }
     124   [ #  #  #  #  :           0 :     obj.pushKV("paytxfee", ValueFromAmount(pwallet->m_pay_tx_fee.GetFeePerK()));
                   #  # ]
     125   [ #  #  #  #  :           0 :     obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
             #  #  #  # ]
     126   [ #  #  #  #  :           0 :     obj.pushKV("avoid_reuse", pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE));
             #  #  #  # ]
     127         [ #  # ]:           0 :     if (pwallet->IsScanning()) {
     128                 :           0 :         UniValue scanning(UniValue::VOBJ);
     129   [ #  #  #  #  :           0 :         scanning.pushKV("duration", Ticks<std::chrono::seconds>(pwallet->ScanningDuration()));
                   #  # ]
     130   [ #  #  #  #  :           0 :         scanning.pushKV("progress", pwallet->ScanningProgress());
                   #  # ]
     131   [ #  #  #  # ]:           0 :         obj.pushKV("scanning", std::move(scanning));
     132                 :           0 :     } else {
     133   [ #  #  #  #  :           0 :         obj.pushKV("scanning", false);
                   #  # ]
     134                 :             :     }
     135   [ #  #  #  #  :           0 :     obj.pushKV("descriptors", pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
             #  #  #  # ]
     136   [ #  #  #  #  :           0 :     obj.pushKV("external_signer", pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER));
             #  #  #  # ]
     137   [ #  #  #  #  :           0 :     obj.pushKV("blank", pwallet->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
             #  #  #  # ]
     138         [ #  # ]:           0 :     if (int64_t birthtime = pwallet->GetBirthTime(); birthtime != UNKNOWN_TIME) {
     139   [ #  #  #  #  :           0 :         obj.pushKV("birthtime", birthtime);
                   #  # ]
     140                 :             :     }
     141                 :             : 
     142         [ #  # ]:           0 :     AppendLastProcessedBlock(obj, *pwallet);
     143                 :           0 :     return obj;
     144         [ #  # ]:           0 : },
     145   [ +  -  +  -  :          60 :     };
             +  -  +  - ]
     146   [ +  -  +  -  :         230 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
                -  -  - ]
     147                 :             : 
     148                 :          10 : static RPCHelpMan listwalletdir()
     149                 :             : {
     150                 :          10 :     return RPCHelpMan{"listwalletdir",
     151                 :             :                 "Returns a list of wallets in the wallet directory.\n",
     152                 :             :                 {},
     153                 :           0 :                 RPCResult{
     154                 :             :                     RPCResult::Type::OBJ, "", "",
     155                 :             :                     {
     156                 :             :                         {RPCResult::Type::ARR, "wallets", "",
     157                 :             :                         {
     158                 :             :                             {RPCResult::Type::OBJ, "", "",
     159                 :             :                             {
     160                 :             :                                 {RPCResult::Type::STR, "name", "The wallet name"},
     161                 :             :                             }},
     162                 :             :                         }},
     163                 :             :                     }
     164   [ +  -  +  -  :          70 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
          +  +  +  -  -  
             -  -  -  - ]
     165                 :          10 :                 RPCExamples{
     166   [ +  -  +  -  :          20 :                     HelpExampleCli("listwalletdir", "")
                   +  - ]
     167   [ +  -  +  -  :          40 :             + HelpExampleRpc("listwalletdir", "")
             +  -  +  - ]
     168         [ +  - ]:          10 :                 },
     169                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     170                 :             : {
     171                 :           0 :     UniValue wallets(UniValue::VARR);
     172   [ #  #  #  #  :           0 :     for (const auto& [path, _] : ListDatabases(GetWalletDir())) {
                   #  # ]
     173                 :           0 :         UniValue wallet(UniValue::VOBJ);
     174   [ #  #  #  #  :           0 :         wallet.pushKV("name", path.utf8string());
             #  #  #  # ]
     175         [ #  # ]:           0 :         wallets.push_back(std::move(wallet));
     176                 :           0 :     }
     177                 :             : 
     178                 :           0 :     UniValue result(UniValue::VOBJ);
     179   [ #  #  #  # ]:           0 :     result.pushKV("wallets", std::move(wallets));
     180                 :           0 :     return result;
     181                 :           0 : },
     182   [ +  -  +  -  :          60 :     };
             +  -  +  - ]
     183   [ +  -  +  -  :          40 : }
             +  -  +  - ]
     184                 :             : 
     185                 :          10 : static RPCHelpMan listwallets()
     186                 :             : {
     187                 :          10 :     return RPCHelpMan{"listwallets",
     188                 :             :                 "Returns a list of currently loaded wallets.\n"
     189                 :             :                 "For full information on the wallet, use \"getwalletinfo\"\n",
     190                 :             :                 {},
     191                 :           0 :                 RPCResult{
     192                 :             :                     RPCResult::Type::ARR, "", "",
     193                 :             :                     {
     194                 :             :                         {RPCResult::Type::STR, "walletname", "the wallet name"},
     195                 :             :                     }
     196   [ +  -  +  -  :          30 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
     197                 :          10 :                 RPCExamples{
     198   [ +  -  +  -  :          20 :                     HelpExampleCli("listwallets", "")
                   +  - ]
     199   [ +  -  +  -  :          40 :             + HelpExampleRpc("listwallets", "")
             +  -  +  - ]
     200         [ +  - ]:          10 :                 },
     201                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     202                 :             : {
     203                 :           0 :     UniValue obj(UniValue::VARR);
     204                 :             : 
     205         [ #  # ]:           0 :     WalletContext& context = EnsureWalletContext(request.context);
     206   [ #  #  #  # ]:           0 :     for (const std::shared_ptr<CWallet>& wallet : GetWallets(context)) {
     207         [ #  # ]:           0 :         LOCK(wallet->cs_wallet);
     208   [ #  #  #  #  :           0 :         obj.push_back(wallet->GetName());
                   #  # ]
     209                 :           0 :     }
     210                 :             : 
     211                 :           0 :     return obj;
     212                 :           0 : },
     213   [ +  -  +  -  :          60 :     };
             +  -  +  - ]
     214   [ +  -  +  - ]:          20 : }
     215                 :             : 
     216                 :          10 : static RPCHelpMan loadwallet()
     217                 :             : {
     218                 :          10 :     return RPCHelpMan{"loadwallet",
     219                 :             :                 "\nLoads a wallet from a wallet file or directory."
     220                 :             :                 "\nNote that all wallet command-line options used when starting bitcoind will be"
     221                 :             :                 "\napplied to the new wallet.\n",
     222                 :             :                 {
     223         [ +  - ]:          10 :                     {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet directory or .dat file."},
     224         [ +  - ]:          10 :                     {"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."},
     225                 :             :                 },
     226                 :           0 :                 RPCResult{
     227                 :             :                     RPCResult::Type::OBJ, "", "",
     228                 :             :                     {
     229                 :             :                         {RPCResult::Type::STR, "name", "The wallet name if loaded successfully."},
     230                 :             :                         {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to loading the wallet.",
     231                 :             :                         {
     232                 :             :                             {RPCResult::Type::STR, "", ""},
     233                 :             :                         }},
     234                 :             :                     }
     235   [ +  -  +  -  :          60 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     236                 :          10 :                 RPCExamples{
     237   [ +  -  +  -  :          20 :                     HelpExampleCli("loadwallet", "\"test.dat\"")
                   +  - ]
     238   [ +  -  +  -  :          40 :             + HelpExampleRpc("loadwallet", "\"test.dat\"")
             +  -  +  - ]
     239         [ +  - ]:          10 :                 },
     240                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     241                 :             : {
     242                 :           0 :     WalletContext& context = EnsureWalletContext(request.context);
     243                 :           0 :     const std::string name(request.params[0].get_str());
     244                 :             : 
     245         [ #  # ]:           0 :     DatabaseOptions options;
     246                 :           0 :     DatabaseStatus status;
     247         [ #  # ]:           0 :     ReadDatabaseArgs(*context.args, options);
     248                 :           0 :     options.require_existing = true;
     249         [ #  # ]:           0 :     bilingual_str error;
     250                 :           0 :     std::vector<bilingual_str> warnings;
     251   [ #  #  #  #  :           0 :     std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool());
             #  #  #  # ]
     252                 :             : 
     253                 :           0 :     {
     254         [ #  # ]:           0 :         LOCK(context.wallets_mutex);
     255   [ #  #  #  #  :           0 :         if (std::any_of(context.wallets.begin(), context.wallets.end(), [&name](const auto& wallet) { return wallet->GetName() == name; })) {
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     256   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded.");
     257                 :             :         }
     258                 :           0 :     }
     259                 :             : 
     260         [ #  # ]:           0 :     std::shared_ptr<CWallet> const wallet = LoadWallet(context, name, load_on_start, options, status, error, warnings);
     261                 :             : 
     262   [ #  #  #  # ]:           0 :     HandleWalletError(wallet, status, error);
     263                 :             : 
     264                 :           0 :     UniValue obj(UniValue::VOBJ);
     265   [ #  #  #  #  :           0 :     obj.pushKV("name", wallet->GetName());
                   #  # ]
     266         [ #  # ]:           0 :     PushWarnings(warnings, obj);
     267                 :             : 
     268         [ #  # ]:           0 :     return obj;
     269                 :           0 : },
     270   [ +  -  +  -  :         120 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     271   [ +  -  +  -  :          90 : }
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
     272                 :             : 
     273                 :          10 : static RPCHelpMan setwalletflag()
     274                 :             : {
     275                 :          10 :             std::string flags;
     276         [ +  + ]:          80 :             for (auto& it : WALLET_FLAG_MAP)
     277         [ +  + ]:          70 :                 if (it.second & MUTABLE_WALLET_FLAGS)
     278   [ -  +  +  - ]:          20 :                     flags += (flags == "" ? "" : ", ") + it.first;
     279                 :             : 
     280         [ +  - ]:          10 :     return RPCHelpMan{"setwalletflag",
     281                 :             :                 "\nChange the state of the given wallet flag for a wallet.\n",
     282                 :             :                 {
     283         [ +  - ]:          20 :                     {"flag", RPCArg::Type::STR, RPCArg::Optional::NO, "The name of the flag to change. Current available flags: " + flags},
     284         [ +  - ]:          20 :                     {"value", RPCArg::Type::BOOL, RPCArg::Default{true}, "The new state."},
     285                 :             :                 },
     286                 :           0 :                 RPCResult{
     287                 :             :                     RPCResult::Type::OBJ, "", "",
     288                 :             :                     {
     289                 :             :                         {RPCResult::Type::STR, "flag_name", "The name of the flag that was modified"},
     290                 :             :                         {RPCResult::Type::BOOL, "flag_state", "The new state of the flag"},
     291                 :             :                         {RPCResult::Type::STR, "warnings", /*optional=*/true, "Any warnings associated with the change"},
     292                 :             :                     }
     293   [ +  -  +  -  :          50 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     294                 :          10 :                 RPCExamples{
     295   [ +  -  +  -  :          20 :                     HelpExampleCli("setwalletflag", "avoid_reuse")
                   +  - ]
     296   [ +  -  +  -  :          40 :                   + HelpExampleRpc("setwalletflag", "\"avoid_reuse\"")
             +  -  +  - ]
     297         [ +  - ]:          10 :                 },
     298                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     299                 :             : {
     300                 :           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     301         [ #  # ]:           0 :     if (!pwallet) return UniValue::VNULL;
     302                 :             : 
     303   [ #  #  #  #  :           0 :     std::string flag_str = request.params[0].get_str();
                   #  # ]
     304   [ #  #  #  #  :           0 :     bool value = request.params[1].isNull() || request.params[1].get_bool();
          #  #  #  #  #  
                      # ]
     305                 :             : 
     306         [ #  # ]:           0 :     if (!WALLET_FLAG_MAP.count(flag_str)) {
     307   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unknown wallet flag: %s", flag_str));
     308                 :             :     }
     309                 :             : 
     310         [ #  # ]:           0 :     auto flag = WALLET_FLAG_MAP.at(flag_str);
     311                 :             : 
     312         [ #  # ]:           0 :     if (!(flag & MUTABLE_WALLET_FLAGS)) {
     313   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is immutable: %s", flag_str));
     314                 :             :     }
     315                 :             : 
     316                 :           0 :     UniValue res(UniValue::VOBJ);
     317                 :             : 
     318   [ #  #  #  # ]:           0 :     if (pwallet->IsWalletFlagSet(flag) == value) {
     319   [ #  #  #  #  :           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is already set to %s: %s", value ? "true" : "false", flag_str));
                   #  # ]
     320                 :             :     }
     321                 :             : 
     322   [ #  #  #  #  :           0 :     res.pushKV("flag_name", flag_str);
                   #  # ]
     323   [ #  #  #  #  :           0 :     res.pushKV("flag_state", value);
                   #  # ]
     324                 :             : 
     325         [ #  # ]:           0 :     if (value) {
     326         [ #  # ]:           0 :         pwallet->SetWalletFlag(flag);
     327                 :             :     } else {
     328         [ #  # ]:           0 :         pwallet->UnsetWalletFlag(flag);
     329                 :             :     }
     330                 :             : 
     331   [ #  #  #  #  :           0 :     if (flag && value && WALLET_FLAG_CAVEATS.count(flag)) {
                   #  # ]
     332   [ #  #  #  #  :           0 :         res.pushKV("warnings", WALLET_FLAG_CAVEATS.at(flag));
             #  #  #  # ]
     333                 :             :     }
     334                 :             : 
     335                 :           0 :     return res;
     336                 :           0 : },
     337   [ +  -  +  -  :         140 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                +  -  - ]
     338   [ +  -  +  -  :         100 : }
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
     339                 :             : 
     340                 :          10 : static RPCHelpMan createwallet()
     341                 :             : {
     342                 :          10 :     return RPCHelpMan{
     343                 :             :         "createwallet",
     344                 :             :         "\nCreates and loads a new wallet.\n",
     345                 :             :         {
     346         [ +  - ]:          10 :             {"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."},
     347         [ +  - ]:          20 :             {"disable_private_keys", RPCArg::Type::BOOL, RPCArg::Default{false}, "Disable the possibility of private keys (only watchonlys are possible in this mode)."},
     348         [ +  - ]:          20 :             {"blank", RPCArg::Type::BOOL, RPCArg::Default{false}, "Create a blank wallet. A blank wallet has no keys or HD seed. One can be set using sethdseed."},
     349         [ +  - ]:          10 :             {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Encrypt the wallet with this passphrase."},
     350         [ +  - ]:          20 :             {"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."},
     351         [ +  - ]:          20 :             {"descriptors", RPCArg::Type::BOOL, RPCArg::Default{true}, "Create a native descriptor wallet. The wallet will use descriptors internally to handle address creation."
     352                 :             :                                                                        " Setting to \"false\" will create a legacy wallet; This is only possible with the -deprecatedrpc=create_bdb setting because, the legacy wallet type is being deprecated and"
     353                 :             :                                                                        " support for creating and opening legacy wallets will be removed in the future."},
     354         [ +  - ]:          10 :             {"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."},
     355         [ +  - ]:          20 :             {"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."},
     356                 :             :         },
     357                 :           0 :         RPCResult{
     358                 :             :             RPCResult::Type::OBJ, "", "",
     359                 :             :             {
     360                 :             :                 {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."},
     361                 :             :                 {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to creating and loading the wallet.",
     362                 :             :                 {
     363                 :             :                     {RPCResult::Type::STR, "", ""},
     364                 :             :                 }},
     365                 :             :             }
     366   [ +  -  +  -  :          60 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     367                 :          10 :         RPCExamples{
     368   [ +  -  +  -  :          20 :             HelpExampleCli("createwallet", "\"testwallet\"")
                   +  - ]
     369   [ +  -  +  -  :          40 :             + HelpExampleRpc("createwallet", "\"testwallet\"")
             +  -  +  - ]
     370   [ +  -  +  -  :          80 :             + HelpExampleCliNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"descriptors", true}, {"load_on_startup", true}})
          +  -  +  -  +  
                +  -  - ]
     371   [ +  -  +  -  :          80 :             + HelpExampleRpcNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"descriptors", true}, {"load_on_startup", true}})
          +  -  +  -  +  
                +  -  - ]
     372         [ +  - ]:          10 :         },
     373                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     374                 :             : {
     375                 :           0 :     WalletContext& context = EnsureWalletContext(request.context);
     376                 :           0 :     uint64_t flags = 0;
     377   [ #  #  #  # ]:           0 :     if (!request.params[1].isNull() && request.params[1].get_bool()) {
     378                 :             :         flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS;
     379                 :             :     }
     380                 :             : 
     381   [ #  #  #  # ]:           0 :     if (!request.params[2].isNull() && request.params[2].get_bool()) {
     382                 :           0 :         flags |= WALLET_FLAG_BLANK_WALLET;
     383                 :             :     }
     384         [ #  # ]:           0 :     SecureString passphrase;
     385         [ #  # ]:           0 :     passphrase.reserve(100);
     386                 :           0 :     std::vector<bilingual_str> warnings;
     387   [ #  #  #  # ]:           0 :     if (!request.params[3].isNull()) {
     388   [ #  #  #  #  :           0 :         passphrase = std::string_view{request.params[3].get_str()};
                   #  # ]
     389         [ #  # ]:           0 :         if (passphrase.empty()) {
     390                 :             :             // Empty string means unencrypted
     391   [ #  #  #  #  :           0 :             warnings.emplace_back(Untranslated("Empty string given as passphrase, wallet will not be encrypted."));
                   #  # ]
     392                 :             :         }
     393                 :             :     }
     394                 :             : 
     395   [ #  #  #  #  :           0 :     if (!request.params[4].isNull() && request.params[4].get_bool()) {
          #  #  #  #  #  
                      # ]
     396                 :           0 :         flags |= WALLET_FLAG_AVOID_REUSE;
     397                 :             :     }
     398   [ #  #  #  # ]:           0 :     if (self.Arg<bool>("descriptors")) {
     399                 :             : #ifndef USE_SQLITE
     400                 :             :         throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without sqlite support (required for descriptor wallets)");
     401                 :             : #endif
     402                 :           0 :         flags |= WALLET_FLAG_DESCRIPTORS;
     403                 :             :     } else {
     404   [ #  #  #  #  :           0 :         if (!context.chain->rpcEnableDeprecated("create_bdb")) {
                   #  # ]
     405         [ #  # ]:           0 :             throw JSONRPCError(RPC_WALLET_ERROR, "BDB wallet creation is deprecated and will be removed in a future release."
     406   [ #  #  #  # ]:           0 :                                                  " In this release it can be re-enabled temporarily with the -deprecatedrpc=create_bdb setting.");
     407                 :             :         }
     408                 :             :     }
     409   [ #  #  #  #  :           0 :     if (!request.params[7].isNull() && request.params[7].get_bool()) {
          #  #  #  #  #  
                      # ]
     410                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
     411                 :           0 :         flags |= WALLET_FLAG_EXTERNAL_SIGNER;
     412                 :             : #else
     413                 :             :         throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without external signing support (required for external signing)");
     414                 :             : #endif
     415                 :             :     }
     416                 :             : 
     417                 :             : #ifndef USE_BDB
     418         [ #  # ]:           0 :     if (!(flags & WALLET_FLAG_DESCRIPTORS)) {
     419   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without bdb support (required for legacy wallets)");
     420                 :             :     }
     421                 :             : #endif
     422                 :             : 
     423         [ #  # ]:           0 :     DatabaseOptions options;
     424                 :           0 :     DatabaseStatus status;
     425         [ #  # ]:           0 :     ReadDatabaseArgs(*context.args, options);
     426                 :           0 :     options.require_create = true;
     427                 :           0 :     options.create_flags = flags;
     428         [ #  # ]:           0 :     options.create_passphrase = passphrase;
     429         [ #  # ]:           0 :     bilingual_str error;
     430   [ #  #  #  #  :           0 :     std::optional<bool> load_on_start = request.params[6].isNull() ? std::nullopt : std::optional<bool>(request.params[6].get_bool());
             #  #  #  # ]
     431   [ #  #  #  #  :           0 :     const std::shared_ptr<CWallet> wallet = CreateWallet(context, request.params[0].get_str(), load_on_start, options, status, error, warnings);
                   #  # ]
     432         [ #  # ]:           0 :     if (!wallet) {
     433         [ #  # ]:           0 :         RPCErrorCode code = status == DatabaseStatus::FAILED_ENCRYPT ? RPC_WALLET_ENCRYPTION_FAILED : RPC_WALLET_ERROR;
     434         [ #  # ]:           0 :         throw JSONRPCError(code, error.original);
     435                 :             :     }
     436                 :             : 
     437                 :           0 :     UniValue obj(UniValue::VOBJ);
     438   [ #  #  #  #  :           0 :     obj.pushKV("name", wallet->GetName());
                   #  # ]
     439         [ #  # ]:           0 :     PushWarnings(warnings, obj);
     440                 :             : 
     441         [ #  # ]:           0 :     return obj;
     442                 :           0 : },
     443   [ +  -  +  -  :         400 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     444   [ +  -  +  -  :         230 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          -  -  -  -  -  
                      - ]
     445                 :             : 
     446                 :          10 : static RPCHelpMan unloadwallet()
     447                 :             : {
     448                 :          10 :     return RPCHelpMan{"unloadwallet",
     449                 :             :                 "Unloads the wallet referenced by the request endpoint, otherwise unloads the wallet specified in the argument.\n"
     450                 :             :                 "Specifying the wallet name on a wallet endpoint is invalid.",
     451                 :             :                 {
     452         [ +  - ]:          20 :                     {"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."},
     453         [ +  - ]:          10 :                     {"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."},
     454                 :             :                 },
     455                 :           0 :                 RPCResult{RPCResult::Type::OBJ, "", "", {
     456                 :             :                     {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to unloading the wallet.",
     457                 :             :                     {
     458                 :             :                         {RPCResult::Type::STR, "", ""},
     459                 :             :                     }},
     460   [ +  -  +  -  :          50 :                 }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  +  
             -  -  -  - ]
     461                 :          10 :                 RPCExamples{
     462   [ +  -  +  -  :          20 :                     HelpExampleCli("unloadwallet", "wallet_name")
                   +  - ]
     463   [ +  -  +  -  :          40 :             + HelpExampleRpc("unloadwallet", "wallet_name")
             +  -  +  - ]
     464         [ +  - ]:          10 :                 },
     465                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     466                 :             : {
     467         [ #  # ]:           0 :     std::string wallet_name;
     468   [ #  #  #  # ]:           0 :     if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
     469   [ #  #  #  #  :           0 :         if (!(request.params[0].isNull() || request.params[0].get_str() == wallet_name)) {
          #  #  #  #  #  
                      # ]
     470   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "RPC endpoint wallet and wallet_name parameter specify different wallets");
     471                 :             :         }
     472                 :             :     } else {
     473   [ #  #  #  #  :           0 :         wallet_name = request.params[0].get_str();
                   #  # ]
     474                 :             :     }
     475                 :             : 
     476         [ #  # ]:           0 :     WalletContext& context = EnsureWalletContext(request.context);
     477         [ #  # ]:           0 :     std::shared_ptr<CWallet> wallet = GetWallet(context, wallet_name);
     478         [ #  # ]:           0 :     if (!wallet) {
     479   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
     480                 :             :     }
     481                 :             : 
     482                 :           0 :     std::vector<bilingual_str> warnings;
     483                 :           0 :     {
     484                 :           0 :         WalletRescanReserver reserver(*wallet);
     485         [ #  # ]:           0 :         if (!reserver.reserve()) {
     486   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
     487                 :             :         }
     488                 :             : 
     489                 :             :         // Release the "main" shared pointer and prevent further notifications.
     490                 :             :         // Note that any attempt to load the same wallet would fail until the wallet
     491                 :             :         // is destroyed (see CheckUniqueFileid).
     492         [ #  # ]:           0 :         std::optional<bool> load_on_start{self.MaybeArg<bool>("load_on_startup")};
     493   [ #  #  #  # ]:           0 :         if (!RemoveWallet(context, wallet, load_on_start, warnings)) {
     494   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded");
     495                 :             :         }
     496                 :           0 :     }
     497                 :             : 
     498         [ #  # ]:           0 :     WaitForDeleteWallet(std::move(wallet));
     499                 :             : 
     500                 :           0 :     UniValue result(UniValue::VOBJ);
     501         [ #  # ]:           0 :     PushWarnings(warnings, result);
     502                 :             : 
     503                 :           0 :     return result;
     504         [ #  # ]:           0 : },
     505   [ +  -  +  -  :         140 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     506   [ +  -  +  -  :          80 : }
          +  -  +  -  +  
             -  +  -  -  
                      - ]
     507                 :             : 
     508                 :          10 : static RPCHelpMan sethdseed()
     509                 :             : {
     510                 :          10 :     return RPCHelpMan{"sethdseed",
     511                 :             :                 "\nSet or generate a new HD wallet seed. Non-HD wallets will not be upgraded to being a HD wallet. Wallets that are already\n"
     512                 :             :                 "HD will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n"
     513         [ +  - ]:          20 :                 "\nNote that you will need to MAKE A NEW BACKUP of your wallet after setting the HD wallet seed." + HELP_REQUIRING_PASSPHRASE +
     514                 :          10 :                 "Note: This command is only compatible with legacy wallets.\n",
     515                 :             :                 {
     516         [ +  - ]:          20 :                     {"newkeypool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to flush old unused addresses, including change addresses, from the keypool and regenerate it.\n"
     517                 :             :                                          "If true, the next address from getnewaddress and change address from getrawchangeaddress will be from this new seed.\n"
     518                 :             :                                          "If false, addresses (including change addresses if the wallet already had HD Chain Split enabled) from the existing\n"
     519                 :             :                                          "keypool will be used until it has been depleted."},
     520         [ +  - ]:          20 :                     {"seed", RPCArg::Type::STR, RPCArg::DefaultHint{"random seed"}, "The WIF private key to use as the new HD seed.\n"
     521                 :             :                                          "The seed value can be retrieved using the dumpwallet command. It is the private key marked hdseed=1"},
     522                 :             :                 },
     523   [ +  -  +  -  :          20 :                 RPCResult{RPCResult::Type::NONE, "", ""},
                   +  - ]
     524                 :          10 :                 RPCExamples{
     525   [ +  -  +  -  :          20 :                     HelpExampleCli("sethdseed", "")
                   +  - ]
     526   [ +  -  +  -  :          40 :             + HelpExampleCli("sethdseed", "false")
             +  -  +  - ]
     527   [ +  -  +  -  :          40 :             + HelpExampleCli("sethdseed", "true \"wifkey\"")
             +  -  +  - ]
     528   [ +  -  +  -  :          40 :             + HelpExampleRpc("sethdseed", "true, \"wifkey\"")
             +  -  +  - ]
     529         [ +  - ]:          10 :                 },
     530                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     531                 :             : {
     532                 :           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     533         [ #  # ]:           0 :     if (!pwallet) return UniValue::VNULL;
     534                 :             : 
     535         [ #  # ]:           0 :     LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet, true);
     536                 :             : 
     537   [ #  #  #  # ]:           0 :     if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     538   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed to a wallet with private keys disabled");
     539                 :             :     }
     540                 :             : 
     541   [ #  #  #  # ]:           0 :     LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
     542                 :             : 
     543                 :             :     // Do not do anything to non-HD wallets
     544   [ #  #  #  # ]:           0 :     if (!pwallet->CanSupportFeature(FEATURE_HD)) {
     545   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set an HD seed on a non-HD wallet. Use the upgradewallet RPC in order to upgrade a non-HD wallet to HD");
     546                 :             :     }
     547                 :             : 
     548         [ #  # ]:           0 :     EnsureWalletIsUnlocked(*pwallet);
     549                 :             : 
     550                 :           0 :     bool flush_key_pool = true;
     551   [ #  #  #  # ]:           0 :     if (!request.params[0].isNull()) {
     552   [ #  #  #  # ]:           0 :         flush_key_pool = request.params[0].get_bool();
     553                 :             :     }
     554                 :             : 
     555         [ #  # ]:           0 :     CPubKey master_pub_key;
     556   [ #  #  #  # ]:           0 :     if (request.params[1].isNull()) {
     557         [ #  # ]:           0 :         master_pub_key = spk_man.GenerateNewSeed();
     558                 :             :     } else {
     559   [ #  #  #  #  :           0 :         CKey key = DecodeSecret(request.params[1].get_str());
                   #  # ]
     560         [ #  # ]:           0 :         if (!key.IsValid()) {
     561   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
     562                 :             :         }
     563                 :             : 
     564   [ #  #  #  # ]:           0 :         if (HaveKey(spk_man, key)) {
     565   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)");
     566                 :             :         }
     567                 :             : 
     568         [ #  # ]:           0 :         master_pub_key = spk_man.DeriveNewSeed(key);
     569                 :           0 :     }
     570                 :             : 
     571         [ #  # ]:           0 :     spk_man.SetHDSeed(master_pub_key);
     572   [ #  #  #  # ]:           0 :     if (flush_key_pool) spk_man.NewKeyPool();
     573                 :             : 
     574         [ #  # ]:           0 :     return UniValue::VNULL;
     575         [ #  # ]:           0 : },
     576   [ +  -  +  -  :         180 :     };
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
     577   [ +  -  +  -  :          50 : }
             +  -  -  - ]
     578                 :             : 
     579                 :          10 : static RPCHelpMan upgradewallet()
     580                 :             : {
     581                 :          10 :     return RPCHelpMan{"upgradewallet",
     582                 :             :         "\nUpgrade the wallet. Upgrades to the latest version if no version number is specified.\n"
     583                 :             :         "New keys may be generated and a new wallet backup will need to be made.",
     584                 :             :         {
     585         [ +  - ]:          20 :             {"version", RPCArg::Type::NUM, RPCArg::Default{int{FEATURE_LATEST}}, "The version number to upgrade to. Default is the latest wallet version."}
     586                 :             :         },
     587                 :           0 :         RPCResult{
     588                 :             :             RPCResult::Type::OBJ, "", "",
     589                 :             :             {
     590                 :             :                 {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"},
     591                 :             :                 {RPCResult::Type::NUM, "previous_version", "Version of wallet before this operation"},
     592                 :             :                 {RPCResult::Type::NUM, "current_version", "Version of wallet after this operation"},
     593                 :             :                 {RPCResult::Type::STR, "result", /*optional=*/true, "Description of result, if no error"},
     594                 :             :                 {RPCResult::Type::STR, "error", /*optional=*/true, "Error message (if there is one)"}
     595                 :             :             },
     596   [ +  -  +  -  :          70 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                +  -  - ]
     597                 :          10 :         RPCExamples{
     598   [ +  -  +  -  :          20 :             HelpExampleCli("upgradewallet", "169900")
                   +  - ]
     599   [ +  -  +  -  :          40 :             + HelpExampleRpc("upgradewallet", "169900")
             +  -  +  - ]
     600         [ +  - ]:          10 :         },
     601                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     602                 :             : {
     603                 :           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     604         [ #  # ]:           0 :     if (!pwallet) return UniValue::VNULL;
     605                 :             : 
     606         [ #  # ]:           0 :     EnsureWalletIsUnlocked(*pwallet);
     607                 :             : 
     608                 :           0 :     int version = 0;
     609   [ #  #  #  # ]:           0 :     if (!request.params[0].isNull()) {
     610   [ #  #  #  # ]:           0 :         version = request.params[0].getInt<int>();
     611                 :             :     }
     612         [ #  # ]:           0 :     bilingual_str error;
     613         [ #  # ]:           0 :     const int previous_version{pwallet->GetVersion()};
     614         [ #  # ]:           0 :     const bool wallet_upgraded{pwallet->UpgradeWallet(version, error)};
     615         [ #  # ]:           0 :     const int current_version{pwallet->GetVersion()};
     616         [ #  # ]:           0 :     std::string result;
     617                 :             : 
     618         [ #  # ]:           0 :     if (wallet_upgraded) {
     619         [ #  # ]:           0 :         if (previous_version == current_version) {
     620         [ #  # ]:           0 :             result = "Already at latest version. Wallet version unchanged.";
     621                 :             :         } else {
     622         [ #  # ]:           0 :             result = strprintf("Wallet upgraded successfully from version %i to version %i.", previous_version, current_version);
     623                 :             :         }
     624                 :             :     }
     625                 :             : 
     626                 :           0 :     UniValue obj(UniValue::VOBJ);
     627   [ #  #  #  #  :           0 :     obj.pushKV("wallet_name", pwallet->GetName());
                   #  # ]
     628   [ #  #  #  #  :           0 :     obj.pushKV("previous_version", previous_version);
                   #  # ]
     629   [ #  #  #  #  :           0 :     obj.pushKV("current_version", current_version);
                   #  # ]
     630         [ #  # ]:           0 :     if (!result.empty()) {
     631   [ #  #  #  #  :           0 :         obj.pushKV("result", result);
                   #  # ]
     632                 :             :     } else {
     633         [ #  # ]:           0 :         CHECK_NONFATAL(!error.empty());
     634   [ #  #  #  #  :           0 :         obj.pushKV("error", error.original);
                   #  # ]
     635                 :             :     }
     636                 :           0 :     return obj;
     637                 :           0 : },
     638   [ +  -  +  -  :         110 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     639   [ +  -  +  -  :          90 : }
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  -  - ]
     640                 :             : 
     641                 :          10 : RPCHelpMan simulaterawtransaction()
     642                 :             : {
     643                 :          10 :     return RPCHelpMan{"simulaterawtransaction",
     644                 :             :         "\nCalculate the balance change resulting in the signing and broadcasting of the given transaction(s).\n",
     645                 :             :         {
     646         [ +  - ]:          10 :             {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of hex strings of raw transactions.\n",
     647                 :             :                 {
     648         [ +  - ]:          10 :                     {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
     649                 :             :                 },
     650                 :             :             },
     651         [ +  - ]:          10 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
     652                 :             :                 {
     653         [ +  - ]:          20 :                     {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see RPC importaddress)"},
     654                 :             :                 },
     655                 :             :             },
     656                 :             :         },
     657                 :           0 :         RPCResult{
     658                 :             :             RPCResult::Type::OBJ, "", "",
     659                 :             :             {
     660                 :             :                 {RPCResult::Type::STR_AMOUNT, "balance_change", "The wallet balance change (negative means decrease)."},
     661                 :             :             }
     662   [ +  -  +  -  :          30 :         },
          +  -  +  -  +  
          -  +  -  +  -  
             +  +  -  - ]
     663                 :          10 :         RPCExamples{
     664   [ +  -  +  -  :          20 :             HelpExampleCli("simulaterawtransaction", "[\"myhex\"]")
                   +  - ]
     665   [ +  -  +  -  :          40 :             + HelpExampleRpc("simulaterawtransaction", "[\"myhex\"]")
             +  -  +  - ]
     666         [ +  - ]:          10 :         },
     667                 :           0 :     [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     668                 :             : {
     669         [ #  # ]:           0 :     const std::shared_ptr<const CWallet> rpc_wallet = GetWalletForJSONRPCRequest(request);
     670         [ #  # ]:           0 :     if (!rpc_wallet) return UniValue::VNULL;
     671         [ #  # ]:           0 :     const CWallet& wallet = *rpc_wallet;
     672                 :             : 
     673         [ #  # ]:           0 :     LOCK(wallet.cs_wallet);
     674                 :             : 
     675                 :           0 :     UniValue include_watchonly(UniValue::VNULL);
     676   [ #  #  #  # ]:           0 :     if (request.params[1].isObject()) {
     677   [ #  #  #  # ]:           0 :         UniValue options = request.params[1];
     678   [ #  #  #  #  :           0 :         RPCTypeCheckObj(options,
                   #  # ]
     679                 :             :             {
     680         [ #  # ]:           0 :                 {"include_watchonly", UniValueType(UniValue::VBOOL)},
     681                 :             :             },
     682                 :             :             true, true);
     683                 :             : 
     684   [ #  #  #  #  :           0 :         include_watchonly = options["include_watchonly"];
                   #  # ]
     685                 :           0 :     }
     686                 :             : 
     687                 :           0 :     isminefilter filter = ISMINE_SPENDABLE;
     688   [ #  #  #  # ]:           0 :     if (ParseIncludeWatchonly(include_watchonly, wallet)) {
     689                 :           0 :         filter |= ISMINE_WATCH_ONLY;
     690                 :             :     }
     691                 :             : 
     692   [ #  #  #  # ]:           0 :     const auto& txs = request.params[0].get_array();
     693                 :           0 :     CAmount changes{0};
     694                 :           0 :     std::map<COutPoint, CAmount> new_utxos; // UTXO:s that were made available in transaction array
     695                 :           0 :     std::set<COutPoint> spent;
     696                 :             : 
     697         [ #  # ]:           0 :     for (size_t i = 0; i < txs.size(); ++i) {
     698         [ #  # ]:           0 :         CMutableTransaction mtx;
     699   [ #  #  #  #  :           0 :         if (!DecodeHexTx(mtx, txs[i].get_str(), /* try_no_witness */ true, /* try_witness */ true)) {
             #  #  #  # ]
     700   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Transaction hex string decoding failure.");
     701                 :             :         }
     702                 :             : 
     703                 :             :         // Fetch previous transactions (inputs)
     704                 :           0 :         std::map<COutPoint, Coin> coins;
     705         [ #  # ]:           0 :         for (const CTxIn& txin : mtx.vin) {
     706         [ #  # ]:           0 :             coins[txin.prevout]; // Create empty map entry keyed by prevout.
     707                 :             :         }
     708         [ #  # ]:           0 :         wallet.chain().findCoins(coins);
     709                 :             : 
     710                 :             :         // Fetch debit; we are *spending* these; if the transaction is signed and
     711                 :             :         // broadcast, we will lose everything in these
     712         [ #  # ]:           0 :         for (const auto& txin : mtx.vin) {
     713                 :           0 :             const auto& outpoint = txin.prevout;
     714         [ #  # ]:           0 :             if (spent.count(outpoint)) {
     715   [ #  #  #  # ]:           0 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction(s) are spending the same output more than once");
     716                 :             :             }
     717         [ #  # ]:           0 :             if (new_utxos.count(outpoint)) {
     718         [ #  # ]:           0 :                 changes -= new_utxos.at(outpoint);
     719                 :           0 :                 new_utxos.erase(outpoint);
     720                 :             :             } else {
     721   [ #  #  #  # ]:           0 :                 if (coins.at(outpoint).IsSpent()) {
     722   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more transaction inputs are missing or have been spent already");
     723                 :             :                 }
     724         [ #  # ]:           0 :                 changes -= wallet.GetDebit(txin, filter);
     725                 :             :             }
     726         [ #  # ]:           0 :             spent.insert(outpoint);
     727                 :             :         }
     728                 :             : 
     729                 :             :         // Iterate over outputs; we are *receiving* these, if the wallet considers
     730                 :             :         // them "mine"; if the transaction is signed and broadcast, we will receive
     731                 :             :         // everything in these
     732                 :             :         // Also populate new_utxos in case these are spent in later transactions
     733                 :             : 
     734         [ #  # ]:           0 :         const auto& hash = mtx.GetHash();
     735         [ #  # ]:           0 :         for (size_t i = 0; i < mtx.vout.size(); ++i) {
     736         [ #  # ]:           0 :             const auto& txout = mtx.vout[i];
     737         [ #  # ]:           0 :             bool is_mine = 0 < (wallet.IsMine(txout) & filter);
     738   [ #  #  #  # ]:           0 :             changes += new_utxos[COutPoint(hash, i)] = is_mine ? txout.nValue : 0;
     739                 :             :         }
     740                 :           0 :     }
     741                 :             : 
     742                 :           0 :     UniValue result(UniValue::VOBJ);
     743   [ #  #  #  #  :           0 :     result.pushKV("balance_change", ValueFromAmount(changes));
                   #  # ]
     744                 :             : 
     745                 :           0 :     return result;
     746   [ #  #  #  #  :           0 : }
                   #  # ]
     747   [ +  -  +  -  :         200 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  +  +  
          -  -  -  -  -  
                      - ]
     748   [ +  -  +  -  :         110 : }
          +  -  +  -  +  
          -  +  -  +  -  
                   -  - ]
     749                 :             : 
     750                 :          10 : static RPCHelpMan migratewallet()
     751                 :             : {
     752                 :          10 :     return RPCHelpMan{"migratewallet",
     753                 :             :         "\nMigrate the wallet to a descriptor wallet.\n"
     754                 :             :         "A new wallet backup will need to be made.\n"
     755                 :             :         "\nThe migration process will create a backup of the wallet before migrating. This backup\n"
     756                 :             :         "file will be named <wallet name>-<timestamp>.legacy.bak and can be found in the directory\n"
     757                 :             :         "for this wallet. In the event of an incorrect migration, the backup can be restored using restorewallet."
     758                 :             :         "\nEncrypted wallets must have the passphrase provided as an argument to this call.\n"
     759                 :             :         "\nThis RPC may take a long time to complete. Increasing the RPC client timeout is recommended.",
     760                 :             :         {
     761         [ +  - ]:          20 :             {"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."},
     762         [ +  - ]:          10 :             {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "The wallet passphrase"},
     763                 :             :         },
     764                 :           0 :         RPCResult{
     765                 :             :             RPCResult::Type::OBJ, "", "",
     766                 :             :             {
     767                 :             :                 {RPCResult::Type::STR, "wallet_name", "The name of the primary migrated wallet"},
     768                 :             :                 {RPCResult::Type::STR, "watchonly_name", /*optional=*/true, "The name of the migrated wallet containing the watchonly scripts"},
     769                 :             :                 {RPCResult::Type::STR, "solvables_name", /*optional=*/true, "The name of the migrated wallet containing solvable but not watched scripts"},
     770                 :             :                 {RPCResult::Type::STR, "backup_path", "The location of the backup of the original wallet"},
     771                 :             :             }
     772   [ +  -  +  -  :          60 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     773                 :          10 :         RPCExamples{
     774   [ +  -  +  -  :          20 :             HelpExampleCli("migratewallet", "")
                   +  - ]
     775   [ +  -  +  -  :          40 :             + HelpExampleRpc("migratewallet", "")
             +  -  +  - ]
     776         [ +  - ]:          10 :         },
     777                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     778                 :             :         {
     779         [ #  # ]:           0 :             std::string wallet_name;
     780   [ #  #  #  # ]:           0 :             if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
     781   [ #  #  #  #  :           0 :                 if (!(request.params[0].isNull() || request.params[0].get_str() == wallet_name)) {
          #  #  #  #  #  
                      # ]
     782   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "RPC endpoint wallet and wallet_name parameter specify different wallets");
     783                 :             :                 }
     784                 :             :             } else {
     785   [ #  #  #  # ]:           0 :                 if (request.params[0].isNull()) {
     786   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "Either RPC endpoint wallet or wallet_name parameter must be provided");
     787                 :             :                 }
     788   [ #  #  #  #  :           0 :                 wallet_name = request.params[0].get_str();
                   #  # ]
     789                 :             :             }
     790                 :             : 
     791         [ #  # ]:           0 :             SecureString wallet_pass;
     792         [ #  # ]:           0 :             wallet_pass.reserve(100);
     793   [ #  #  #  # ]:           0 :             if (!request.params[1].isNull()) {
     794   [ #  #  #  #  :           0 :                 wallet_pass = std::string_view{request.params[1].get_str()};
                   #  # ]
     795                 :             :             }
     796                 :             : 
     797         [ #  # ]:           0 :             WalletContext& context = EnsureWalletContext(request.context);
     798         [ #  # ]:           0 :             util::Result<MigrationResult> res = MigrateLegacyToDescriptor(wallet_name, wallet_pass, context);
     799         [ #  # ]:           0 :             if (!res) {
     800   [ #  #  #  # ]:           0 :                 throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(res).original);
     801                 :             :             }
     802                 :             : 
     803                 :           0 :             UniValue r{UniValue::VOBJ};
     804   [ #  #  #  #  :           0 :             r.pushKV("wallet_name", res->wallet_name);
                   #  # ]
     805         [ #  # ]:           0 :             if (res->watchonly_wallet) {
     806   [ #  #  #  #  :           0 :                 r.pushKV("watchonly_name", res->watchonly_wallet->GetName());
                   #  # ]
     807                 :             :             }
     808         [ #  # ]:           0 :             if (res->solvables_wallet) {
     809   [ #  #  #  #  :           0 :                 r.pushKV("solvables_name", res->solvables_wallet->GetName());
                   #  # ]
     810                 :             :             }
     811   [ #  #  #  #  :           0 :             r.pushKV("backup_path", res->backup_path.utf8string());
             #  #  #  # ]
     812                 :             : 
     813                 :           0 :             return r;
     814                 :           0 :         },
     815   [ +  -  +  -  :         140 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  -  
                      - ]
     816   [ +  -  +  -  :         100 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  -  -  
                      - ]
     817                 :             : 
     818                 :          10 : RPCHelpMan gethdkeys()
     819                 :             : {
     820                 :          10 :     return RPCHelpMan{
     821                 :             :         "gethdkeys",
     822                 :             :         "\nList all BIP 32 HD keys in the wallet and which descriptors use them.\n",
     823                 :             :         {
     824         [ +  - ]:          10 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
     825         [ +  - ]:          20 :                 {"active_only", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show the keys for only active descriptors"},
     826         [ +  - ]:          20 :                 {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private keys"}
     827                 :             :             }},
     828                 :             :         },
     829                 :           0 :         RPCResult{RPCResult::Type::ARR, "", "", {
     830                 :             :             {
     831                 :             :                 {RPCResult::Type::OBJ, "", "", {
     832                 :             :                     {RPCResult::Type::STR, "xpub", "The extended public key"},
     833                 :             :                     {RPCResult::Type::BOOL, "has_private", "Whether the wallet has the private key for this xpub"},
     834                 :             :                     {RPCResult::Type::STR, "xprv", /*optional=*/true, "The extended private key if \"private\" is true"},
     835                 :             :                     {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects that use this HD key",
     836                 :             :                     {
     837                 :             :                         {RPCResult::Type::OBJ, "", "", {
     838                 :             :                             {RPCResult::Type::STR, "desc", "Descriptor string representation"},
     839                 :             :                             {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"},
     840                 :             :                         }},
     841                 :             :                     }},
     842                 :             :                 }},
     843                 :             :             }
     844   [ +  -  +  -  :         130 :         }},
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
          +  +  +  +  +  
          -  -  -  -  -  
                -  -  - ]
     845                 :          10 :         RPCExamples{
     846   [ +  -  +  -  :          20 :             HelpExampleCli("gethdkeys", "") + HelpExampleRpc("gethdkeys", "")
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     847   [ +  -  +  -  :         100 :             + HelpExampleCliNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}}) + HelpExampleRpcNamed("gethdkeys", {{"active_only", "true"}, {"private", "true"}})
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  +  +  
             +  -  -  -  
                      - ]
     848         [ +  - ]:          10 :         },
     849                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     850                 :             :         {
     851         [ #  # ]:           0 :             const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
     852         [ #  # ]:           0 :             if (!wallet) return UniValue::VNULL;
     853                 :             : 
     854   [ #  #  #  # ]:           0 :             if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
     855   [ #  #  #  # ]:           0 :                 throw JSONRPCError(RPC_WALLET_ERROR, "gethdkeys is not available for non-descriptor wallets");
     856                 :             :             }
     857                 :             : 
     858         [ #  # ]:           0 :             LOCK(wallet->cs_wallet);
     859                 :             : 
     860   [ #  #  #  #  :           0 :             UniValue options{request.params[0].isNull() ? UniValue::VOBJ : request.params[0]};
             #  #  #  # ]
     861   [ #  #  #  #  :           0 :             const bool active_only{options.exists("active_only") ? options["active_only"].get_bool() : false};
          #  #  #  #  #  
                      # ]
     862   [ #  #  #  #  :           0 :             const bool priv{options.exists("private") ? options["private"].get_bool() : false};
          #  #  #  #  #  
                      # ]
     863         [ #  # ]:           0 :             if (priv) {
     864         [ #  # ]:           0 :                 EnsureWalletIsUnlocked(*wallet);
     865                 :             :             }
     866                 :             : 
     867                 :             : 
     868         [ #  # ]:           0 :             std::set<ScriptPubKeyMan*> spkms;
     869         [ #  # ]:           0 :             if (active_only) {
     870         [ #  # ]:           0 :                 spkms = wallet->GetActiveScriptPubKeyMans();
     871                 :             :             } else {
     872         [ #  # ]:           0 :                 spkms = wallet->GetAllScriptPubKeyMans();
     873                 :             :             }
     874                 :             : 
     875                 :           0 :             std::map<CExtPubKey, std::set<std::tuple<std::string, bool, bool>>> wallet_xpubs;
     876                 :           0 :             std::map<CExtPubKey, CExtKey> wallet_xprvs;
     877         [ #  # ]:           0 :             for (auto* spkm : spkms) {
     878         [ #  # ]:           0 :                 auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};
     879         [ #  # ]:           0 :                 CHECK_NONFATAL(desc_spkm);
     880         [ #  # ]:           0 :                 LOCK(desc_spkm->cs_desc_man);
     881         [ #  # ]:           0 :                 WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();
     882                 :             : 
     883                 :             :                 // Retrieve the pubkeys from the descriptor
     884         [ #  # ]:           0 :                 std::set<CPubKey> desc_pubkeys;
     885                 :           0 :                 std::set<CExtPubKey> desc_xpubs;
     886         [ #  # ]:           0 :                 w_desc.descriptor->GetPubKeys(desc_pubkeys, desc_xpubs);
     887         [ #  # ]:           0 :                 for (const CExtPubKey& xpub : desc_xpubs) {
     888         [ #  # ]:           0 :                     std::string desc_str;
     889         [ #  # ]:           0 :                     bool ok = desc_spkm->GetDescriptorString(desc_str, false);
     890         [ #  # ]:           0 :                     CHECK_NONFATAL(ok);
     891   [ #  #  #  #  :           0 :                     wallet_xpubs[xpub].emplace(desc_str, wallet->IsActiveScriptPubKeyMan(*spkm), desc_spkm->HasPrivKey(xpub.pubkey.GetID()));
          #  #  #  #  #  
                      # ]
     892   [ #  #  #  #  :           0 :                     if (std::optional<CKey> key = priv ? desc_spkm->GetKey(xpub.pubkey.GetID()) : std::nullopt) {
             #  #  #  # ]
     893   [ #  #  #  # ]:           0 :                         wallet_xprvs[xpub] = CExtKey(xpub, *key);
     894                 :           0 :                     }
     895                 :           0 :                 }
     896         [ #  # ]:           0 :             }
     897                 :             : 
     898                 :           0 :             UniValue response(UniValue::VARR);
     899         [ #  # ]:           0 :             for (const auto& [xpub, descs] : wallet_xpubs) {
     900                 :           0 :                 bool has_xprv = false;
     901                 :           0 :                 UniValue descriptors(UniValue::VARR);
     902         [ #  # ]:           0 :                 for (const auto& [desc, active, has_priv] : descs) {
     903                 :           0 :                     UniValue d(UniValue::VOBJ);
     904   [ #  #  #  #  :           0 :                     d.pushKV("desc", desc);
                   #  # ]
     905   [ #  #  #  #  :           0 :                     d.pushKV("active", active);
                   #  # ]
     906                 :           0 :                     has_xprv |= has_priv;
     907                 :             : 
     908         [ #  # ]:           0 :                     descriptors.push_back(std::move(d));
     909                 :           0 :                 }
     910                 :           0 :                 UniValue xpub_info(UniValue::VOBJ);
     911   [ #  #  #  #  :           0 :                 xpub_info.pushKV("xpub", EncodeExtPubKey(xpub));
             #  #  #  # ]
     912   [ #  #  #  #  :           0 :                 xpub_info.pushKV("has_private", has_xprv);
                   #  # ]
     913         [ #  # ]:           0 :                 if (priv) {
     914   [ #  #  #  #  :           0 :                     xpub_info.pushKV("xprv", EncodeExtKey(wallet_xprvs.at(xpub)));
          #  #  #  #  #  
                      # ]
     915                 :             :                 }
     916   [ #  #  #  # ]:           0 :                 xpub_info.pushKV("descriptors", std::move(descriptors));
     917                 :             : 
     918         [ #  # ]:           0 :                 response.push_back(std::move(xpub_info));
     919                 :           0 :             }
     920                 :             : 
     921                 :           0 :             return response;
     922         [ #  # ]:           0 :         },
     923   [ +  -  +  -  :         190 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  +  
          +  +  -  -  -  
                      - ]
     924   [ +  -  +  -  :         180 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
             -  -  -  -  
                      - ]
     925                 :             : 
     926                 :          10 : static RPCHelpMan createwalletdescriptor()
     927                 :             : {
     928                 :          10 :     return RPCHelpMan{"createwalletdescriptor",
     929                 :             :         "Creates the wallet's descriptor for the given address type. "
     930                 :             :         "The address type must be one that the wallet does not already have a descriptor for."
     931         [ +  - ]:          20 :         + HELP_REQUIRING_PASSPHRASE,
     932                 :             :         {
     933         [ +  - ]:          10 :             {"type", RPCArg::Type::STR, RPCArg::Optional::NO, "The address type the descriptor will produce. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
     934         [ +  - ]:          10 :             {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", {
     935         [ +  - ]:          20 :                 {"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)"},
     936         [ +  - ]:          20 :                 {"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"},
     937                 :             :             }},
     938                 :             :         },
     939                 :           0 :         RPCResult{
     940                 :             :             RPCResult::Type::OBJ, "", "",
     941                 :             :             {
     942                 :             :                 {RPCResult::Type::ARR, "descs", "The public descriptors that were added to the wallet",
     943                 :             :                     {{RPCResult::Type::STR, "", ""}}
     944                 :             :                 }
     945                 :             :             },
     946   [ +  -  +  -  :          50 :         },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  +  
             -  -  -  - ]
     947                 :          10 :         RPCExamples{
     948   [ +  -  +  -  :          20 :             HelpExampleCli("createwalletdescriptor", "bech32m")
                   +  - ]
     949   [ +  -  +  -  :          40 :             + HelpExampleRpc("createwalletdescriptor", "bech32m")
             +  -  +  - ]
     950         [ +  - ]:          10 :         },
     951                 :           0 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     952                 :             :         {
     953                 :           0 :             std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     954         [ #  # ]:           0 :             if (!pwallet) return UniValue::VNULL;
     955                 :             : 
     956                 :             :             //  Make sure wallet is a descriptor wallet
     957   [ #  #  #  # ]:           0 :             if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
     958   [ #  #  #  # ]:           0 :                 throw JSONRPCError(RPC_WALLET_ERROR, "createwalletdescriptor is not available for non-descriptor wallets");
     959                 :             :             }
     960                 :             : 
     961   [ #  #  #  #  :           0 :             std::optional<OutputType> output_type = ParseOutputType(request.params[0].get_str());
                   #  # ]
     962         [ #  # ]:           0 :             if (!output_type) {
     963   [ #  #  #  #  :           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
             #  #  #  # ]
     964                 :             :             }
     965                 :             : 
     966   [ #  #  #  #  :           0 :             UniValue options{request.params[1].isNull() ? UniValue::VOBJ : request.params[1]};
             #  #  #  # ]
     967   [ #  #  #  #  :           0 :             UniValue internal_only{options["internal"]};
                   #  # ]
     968   [ #  #  #  #  :           0 :             UniValue hdkey{options["hdkey"]};
                   #  # ]
     969                 :             : 
     970                 :           0 :             std::vector<bool> internals;
     971         [ #  # ]:           0 :             if (internal_only.isNull()) {
     972         [ #  # ]:           0 :                 internals.push_back(false);
     973         [ #  # ]:           0 :                 internals.push_back(true);
     974                 :             :             } else {
     975   [ #  #  #  # ]:           0 :                 internals.push_back(internal_only.get_bool());
     976                 :             :             }
     977                 :             : 
     978         [ #  # ]:           0 :             LOCK(pwallet->cs_wallet);
     979         [ #  # ]:           0 :             EnsureWalletIsUnlocked(*pwallet);
     980                 :             : 
     981         [ #  # ]:           0 :             CExtPubKey xpub;
     982         [ #  # ]:           0 :             if (hdkey.isNull()) {
     983         [ #  # ]:           0 :                 std::set<CExtPubKey> active_xpubs = pwallet->GetActiveHDPubKeys();
     984         [ #  # ]:           0 :                 if (active_xpubs.size() != 1) {
     985   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to determine which HD key to use from active descriptors. Please specify with 'hdkey'");
     986                 :             :                 }
     987                 :           0 :                 xpub = *active_xpubs.begin();
     988                 :           0 :             } else {
     989   [ #  #  #  # ]:           0 :                 xpub = DecodeExtPubKey(hdkey.get_str());
     990         [ #  # ]:           0 :                 if (!xpub.pubkey.IsValid()) {
     991   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to parse HD key. Please provide a valid xpub");
     992                 :             :                 }
     993                 :             :             }
     994                 :             : 
     995   [ #  #  #  # ]:           0 :             std::optional<CKey> key = pwallet->GetKey(xpub.pubkey.GetID());
     996         [ #  # ]:           0 :             if (!key) {
     997   [ #  #  #  #  :           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Private key for %s is not known", EncodeExtPubKey(xpub)));
                   #  # ]
     998                 :             :             }
     999         [ #  # ]:           0 :             CExtKey active_hdkey(xpub, *key);
    1000                 :             : 
    1001                 :           0 :             std::vector<std::reference_wrapper<DescriptorScriptPubKeyMan>> spkms;
    1002         [ #  # ]:           0 :             WalletBatch batch{pwallet->GetDatabase()};
    1003   [ #  #  #  # ]:           0 :             for (bool internal : internals) {
    1004         [ #  # ]:           0 :                 WalletDescriptor w_desc = GenerateWalletDescriptor(xpub, *output_type, internal);
    1005         [ #  # ]:           0 :                 uint256 w_id = DescriptorID(*w_desc.descriptor);
    1006   [ #  #  #  # ]:           0 :                 if (!pwallet->GetScriptPubKeyMan(w_id)) {
    1007   [ #  #  #  # ]:           0 :                     spkms.emplace_back(pwallet->SetupDescriptorScriptPubKeyMan(batch, active_hdkey, *output_type, internal));
    1008                 :             :                 }
    1009                 :           0 :             }
    1010         [ #  # ]:           0 :             if (spkms.empty()) {
    1011   [ #  #  #  # ]:           0 :                 throw JSONRPCError(RPC_WALLET_ERROR, "Descriptor already exists");
    1012                 :             :             }
    1013                 :             : 
    1014                 :             :             // Fetch each descspkm from the wallet in order to get the descriptor strings
    1015                 :           0 :             UniValue descs{UniValue::VARR};
    1016         [ #  # ]:           0 :             for (const auto& spkm : spkms) {
    1017         [ #  # ]:           0 :                 std::string desc_str;
    1018         [ #  # ]:           0 :                 bool ok = spkm.get().GetDescriptorString(desc_str, false);
    1019         [ #  # ]:           0 :                 CHECK_NONFATAL(ok);
    1020   [ #  #  #  # ]:           0 :                 descs.push_back(desc_str);
    1021                 :           0 :             }
    1022                 :           0 :             UniValue out{UniValue::VOBJ};
    1023   [ #  #  #  # ]:           0 :             out.pushKV("descs", std::move(descs));
    1024                 :           0 :             return out;
    1025         [ #  # ]:           0 :         }
    1026   [ +  -  +  -  :         240 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  +  +  +  -  
                -  -  - ]
    1027   [ +  -  +  -  :         120 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  -  -  
                      - ]
    1028                 :             : 
    1029                 :             : // addresses
    1030                 :             : RPCHelpMan getaddressinfo();
    1031                 :             : RPCHelpMan getnewaddress();
    1032                 :             : RPCHelpMan getrawchangeaddress();
    1033                 :             : RPCHelpMan setlabel();
    1034                 :             : RPCHelpMan listaddressgroupings();
    1035                 :             : RPCHelpMan addmultisigaddress();
    1036                 :             : RPCHelpMan keypoolrefill();
    1037                 :             : RPCHelpMan newkeypool();
    1038                 :             : RPCHelpMan getaddressesbylabel();
    1039                 :             : RPCHelpMan listlabels();
    1040                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
    1041                 :             : RPCHelpMan walletdisplayaddress();
    1042                 :             : #endif // ENABLE_EXTERNAL_SIGNER
    1043                 :             : 
    1044                 :             : // backup
    1045                 :             : RPCHelpMan dumpprivkey();
    1046                 :             : RPCHelpMan importprivkey();
    1047                 :             : RPCHelpMan importaddress();
    1048                 :             : RPCHelpMan importpubkey();
    1049                 :             : RPCHelpMan dumpwallet();
    1050                 :             : RPCHelpMan importwallet();
    1051                 :             : RPCHelpMan importprunedfunds();
    1052                 :             : RPCHelpMan removeprunedfunds();
    1053                 :             : RPCHelpMan importmulti();
    1054                 :             : RPCHelpMan importdescriptors();
    1055                 :             : RPCHelpMan listdescriptors();
    1056                 :             : RPCHelpMan backupwallet();
    1057                 :             : RPCHelpMan restorewallet();
    1058                 :             : 
    1059                 :             : // coins
    1060                 :             : RPCHelpMan getreceivedbyaddress();
    1061                 :             : RPCHelpMan getreceivedbylabel();
    1062                 :             : RPCHelpMan getbalance();
    1063                 :             : RPCHelpMan getunconfirmedbalance();
    1064                 :             : RPCHelpMan lockunspent();
    1065                 :             : RPCHelpMan listlockunspent();
    1066                 :             : RPCHelpMan getbalances();
    1067                 :             : RPCHelpMan listunspent();
    1068                 :             : 
    1069                 :             : // encryption
    1070                 :             : RPCHelpMan walletpassphrase();
    1071                 :             : RPCHelpMan walletpassphrasechange();
    1072                 :             : RPCHelpMan walletlock();
    1073                 :             : RPCHelpMan encryptwallet();
    1074                 :             : 
    1075                 :             : // spend
    1076                 :             : RPCHelpMan sendtoaddress();
    1077                 :             : RPCHelpMan sendmany();
    1078                 :             : RPCHelpMan settxfee();
    1079                 :             : RPCHelpMan fundrawtransaction();
    1080                 :             : RPCHelpMan bumpfee();
    1081                 :             : RPCHelpMan psbtbumpfee();
    1082                 :             : RPCHelpMan send();
    1083                 :             : RPCHelpMan sendall();
    1084                 :             : RPCHelpMan walletprocesspsbt();
    1085                 :             : RPCHelpMan walletcreatefundedpsbt();
    1086                 :             : RPCHelpMan signrawtransactionwithwallet();
    1087                 :             : 
    1088                 :             : // signmessage
    1089                 :             : RPCHelpMan signmessage();
    1090                 :             : 
    1091                 :             : // transactions
    1092                 :             : RPCHelpMan listreceivedbyaddress();
    1093                 :             : RPCHelpMan listreceivedbylabel();
    1094                 :             : RPCHelpMan listtransactions();
    1095                 :             : RPCHelpMan listsinceblock();
    1096                 :             : RPCHelpMan gettransaction();
    1097                 :             : RPCHelpMan abandontransaction();
    1098                 :             : RPCHelpMan rescanblockchain();
    1099                 :             : RPCHelpMan abortrescan();
    1100                 :             : 
    1101                 :          18 : Span<const CRPCCommand> GetWalletRPCCommands()
    1102                 :             : {
    1103                 :          18 :     static const CRPCCommand commands[]{
    1104                 :             :         {"rawtransactions", &fundrawtransaction},
    1105                 :             :         {"wallet", &abandontransaction},
    1106                 :             :         {"wallet", &abortrescan},
    1107                 :             :         {"wallet", &addmultisigaddress},
    1108                 :             :         {"wallet", &backupwallet},
    1109                 :             :         {"wallet", &bumpfee},
    1110                 :             :         {"wallet", &psbtbumpfee},
    1111                 :             :         {"wallet", &createwallet},
    1112                 :             :         {"wallet", &createwalletdescriptor},
    1113                 :             :         {"wallet", &restorewallet},
    1114                 :             :         {"wallet", &dumpprivkey},
    1115                 :             :         {"wallet", &dumpwallet},
    1116                 :             :         {"wallet", &encryptwallet},
    1117                 :             :         {"wallet", &getaddressesbylabel},
    1118                 :             :         {"wallet", &getaddressinfo},
    1119                 :             :         {"wallet", &getbalance},
    1120                 :             :         {"wallet", &gethdkeys},
    1121                 :             :         {"wallet", &getnewaddress},
    1122                 :             :         {"wallet", &getrawchangeaddress},
    1123                 :             :         {"wallet", &getreceivedbyaddress},
    1124                 :             :         {"wallet", &getreceivedbylabel},
    1125                 :             :         {"wallet", &gettransaction},
    1126                 :             :         {"wallet", &getunconfirmedbalance},
    1127                 :             :         {"wallet", &getbalances},
    1128                 :             :         {"wallet", &getwalletinfo},
    1129                 :             :         {"wallet", &importaddress},
    1130                 :             :         {"wallet", &importdescriptors},
    1131                 :             :         {"wallet", &importmulti},
    1132                 :             :         {"wallet", &importprivkey},
    1133                 :             :         {"wallet", &importprunedfunds},
    1134                 :             :         {"wallet", &importpubkey},
    1135                 :             :         {"wallet", &importwallet},
    1136                 :             :         {"wallet", &keypoolrefill},
    1137                 :             :         {"wallet", &listaddressgroupings},
    1138                 :             :         {"wallet", &listdescriptors},
    1139                 :             :         {"wallet", &listlabels},
    1140                 :             :         {"wallet", &listlockunspent},
    1141                 :             :         {"wallet", &listreceivedbyaddress},
    1142                 :             :         {"wallet", &listreceivedbylabel},
    1143                 :             :         {"wallet", &listsinceblock},
    1144                 :             :         {"wallet", &listtransactions},
    1145                 :             :         {"wallet", &listunspent},
    1146                 :             :         {"wallet", &listwalletdir},
    1147                 :             :         {"wallet", &listwallets},
    1148                 :             :         {"wallet", &loadwallet},
    1149                 :             :         {"wallet", &lockunspent},
    1150                 :             :         {"wallet", &migratewallet},
    1151                 :             :         {"wallet", &newkeypool},
    1152                 :             :         {"wallet", &removeprunedfunds},
    1153                 :             :         {"wallet", &rescanblockchain},
    1154                 :             :         {"wallet", &send},
    1155                 :             :         {"wallet", &sendmany},
    1156                 :             :         {"wallet", &sendtoaddress},
    1157                 :             :         {"wallet", &sethdseed},
    1158                 :             :         {"wallet", &setlabel},
    1159                 :             :         {"wallet", &settxfee},
    1160                 :             :         {"wallet", &setwalletflag},
    1161                 :             :         {"wallet", &signmessage},
    1162                 :             :         {"wallet", &signrawtransactionwithwallet},
    1163                 :             :         {"wallet", &simulaterawtransaction},
    1164                 :             :         {"wallet", &sendall},
    1165                 :             :         {"wallet", &unloadwallet},
    1166                 :             :         {"wallet", &upgradewallet},
    1167                 :             :         {"wallet", &walletcreatefundedpsbt},
    1168                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
    1169                 :             :         {"wallet", &walletdisplayaddress},
    1170                 :             : #endif // ENABLE_EXTERNAL_SIGNER
    1171                 :             :         {"wallet", &walletlock},
    1172                 :             :         {"wallet", &walletpassphrase},
    1173                 :             :         {"wallet", &walletpassphrasechange},
    1174                 :             :         {"wallet", &walletprocesspsbt},
    1175   [ +  +  +  -  :          18 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  -  - ]
    1176                 :          18 :     return commands;
    1177                 :             : }
    1178                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1