LCOV - code coverage report
Current view: top level - src/wallet/rpc - backup.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 1359 1507 90.2 %
Date: 2022-04-21 14:51:19 Functions: 39 39 100.0 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 520 638 81.5 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2009-2021 The Bitcoin Core developers
#       2                 :            : // Distributed under the MIT software license, see the accompanying
#       3                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#       4                 :            : 
#       5                 :            : #include <chain.h>
#       6                 :            : #include <clientversion.h>
#       7                 :            : #include <core_io.h>
#       8                 :            : #include <fs.h>
#       9                 :            : #include <interfaces/chain.h>
#      10                 :            : #include <key_io.h>
#      11                 :            : #include <merkleblock.h>
#      12                 :            : #include <rpc/util.h>
#      13                 :            : #include <script/descriptor.h>
#      14                 :            : #include <script/script.h>
#      15                 :            : #include <script/standard.h>
#      16                 :            : #include <sync.h>
#      17                 :            : #include <util/bip32.h>
#      18                 :            : #include <util/system.h>
#      19                 :            : #include <util/time.h>
#      20                 :            : #include <util/translation.h>
#      21                 :            : #include <wallet/rpc/util.h>
#      22                 :            : #include <wallet/wallet.h>
#      23                 :            : 
#      24                 :            : #include <cstdint>
#      25                 :            : #include <fstream>
#      26                 :            : #include <tuple>
#      27                 :            : #include <string>
#      28                 :            : 
#      29                 :            : #include <boost/algorithm/string.hpp>
#      30                 :            : 
#      31                 :            : #include <univalue.h>
#      32                 :            : 
#      33                 :            : 
#      34                 :            : 
#      35                 :            : using interfaces::FoundBlock;
#      36                 :            : 
#      37                 :            : namespace wallet {
#      38                 :         88 : std::string static EncodeDumpString(const std::string &str) {
#      39                 :         88 :     std::stringstream ret;
#      40         [ +  + ]:        117 :     for (const unsigned char c : str) {
#      41 [ -  + ][ -  + ]:        117 :         if (c <= 32 || c >= 128 || c == '%') {
#                 [ -  + ]
#      42                 :          0 :             ret << '%' << HexStr({&c, 1});
#      43                 :        117 :         } else {
#      44                 :        117 :             ret << c;
#      45                 :        117 :         }
#      46                 :        117 :     }
#      47                 :         88 :     return ret.str();
#      48                 :         88 : }
#      49                 :            : 
#      50                 :         48 : static std::string DecodeDumpString(const std::string &str) {
#      51                 :         48 :     std::stringstream ret;
#      52         [ +  + ]:         72 :     for (unsigned int pos = 0; pos < str.length(); pos++) {
#      53                 :         24 :         unsigned char c = str[pos];
#      54 [ -  + ][ #  # ]:         24 :         if (c == '%' && pos+2 < str.length()) {
#      55                 :          0 :             c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
#      56                 :          0 :                 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
#      57                 :          0 :             pos += 2;
#      58                 :          0 :         }
#      59                 :         24 :         ret << c;
#      60                 :         24 :     }
#      61                 :         48 :     return ret.str();
#      62                 :         48 : }
#      63                 :            : 
#      64                 :            : static bool GetWalletAddressesForKey(const LegacyScriptPubKeyMan* spk_man, const CWallet& wallet, const CKeyID& keyid, std::string& strAddr, std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
#      65                 :       1435 : {
#      66                 :       1435 :     bool fLabelFound = false;
#      67                 :       1435 :     CKey key;
#      68                 :       1435 :     spk_man->GetKey(keyid, key);
#      69         [ +  + ]:       4305 :     for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) {
#      70                 :       4305 :         const auto* address_book_entry = wallet.FindAddressBookEntry(dest);
#      71         [ +  + ]:       4305 :         if (address_book_entry) {
#      72         [ +  + ]:         88 :             if (!strAddr.empty()) {
#      73                 :          8 :                 strAddr += ",";
#      74                 :          8 :             }
#      75                 :         88 :             strAddr += EncodeDestination(dest);
#      76                 :         88 :             strLabel = EncodeDumpString(address_book_entry->GetLabel());
#      77                 :         88 :             fLabelFound = true;
#      78                 :         88 :         }
#      79                 :       4305 :     }
#      80         [ +  + ]:       1435 :     if (!fLabelFound) {
#      81                 :       1355 :         strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), wallet.m_default_address_type));
#      82                 :       1355 :     }
#      83                 :       1435 :     return fLabelFound;
#      84                 :       1435 : }
#      85                 :            : 
#      86                 :            : static const int64_t TIMESTAMP_MIN = 0;
#      87                 :            : 
#      88                 :            : static void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver, int64_t time_begin = TIMESTAMP_MIN, bool update = true)
#      89                 :        232 : {
#      90                 :        232 :     int64_t scanned_time = wallet.RescanFromTime(time_begin, reserver, update);
#      91         [ -  + ]:        232 :     if (wallet.IsAbortingRescan()) {
#      92                 :          0 :         throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user.");
#      93         [ -  + ]:        232 :     } else if (scanned_time > time_begin) {
#      94                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Rescan was unable to fully rescan the blockchain. Some transactions may be missing.");
#      95                 :          0 :     }
#      96                 :        232 : }
#      97                 :            : 
#      98                 :            : RPCHelpMan importprivkey()
#      99                 :       1783 : {
#     100                 :       1783 :     return RPCHelpMan{"importprivkey",
#     101                 :       1783 :                 "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n"
#     102                 :       1783 :                 "Hint: use importmulti to import more than one private key.\n"
#     103                 :       1783 :             "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n"
#     104                 :       1783 :             "may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
#     105                 :       1783 :             "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
#     106                 :       1783 :                 {
#     107                 :       1783 :                     {"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key (see dumpprivkey)"},
#     108                 :       1783 :                     {"label", RPCArg::Type::STR, RPCArg::DefaultHint{"current label if address exists, otherwise \"\""}, "An optional label"},
#     109                 :       1783 :                     {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"},
#     110                 :       1783 :                 },
#     111                 :       1783 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     112                 :       1783 :                 RPCExamples{
#     113                 :       1783 :             "\nDump a private key\n"
#     114                 :       1783 :             + HelpExampleCli("dumpprivkey", "\"myaddress\"") +
#     115                 :       1783 :             "\nImport the private key with rescan\n"
#     116                 :       1783 :             + HelpExampleCli("importprivkey", "\"mykey\"") +
#     117                 :       1783 :             "\nImport using a label and without rescan\n"
#     118                 :       1783 :             + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
#     119                 :       1783 :             "\nImport using default blank label and without rescan\n"
#     120                 :       1783 :             + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
#     121                 :       1783 :             "\nAs a JSON-RPC call\n"
#     122                 :       1783 :             + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
#     123                 :       1783 :                 },
#     124                 :       1783 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     125                 :       1783 : {
#     126                 :        199 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     127         [ -  + ]:        199 :     if (!pwallet) return NullUniValue;
#     128                 :            : 
#     129         [ +  + ]:        199 :     if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#     130                 :          2 :         throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
#     131                 :          2 :     }
#     132                 :            : 
#     133                 :        197 :     EnsureLegacyScriptPubKeyMan(*pwallet, true);
#     134                 :            : 
#     135                 :        197 :     WalletRescanReserver reserver(*pwallet);
#     136                 :        197 :     bool fRescan = true;
#     137                 :        197 :     {
#     138                 :        197 :         LOCK(pwallet->cs_wallet);
#     139                 :            : 
#     140                 :        197 :         EnsureWalletIsUnlocked(*pwallet);
#     141                 :            : 
#     142                 :        197 :         std::string strSecret = request.params[0].get_str();
#     143                 :        197 :         std::string strLabel = "";
#     144         [ +  + ]:        197 :         if (!request.params[1].isNull())
#     145                 :        164 :             strLabel = request.params[1].get_str();
#     146                 :            : 
#     147                 :            :         // Whether to perform rescan after import
#     148         [ +  + ]:        197 :         if (!request.params[2].isNull())
#     149                 :        161 :             fRescan = request.params[2].get_bool();
#     150                 :            : 
#     151 [ +  + ][ -  + ]:        197 :         if (fRescan && pwallet->chain().havePruned()) {
#     152                 :            :             // Exit early and print an error.
#     153                 :            :             // If a block is pruned after this check, we will import the key(s),
#     154                 :            :             // but fail the rescan with a generic error.
#     155                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned");
#     156                 :          0 :         }
#     157                 :            : 
#     158 [ +  + ][ -  + ]:        197 :         if (fRescan && !reserver.reserve()) {
#     159                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#     160                 :          0 :         }
#     161                 :            : 
#     162                 :        197 :         CKey key = DecodeSecret(strSecret);
#     163         [ +  + ]:        197 :         if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
#     164                 :            : 
#     165                 :        196 :         CPubKey pubkey = key.GetPubKey();
#     166         [ -  + ]:        196 :         CHECK_NONFATAL(key.VerifyPubKey(pubkey));
#     167                 :        196 :         CKeyID vchAddress = pubkey.GetID();
#     168                 :        196 :         {
#     169                 :        196 :             pwallet->MarkDirty();
#     170                 :            : 
#     171                 :            :             // We don't know which corresponding address will be used;
#     172                 :            :             // label all new addresses, and label existing addresses if a
#     173                 :            :             // label was passed.
#     174         [ +  + ]:        579 :             for (const auto& dest : GetAllDestinationsForKey(pubkey)) {
#     175 [ +  + ][ +  + ]:        579 :                 if (!request.params[1].isNull() || !pwallet->FindAddressBookEntry(dest)) {
#     176                 :        566 :                     pwallet->SetAddressBook(dest, strLabel, "receive");
#     177                 :        566 :                 }
#     178                 :        579 :             }
#     179                 :            : 
#     180                 :            :             // Use timestamp of 1 to scan the whole chain
#     181         [ -  + ]:        196 :             if (!pwallet->ImportPrivKeys({{vchAddress, key}}, 1)) {
#     182                 :          0 :                 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
#     183                 :          0 :             }
#     184                 :            : 
#     185                 :            :             // Add the wpkh script for this key if possible
#     186         [ +  + ]:        196 :             if (pubkey.IsCompressed()) {
#     187                 :        192 :                 pwallet->ImportScripts({GetScriptForDestination(WitnessV0KeyHash(vchAddress))}, 0 /* timestamp */);
#     188                 :        192 :             }
#     189                 :        196 :         }
#     190                 :        196 :     }
#     191         [ +  + ]:        196 :     if (fRescan) {
#     192                 :        182 :         RescanWallet(*pwallet, reserver);
#     193                 :        182 :     }
#     194                 :            : 
#     195                 :        196 :     return NullUniValue;
#     196                 :        196 : },
#     197                 :       1783 :     };
#     198                 :       1783 : }
#     199                 :            : 
#     200                 :            : RPCHelpMan importaddress()
#     201                 :       1673 : {
#     202                 :       1673 :     return RPCHelpMan{"importaddress",
#     203                 :       1673 :                 "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
#     204                 :       1673 :             "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n"
#     205                 :       1673 :             "may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
#     206                 :       1673 :             "If you have the full public key, you should call importpubkey instead of this.\n"
#     207                 :       1673 :             "Hint: use importmulti to import more than one address.\n"
#     208                 :       1673 :             "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
#     209                 :       1673 :             "as change, and not show up in many RPCs.\n"
#     210                 :       1673 :             "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
#     211                 :       1673 :                 {
#     212                 :       1673 :                     {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Bitcoin address (or hex-encoded script)"},
#     213                 :       1673 :                     {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"},
#     214                 :       1673 :                     {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"},
#     215                 :       1673 :                     {"p2sh", RPCArg::Type::BOOL, RPCArg::Default{false}, "Add the P2SH version of the script as well"},
#     216                 :       1673 :                 },
#     217                 :       1673 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     218                 :       1673 :                 RPCExamples{
#     219                 :       1673 :             "\nImport an address with rescan\n"
#     220                 :       1673 :             + HelpExampleCli("importaddress", "\"myaddress\"") +
#     221                 :       1673 :             "\nImport using a label without rescan\n"
#     222                 :       1673 :             + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") +
#     223                 :       1673 :             "\nAs a JSON-RPC call\n"
#     224                 :       1673 :             + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")
#     225                 :       1673 :                 },
#     226                 :       1673 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     227                 :       1673 : {
#     228                 :         89 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     229         [ -  + ]:         89 :     if (!pwallet) return NullUniValue;
#     230                 :            : 
#     231                 :         89 :     EnsureLegacyScriptPubKeyMan(*pwallet, true);
#     232                 :            : 
#     233                 :         89 :     std::string strLabel;
#     234         [ +  + ]:         89 :     if (!request.params[1].isNull())
#     235                 :         66 :         strLabel = request.params[1].get_str();
#     236                 :            : 
#     237                 :            :     // Whether to perform rescan after import
#     238                 :         89 :     bool fRescan = true;
#     239         [ +  + ]:         89 :     if (!request.params[2].isNull())
#     240                 :         67 :         fRescan = request.params[2].get_bool();
#     241                 :            : 
#     242 [ +  + ][ -  + ]:         89 :     if (fRescan && pwallet->chain().havePruned()) {
#     243                 :            :         // Exit early and print an error.
#     244                 :            :         // If a block is pruned after this check, we will import the key(s),
#     245                 :            :         // but fail the rescan with a generic error.
#     246                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned");
#     247                 :          0 :     }
#     248                 :            : 
#     249                 :         89 :     WalletRescanReserver reserver(*pwallet);
#     250 [ +  + ][ -  + ]:         89 :     if (fRescan && !reserver.reserve()) {
#     251                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#     252                 :          0 :     }
#     253                 :            : 
#     254                 :            :     // Whether to import a p2sh version, too
#     255                 :         89 :     bool fP2SH = false;
#     256         [ +  + ]:         89 :     if (!request.params[3].isNull())
#     257                 :         43 :         fP2SH = request.params[3].get_bool();
#     258                 :            : 
#     259                 :         89 :     {
#     260                 :         89 :         LOCK(pwallet->cs_wallet);
#     261                 :            : 
#     262                 :         89 :         CTxDestination dest = DecodeDestination(request.params[0].get_str());
#     263         [ +  + ]:         89 :         if (IsValidDestination(dest)) {
#     264         [ +  + ]:         43 :             if (fP2SH) {
#     265                 :          1 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
#     266                 :          1 :             }
#     267         [ +  + ]:         42 :             if (OutputTypeFromDestination(dest) == OutputType::BECH32M) {
#     268                 :          1 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets");
#     269                 :          1 :             }
#     270                 :            : 
#     271                 :         41 :             pwallet->MarkDirty();
#     272                 :            : 
#     273                 :         41 :             pwallet->ImportScriptPubKeys(strLabel, {GetScriptForDestination(dest)}, false /* have_solving_data */, true /* apply_label */, 1 /* timestamp */);
#     274         [ +  + ]:         46 :         } else if (IsHex(request.params[0].get_str())) {
#     275                 :         44 :             std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
#     276                 :         44 :             CScript redeem_script(data.begin(), data.end());
#     277                 :            : 
#     278                 :         44 :             std::set<CScript> scripts = {redeem_script};
#     279                 :         44 :             pwallet->ImportScripts(scripts, 0 /* timestamp */);
#     280                 :            : 
#     281         [ +  + ]:         44 :             if (fP2SH) {
#     282                 :         42 :                 scripts.insert(GetScriptForDestination(ScriptHash(redeem_script)));
#     283                 :         42 :             }
#     284                 :            : 
#     285                 :         44 :             pwallet->ImportScriptPubKeys(strLabel, scripts, false /* have_solving_data */, true /* apply_label */, 1 /* timestamp */);
#     286                 :         44 :         } else {
#     287                 :          2 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script");
#     288                 :          2 :         }
#     289                 :         89 :     }
#     290         [ +  + ]:         85 :     if (fRescan)
#     291                 :         25 :     {
#     292                 :         25 :         RescanWallet(*pwallet, reserver);
#     293                 :         25 :         {
#     294                 :         25 :             LOCK(pwallet->cs_wallet);
#     295                 :         25 :             pwallet->ReacceptWalletTransactions();
#     296                 :         25 :         }
#     297                 :         25 :     }
#     298                 :            : 
#     299                 :         85 :     return NullUniValue;
#     300                 :         89 : },
#     301                 :       1673 :     };
#     302                 :       1673 : }
#     303                 :            : 
#     304                 :            : RPCHelpMan importprunedfunds()
#     305                 :       1598 : {
#     306                 :       1598 :     return RPCHelpMan{"importprunedfunds",
#     307                 :       1598 :                 "\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n",
#     308                 :       1598 :                 {
#     309                 :       1598 :                     {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"},
#     310                 :       1598 :                     {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"},
#     311                 :       1598 :                 },
#     312                 :       1598 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     313                 :       1598 :                 RPCExamples{""},
#     314                 :       1598 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     315                 :       1598 : {
#     316                 :         14 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     317         [ -  + ]:         14 :     if (!pwallet) return NullUniValue;
#     318                 :            : 
#     319                 :         14 :     CMutableTransaction tx;
#     320         [ +  + ]:         14 :     if (!DecodeHexTx(tx, request.params[0].get_str())) {
#     321                 :          2 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
#     322                 :          2 :     }
#     323                 :         12 :     uint256 hashTx = tx.GetHash();
#     324                 :            : 
#     325                 :         12 :     CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
#     326                 :         12 :     CMerkleBlock merkleBlock;
#     327                 :         12 :     ssMB >> merkleBlock;
#     328                 :            : 
#     329                 :            :     //Search partial merkle tree in proof for our transaction and index in valid block
#     330                 :         12 :     std::vector<uint256> vMatch;
#     331                 :         12 :     std::vector<unsigned int> vIndex;
#     332         [ +  + ]:         12 :     if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) {
#     333                 :          2 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
#     334                 :          2 :     }
#     335                 :            : 
#     336                 :         10 :     LOCK(pwallet->cs_wallet);
#     337                 :         10 :     int height;
#     338         [ +  + ]:         10 :     if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) {
#     339                 :          2 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
#     340                 :          2 :     }
#     341                 :            : 
#     342                 :          8 :     std::vector<uint256>::const_iterator it;
#     343         [ +  + ]:          8 :     if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx)) == vMatch.end()) {
#     344                 :          2 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
#     345                 :          2 :     }
#     346                 :            : 
#     347                 :          6 :     unsigned int txnIndex = vIndex[it - vMatch.begin()];
#     348                 :            : 
#     349                 :          6 :     CTransactionRef tx_ref = MakeTransactionRef(tx);
#     350         [ +  + ]:          6 :     if (pwallet->IsMine(*tx_ref)) {
#     351                 :          4 :         pwallet->AddToWallet(std::move(tx_ref), TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)});
#     352                 :          4 :         return NullUniValue;
#     353                 :          4 :     }
#     354                 :            : 
#     355                 :          2 :     throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
#     356                 :          6 : },
#     357                 :       1598 :     };
#     358                 :       1598 : }
#     359                 :            : 
#     360                 :            : RPCHelpMan removeprunedfunds()
#     361                 :       1590 : {
#     362                 :       1590 :     return RPCHelpMan{"removeprunedfunds",
#     363                 :       1590 :                 "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n",
#     364                 :       1590 :                 {
#     365                 :       1590 :                     {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded id of the transaction you are deleting"},
#     366                 :       1590 :                 },
#     367                 :       1590 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     368                 :       1590 :                 RPCExamples{
#     369                 :       1590 :                     HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
#     370                 :       1590 :             "\nAs a JSON-RPC call\n"
#     371                 :       1590 :             + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
#     372                 :       1590 :                 },
#     373                 :       1590 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     374                 :       1590 : {
#     375                 :          6 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     376         [ -  + ]:          6 :     if (!pwallet) return NullUniValue;
#     377                 :            : 
#     378                 :          6 :     LOCK(pwallet->cs_wallet);
#     379                 :            : 
#     380                 :          6 :     uint256 hash(ParseHashV(request.params[0], "txid"));
#     381                 :          6 :     std::vector<uint256> vHash;
#     382                 :          6 :     vHash.push_back(hash);
#     383                 :          6 :     std::vector<uint256> vHashOut;
#     384                 :            : 
#     385         [ -  + ]:          6 :     if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) {
#     386                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
#     387                 :          0 :     }
#     388                 :            : 
#     389         [ +  + ]:          6 :     if(vHashOut.empty()) {
#     390                 :          2 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet.");
#     391                 :          2 :     }
#     392                 :            : 
#     393                 :          4 :     return NullUniValue;
#     394                 :          6 : },
#     395                 :       1590 :     };
#     396                 :       1590 : }
#     397                 :            : 
#     398                 :            : RPCHelpMan importpubkey()
#     399                 :       1619 : {
#     400                 :       1619 :     return RPCHelpMan{"importpubkey",
#     401                 :       1619 :                 "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
#     402                 :       1619 :                 "Hint: use importmulti to import more than one public key.\n"
#     403                 :       1619 :             "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n"
#     404                 :       1619 :             "may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
#     405                 :       1619 :             "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
#     406                 :       1619 :                 {
#     407                 :       1619 :                     {"pubkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The hex-encoded public key"},
#     408                 :       1619 :                     {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"},
#     409                 :       1619 :                     {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"},
#     410                 :       1619 :                 },
#     411                 :       1619 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     412                 :       1619 :                 RPCExamples{
#     413                 :       1619 :             "\nImport a public key with rescan\n"
#     414                 :       1619 :             + HelpExampleCli("importpubkey", "\"mypubkey\"") +
#     415                 :       1619 :             "\nImport using a label without rescan\n"
#     416                 :       1619 :             + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
#     417                 :       1619 :             "\nAs a JSON-RPC call\n"
#     418                 :       1619 :             + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
#     419                 :       1619 :                 },
#     420                 :       1619 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     421                 :       1619 : {
#     422                 :         35 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     423         [ -  + ]:         35 :     if (!pwallet) return NullUniValue;
#     424                 :            : 
#     425                 :         35 :     EnsureLegacyScriptPubKeyMan(*pwallet, true);
#     426                 :            : 
#     427                 :         35 :     std::string strLabel;
#     428         [ +  + ]:         35 :     if (!request.params[1].isNull())
#     429                 :         23 :         strLabel = request.params[1].get_str();
#     430                 :            : 
#     431                 :            :     // Whether to perform rescan after import
#     432                 :         35 :     bool fRescan = true;
#     433         [ +  + ]:         35 :     if (!request.params[2].isNull())
#     434                 :         19 :         fRescan = request.params[2].get_bool();
#     435                 :            : 
#     436 [ +  + ][ -  + ]:         35 :     if (fRescan && pwallet->chain().havePruned()) {
#     437                 :            :         // Exit early and print an error.
#     438                 :            :         // If a block is pruned after this check, we will import the key(s),
#     439                 :            :         // but fail the rescan with a generic error.
#     440                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned");
#     441                 :          0 :     }
#     442                 :            : 
#     443                 :         35 :     WalletRescanReserver reserver(*pwallet);
#     444 [ +  + ][ -  + ]:         35 :     if (fRescan && !reserver.reserve()) {
#     445                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#     446                 :          0 :     }
#     447                 :            : 
#     448         [ +  + ]:         35 :     if (!IsHex(request.params[0].get_str()))
#     449                 :          1 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
#     450                 :         34 :     std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
#     451                 :         34 :     CPubKey pubKey(data);
#     452         [ +  + ]:         34 :     if (!pubKey.IsFullyValid())
#     453                 :          1 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
#     454                 :            : 
#     455                 :         33 :     {
#     456                 :         33 :         LOCK(pwallet->cs_wallet);
#     457                 :            : 
#     458                 :         33 :         std::set<CScript> script_pub_keys;
#     459         [ +  + ]:         92 :         for (const auto& dest : GetAllDestinationsForKey(pubKey)) {
#     460                 :         92 :             script_pub_keys.insert(GetScriptForDestination(dest));
#     461                 :         92 :         }
#     462                 :            : 
#     463                 :         33 :         pwallet->MarkDirty();
#     464                 :            : 
#     465                 :         33 :         pwallet->ImportScriptPubKeys(strLabel, script_pub_keys, true /* have_solving_data */, true /* apply_label */, 1 /* timestamp */);
#     466                 :            : 
#     467                 :         33 :         pwallet->ImportPubKeys({pubKey.GetID()}, {{pubKey.GetID(), pubKey}} , {} /* key_origins */, false /* add_keypool */, false /* internal */, 1 /* timestamp */);
#     468                 :         33 :     }
#     469         [ +  + ]:         33 :     if (fRescan)
#     470                 :         20 :     {
#     471                 :         20 :         RescanWallet(*pwallet, reserver);
#     472                 :         20 :         {
#     473                 :         20 :             LOCK(pwallet->cs_wallet);
#     474                 :         20 :             pwallet->ReacceptWalletTransactions();
#     475                 :         20 :         }
#     476                 :         20 :     }
#     477                 :            : 
#     478                 :         33 :     return NullUniValue;
#     479                 :         34 : },
#     480                 :       1619 :     };
#     481                 :       1619 : }
#     482                 :            : 
#     483                 :            : 
#     484                 :            : RPCHelpMan importwallet()
#     485                 :       1590 : {
#     486                 :       1590 :     return RPCHelpMan{"importwallet",
#     487                 :       1590 :                 "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n"
#     488                 :       1590 :                 "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
#     489                 :       1590 :                 {
#     490                 :       1590 :                     {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet file"},
#     491                 :       1590 :                 },
#     492                 :       1590 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#     493                 :       1590 :                 RPCExamples{
#     494                 :       1590 :             "\nDump the wallet\n"
#     495                 :       1590 :             + HelpExampleCli("dumpwallet", "\"test\"") +
#     496                 :       1590 :             "\nImport the wallet\n"
#     497                 :       1590 :             + HelpExampleCli("importwallet", "\"test\"") +
#     498                 :       1590 :             "\nImport using the json rpc call\n"
#     499                 :       1590 :             + HelpExampleRpc("importwallet", "\"test\"")
#     500                 :       1590 :                 },
#     501                 :       1590 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     502                 :       1590 : {
#     503                 :          6 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
#     504         [ -  + ]:          6 :     if (!pwallet) return NullUniValue;
#     505                 :            : 
#     506                 :          6 :     EnsureLegacyScriptPubKeyMan(*pwallet, true);
#     507                 :            : 
#     508         [ -  + ]:          6 :     if (pwallet->chain().havePruned()) {
#     509                 :            :         // Exit early and print an error.
#     510                 :            :         // If a block is pruned after this check, we will import the key(s),
#     511                 :            :         // but fail the rescan with a generic error.
#     512                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled when blocks are pruned");
#     513                 :          0 :     }
#     514                 :            : 
#     515                 :          6 :     WalletRescanReserver reserver(*pwallet);
#     516         [ -  + ]:          6 :     if (!reserver.reserve()) {
#     517                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#     518                 :          0 :     }
#     519                 :            : 
#     520                 :          6 :     int64_t nTimeBegin = 0;
#     521                 :          6 :     bool fGood = true;
#     522                 :          6 :     {
#     523                 :          6 :         LOCK(pwallet->cs_wallet);
#     524                 :            : 
#     525                 :          6 :         EnsureWalletIsUnlocked(*pwallet);
#     526                 :            : 
#     527                 :          6 :         std::ifstream file;
#     528                 :          6 :         file.open(fs::u8path(request.params[0].get_str()), std::ios::in | std::ios::ate);
#     529         [ -  + ]:          6 :         if (!file.is_open()) {
#     530                 :          0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
#     531                 :          0 :         }
#     532         [ -  + ]:          6 :         CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nTimeBegin)));
#     533                 :            : 
#     534                 :          6 :         int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
#     535                 :          6 :         file.seekg(0, file.beg);
#     536                 :            : 
#     537                 :            :         // Use uiInterface.ShowProgress instead of pwallet.ShowProgress because pwallet.ShowProgress has a cancel button tied to AbortRescan which
#     538                 :            :         // we don't want for this progress bar showing the import progress. uiInterface.ShowProgress does not have a cancel button.
#     539                 :          6 :         pwallet->chain().showProgress(strprintf("%s " + _("Importing…").translated, pwallet->GetDisplayName()), 0, false); // show progress dialog in GUI
#     540                 :          6 :         std::vector<std::tuple<CKey, int64_t, bool, std::string>> keys;
#     541                 :          6 :         std::vector<std::pair<CScript, int64_t>> scripts;
#     542         [ +  + ]:       1776 :         while (file.good()) {
#     543                 :       1770 :             pwallet->chain().showProgress("", std::max(1, std::min(50, (int)(((double)file.tellg() / (double)nFilesize) * 100))), false);
#     544                 :       1770 :             std::string line;
#     545                 :       1770 :             std::getline(file, line);
#     546 [ +  + ][ +  + ]:       1770 :             if (line.empty() || line[0] == '#')
#     547                 :         53 :                 continue;
#     548                 :            : 
#     549                 :       1717 :             std::vector<std::string> vstr;
#     550                 :       1717 :             boost::split(vstr, line, boost::is_any_of(" "));
#     551         [ -  + ]:       1717 :             if (vstr.size() < 2)
#     552                 :          0 :                 continue;
#     553                 :       1717 :             CKey key = DecodeSecret(vstr[0]);
#     554         [ +  + ]:       1717 :             if (key.IsValid()) {
#     555                 :        858 :                 int64_t nTime = ParseISO8601DateTime(vstr[1]);
#     556                 :        858 :                 std::string strLabel;
#     557                 :        858 :                 bool fLabel = true;
#     558         [ +  - ]:       1716 :                 for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
#     559         [ +  + ]:       1716 :                     if (vstr[nStr].front() == '#')
#     560                 :        858 :                         break;
#     561         [ +  + ]:        858 :                     if (vstr[nStr] == "change=1")
#     562                 :         29 :                         fLabel = false;
#     563         [ +  + ]:        858 :                     if (vstr[nStr] == "reserve=1")
#     564                 :        777 :                         fLabel = false;
#     565         [ +  + ]:        858 :                     if (vstr[nStr].substr(0,6) == "label=") {
#     566                 :         48 :                         strLabel = DecodeDumpString(vstr[nStr].substr(6));
#     567                 :         48 :                         fLabel = true;
#     568                 :         48 :                     }
#     569                 :        858 :                 }
#     570                 :        858 :                 keys.push_back(std::make_tuple(key, nTime, fLabel, strLabel));
#     571         [ +  - ]:        859 :             } else if(IsHex(vstr[0])) {
#     572                 :        859 :                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
#     573                 :        859 :                 CScript script = CScript(vData.begin(), vData.end());
#     574                 :        859 :                 int64_t birth_time = ParseISO8601DateTime(vstr[1]);
#     575                 :        859 :                 scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));
#     576                 :        859 :             }
#     577                 :       1717 :         }
#     578                 :          6 :         file.close();
#     579                 :            :         // We now know whether we are importing private keys, so we can error if private keys are disabled
#     580 [ +  + ][ -  + ]:          6 :         if (keys.size() > 0 && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#     581                 :          0 :             pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI
#     582                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled when private keys are disabled");
#     583                 :          0 :         }
#     584                 :          6 :         double total = (double)(keys.size() + scripts.size());
#     585                 :          6 :         double progress = 0;
#     586         [ +  + ]:        858 :         for (const auto& key_tuple : keys) {
#     587                 :        858 :             pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false);
#     588                 :        858 :             const CKey& key = std::get<0>(key_tuple);
#     589                 :        858 :             int64_t time = std::get<1>(key_tuple);
#     590                 :        858 :             bool has_label = std::get<2>(key_tuple);
#     591                 :        858 :             std::string label = std::get<3>(key_tuple);
#     592                 :            : 
#     593                 :        858 :             CPubKey pubkey = key.GetPubKey();
#     594         [ -  + ]:        858 :             CHECK_NONFATAL(key.VerifyPubKey(pubkey));
#     595                 :        858 :             CKeyID keyid = pubkey.GetID();
#     596                 :            : 
#     597                 :        858 :             pwallet->WalletLogPrintf("Importing %s...\n", EncodeDestination(PKHash(keyid)));
#     598                 :            : 
#     599         [ -  + ]:        858 :             if (!pwallet->ImportPrivKeys({{keyid, key}}, time)) {
#     600                 :          0 :                 pwallet->WalletLogPrintf("Error importing key for %s\n", EncodeDestination(PKHash(keyid)));
#     601                 :          0 :                 fGood = false;
#     602                 :          0 :                 continue;
#     603                 :          0 :             }
#     604                 :            : 
#     605         [ +  + ]:        858 :             if (has_label)
#     606                 :         52 :                 pwallet->SetAddressBook(PKHash(keyid), label, "receive");
#     607                 :            : 
#     608                 :        858 :             nTimeBegin = std::min(nTimeBegin, time);
#     609                 :        858 :             progress++;
#     610                 :        858 :         }
#     611         [ +  + ]:        859 :         for (const auto& script_pair : scripts) {
#     612                 :        859 :             pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false);
#     613                 :        859 :             const CScript& script = script_pair.first;
#     614                 :        859 :             int64_t time = script_pair.second;
#     615                 :            : 
#     616         [ -  + ]:        859 :             if (!pwallet->ImportScripts({script}, time)) {
#     617                 :          0 :                 pwallet->WalletLogPrintf("Error importing script %s\n", HexStr(script));
#     618                 :          0 :                 fGood = false;
#     619                 :          0 :                 continue;
#     620                 :          0 :             }
#     621         [ -  + ]:        859 :             if (time > 0) {
#     622                 :          0 :                 nTimeBegin = std::min(nTimeBegin, time);
#     623                 :          0 :             }
#     624                 :            : 
#     625                 :        859 :             progress++;
#     626                 :        859 :         }
#     627                 :          6 :         pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI
#     628                 :          6 :     }
#     629                 :          0 :     pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI
#     630                 :          6 :     RescanWallet(*pwallet, reserver, nTimeBegin, false /* update */);
#     631                 :          6 :     pwallet->MarkDirty();
#     632                 :            : 
#     633         [ -  + ]:          6 :     if (!fGood)
#     634                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet");
#     635                 :            : 
#     636                 :          6 :     return NullUniValue;
#     637                 :          6 : },
#     638                 :       1590 :     };
#     639                 :       1590 : }
#     640                 :            : 
#     641                 :            : RPCHelpMan dumpprivkey()
#     642                 :       1808 : {
#     643                 :       1808 :     return RPCHelpMan{"dumpprivkey",
#     644                 :       1808 :                 "\nReveals the private key corresponding to 'address'.\n"
#     645                 :       1808 :                 "Then the importprivkey can be used with this output\n",
#     646                 :       1808 :                 {
#     647                 :       1808 :                     {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for the private key"},
#     648                 :       1808 :                 },
#     649                 :       1808 :                 RPCResult{
#     650                 :       1808 :                     RPCResult::Type::STR, "key", "The private key"
#     651                 :       1808 :                 },
#     652                 :       1808 :                 RPCExamples{
#     653                 :       1808 :                     HelpExampleCli("dumpprivkey", "\"myaddress\"")
#     654                 :       1808 :             + HelpExampleCli("importprivkey", "\"mykey\"")
#     655                 :       1808 :             + HelpExampleRpc("dumpprivkey", "\"myaddress\"")
#     656                 :       1808 :                 },
#     657                 :       1808 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     658                 :       1808 : {
#     659                 :        224 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
#     660         [ -  + ]:        224 :     if (!pwallet) return NullUniValue;
#     661                 :            : 
#     662                 :        224 :     const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(*pwallet);
#     663                 :            : 
#     664                 :        224 :     LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
#     665                 :            : 
#     666                 :        224 :     EnsureWalletIsUnlocked(*pwallet);
#     667                 :            : 
#     668                 :        224 :     std::string strAddress = request.params[0].get_str();
#     669                 :        224 :     CTxDestination dest = DecodeDestination(strAddress);
#     670         [ +  + ]:        224 :     if (!IsValidDestination(dest)) {
#     671                 :          1 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
#     672                 :          1 :     }
#     673                 :        223 :     auto keyid = GetKeyForDestination(spk_man, dest);
#     674         [ +  + ]:        223 :     if (keyid.IsNull()) {
#     675                 :          1 :         throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
#     676                 :          1 :     }
#     677                 :        222 :     CKey vchSecret;
#     678         [ -  + ]:        222 :     if (!spk_man.GetKey(keyid, vchSecret)) {
#     679                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
#     680                 :          0 :     }
#     681                 :        222 :     return EncodeSecret(vchSecret);
#     682                 :        222 : },
#     683                 :       1808 :     };
#     684                 :       1808 : }
#     685                 :            : 
#     686                 :            : 
#     687                 :            : RPCHelpMan dumpwallet()
#     688                 :       1593 : {
#     689                 :       1593 :     return RPCHelpMan{"dumpwallet",
#     690                 :       1593 :                 "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n"
#     691                 :       1593 :                 "Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n"
#     692                 :       1593 :                 "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n"
#     693                 :       1593 :                 "only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n",
#     694                 :       1593 :                 {
#     695                 :       1593 :                     {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The filename with path (absolute path recommended)"},
#     696                 :       1593 :                 },
#     697                 :       1593 :                 RPCResult{
#     698                 :       1593 :                     RPCResult::Type::OBJ, "", "",
#     699                 :       1593 :                     {
#     700                 :       1593 :                         {RPCResult::Type::STR, "filename", "The filename with full absolute path"},
#     701                 :       1593 :                     }
#     702                 :       1593 :                 },
#     703                 :       1593 :                 RPCExamples{
#     704                 :       1593 :                     HelpExampleCli("dumpwallet", "\"test\"")
#     705                 :       1593 :             + HelpExampleRpc("dumpwallet", "\"test\"")
#     706                 :       1593 :                 },
#     707                 :       1593 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#     708                 :       1593 : {
#     709                 :          9 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
#     710         [ -  + ]:          9 :     if (!pwallet) return NullUniValue;
#     711                 :            : 
#     712                 :          9 :     const CWallet& wallet = *pwallet;
#     713                 :          9 :     const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(wallet);
#     714                 :            : 
#     715                 :            :     // Make sure the results are valid at least up to the most recent block
#     716                 :            :     // the user could have gotten from another RPC command prior to now
#     717                 :          9 :     wallet.BlockUntilSyncedToCurrentChain();
#     718                 :            : 
#     719                 :          9 :     LOCK(wallet.cs_wallet);
#     720                 :            : 
#     721                 :          9 :     EnsureWalletIsUnlocked(wallet);
#     722                 :            : 
#     723                 :          9 :     fs::path filepath = fs::u8path(request.params[0].get_str());
#     724                 :          9 :     filepath = fs::absolute(filepath);
#     725                 :            : 
#     726                 :            :     /* Prevent arbitrary files from being overwritten. There have been reports
#     727                 :            :      * that users have overwritten wallet files this way:
#     728                 :            :      * https://github.com/bitcoin/bitcoin/issues/9934
#     729                 :            :      * It may also avoid other security issues.
#     730                 :            :      */
#     731         [ +  + ]:          9 :     if (fs::exists(filepath)) {
#     732                 :          1 :         throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.u8string() + " already exists. If you are sure this is what you want, move it out of the way first");
#     733                 :          1 :     }
#     734                 :            : 
#     735                 :          8 :     std::ofstream file;
#     736                 :          8 :     file.open(filepath);
#     737         [ -  + ]:          8 :     if (!file.is_open())
#     738                 :          0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
#     739                 :            : 
#     740                 :          8 :     std::map<CKeyID, int64_t> mapKeyBirth;
#     741                 :          8 :     wallet.GetKeyBirthTimes(mapKeyBirth);
#     742                 :            : 
#     743                 :          8 :     int64_t block_time = 0;
#     744         [ -  + ]:          8 :     CHECK_NONFATAL(wallet.chain().findBlock(wallet.GetLastBlockHash(), FoundBlock().time(block_time)));
#     745                 :            : 
#     746                 :            :     // Note: To avoid a lock order issue, access to cs_main must be locked before cs_KeyStore.
#     747                 :            :     // So we do the two things in this function that lock cs_main first: GetKeyBirthTimes, and findBlock.
#     748                 :          8 :     LOCK(spk_man.cs_KeyStore);
#     749                 :            : 
#     750                 :          8 :     const std::map<CKeyID, int64_t>& mapKeyPool = spk_man.GetAllReserveKeys();
#     751                 :          8 :     std::set<CScriptID> scripts = spk_man.GetCScripts();
#     752                 :            : 
#     753                 :            :     // sort time/key pairs
#     754                 :          8 :     std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
#     755         [ +  + ]:       1435 :     for (const auto& entry : mapKeyBirth) {
#     756                 :       1435 :         vKeyBirth.push_back(std::make_pair(entry.second, entry.first));
#     757                 :       1435 :     }
#     758                 :          8 :     mapKeyBirth.clear();
#     759                 :          8 :     std::sort(vKeyBirth.begin(), vKeyBirth.end());
#     760                 :            : 
#     761                 :            :     // produce output
#     762                 :          8 :     file << strprintf("# Wallet dump created by %s %s\n", PACKAGE_NAME, FormatFullVersion());
#     763                 :          8 :     file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime()));
#     764                 :          8 :     file << strprintf("# * Best block at time of backup was %i (%s),\n", wallet.GetLastBlockHeight(), wallet.GetLastBlockHash().ToString());
#     765                 :          8 :     file << strprintf("#   mined on %s\n", FormatISO8601DateTime(block_time));
#     766                 :          8 :     file << "\n";
#     767                 :            : 
#     768                 :            :     // add the base58check encoded extended master if the wallet uses HD
#     769                 :          8 :     CKeyID seed_id = spk_man.GetHDChain().seed_id;
#     770         [ +  + ]:          8 :     if (!seed_id.IsNull())
#     771                 :          6 :     {
#     772                 :          6 :         CKey seed;
#     773         [ +  - ]:          6 :         if (spk_man.GetKey(seed_id, seed)) {
#     774                 :          6 :             CExtKey masterKey;
#     775                 :          6 :             masterKey.SetSeed(seed);
#     776                 :            : 
#     777                 :          6 :             file << "# extended private masterkey: " << EncodeExtKey(masterKey) << "\n\n";
#     778                 :          6 :         }
#     779                 :          6 :     }
#     780         [ +  + ]:       1443 :     for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
#     781                 :       1435 :         const CKeyID &keyid = it->second;
#     782                 :       1435 :         std::string strTime = FormatISO8601DateTime(it->first);
#     783                 :       1435 :         std::string strAddr;
#     784                 :       1435 :         std::string strLabel;
#     785                 :       1435 :         CKey key;
#     786         [ +  - ]:       1435 :         if (spk_man.GetKey(keyid, key)) {
#     787                 :       1435 :             CKeyMetadata metadata;
#     788                 :       1435 :             const auto it{spk_man.mapKeyMetadata.find(keyid)};
#     789         [ +  - ]:       1435 :             if (it != spk_man.mapKeyMetadata.end()) metadata = it->second;
#     790                 :       1435 :             file << strprintf("%s %s ", EncodeSecret(key), strTime);
#     791         [ +  + ]:       1435 :             if (GetWalletAddressesForKey(&spk_man, wallet, keyid, strAddr, strLabel)) {
#     792                 :         80 :                 file << strprintf("label=%s", strLabel);
#     793         [ +  + ]:       1355 :             } else if (keyid == seed_id) {
#     794                 :          6 :                 file << "hdseed=1";
#     795         [ +  + ]:       1349 :             } else if (mapKeyPool.count(keyid)) {
#     796                 :       1137 :                 file << "reserve=1";
#     797         [ +  + ]:       1137 :             } else if (metadata.hdKeypath == "s") {
#     798                 :          1 :                 file << "inactivehdseed=1";
#     799                 :        211 :             } else {
#     800                 :        211 :                 file << "change=1";
#     801                 :        211 :             }
#     802         [ +  + ]:       1435 :             file << strprintf(" # addr=%s%s\n", strAddr, (metadata.has_key_origin ? " hdkeypath="+WriteHDKeypath(metadata.key_origin.path) : ""));
#     803                 :       1435 :         }
#     804                 :       1435 :     }
#     805                 :          8 :     file << "\n";
#     806         [ +  + ]:       1437 :     for (const CScriptID &scriptid : scripts) {
#     807                 :       1437 :         CScript script;
#     808                 :       1437 :         std::string create_time = "0";
#     809                 :       1437 :         std::string address = EncodeDestination(ScriptHash(scriptid));
#     810                 :            :         // get birth times for scripts with metadata
#     811                 :       1437 :         auto it = spk_man.m_script_metadata.find(scriptid);
#     812         [ -  + ]:       1437 :         if (it != spk_man.m_script_metadata.end()) {
#     813                 :          0 :             create_time = FormatISO8601DateTime(it->second.nCreateTime);
#     814                 :          0 :         }
#     815         [ +  - ]:       1437 :         if(spk_man.GetCScript(scriptid, script)) {
#     816                 :       1437 :             file << strprintf("%s %s script=1", HexStr(script), create_time);
#     817                 :       1437 :             file << strprintf(" # addr=%s\n", address);
#     818                 :       1437 :         }
#     819                 :       1437 :     }
#     820                 :          8 :     file << "\n";
#     821                 :          8 :     file << "# End of dump\n";
#     822                 :          8 :     file.close();
#     823                 :            : 
#     824                 :          8 :     UniValue reply(UniValue::VOBJ);
#     825                 :          8 :     reply.pushKV("filename", filepath.u8string());
#     826                 :            : 
#     827                 :          8 :     return reply;
#     828                 :          8 : },
#     829                 :       1593 :     };
#     830                 :       1593 : }
#     831                 :            : 
#     832                 :            : struct ImportData
#     833                 :            : {
#     834                 :            :     // Input data
#     835                 :            :     std::unique_ptr<CScript> redeemscript; //!< Provided redeemScript; will be moved to `import_scripts` if relevant.
#     836                 :            :     std::unique_ptr<CScript> witnessscript; //!< Provided witnessScript; will be moved to `import_scripts` if relevant.
#     837                 :            : 
#     838                 :            :     // Output data
#     839                 :            :     std::set<CScript> import_scripts;
#     840                 :            :     std::map<CKeyID, bool> used_keys; //!< Import these private keys if available (the value indicates whether if the key is required for solvability)
#     841                 :            :     std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> key_origins;
#     842                 :            : };
#     843                 :            : 
#     844                 :            : enum class ScriptContext
#     845                 :            : {
#     846                 :            :     TOP, //!< Top-level scriptPubKey
#     847                 :            :     P2SH, //!< P2SH redeemScript
#     848                 :            :     WITNESS_V0, //!< P2WSH witnessScript
#     849                 :            : };
#     850                 :            : 
#     851                 :            : // Analyse the provided scriptPubKey, determining which keys and which redeem scripts from the ImportData struct are needed to spend it, and mark them as used.
#     852                 :            : // Returns an error string, or the empty string for success.
#     853                 :            : static std::string RecurseImportData(const CScript& script, ImportData& import_data, const ScriptContext script_ctx)
#     854                 :        126 : {
#     855                 :            :     // Use Solver to obtain script type and parsed pubkeys or hashes:
#     856                 :        126 :     std::vector<std::vector<unsigned char>> solverdata;
#     857                 :        126 :     TxoutType script_type = Solver(script, solverdata);
#     858                 :            : 
#     859         [ -  + ]:        126 :     switch (script_type) {
#     860         [ -  + ]:          0 :     case TxoutType::PUBKEY: {
#     861                 :          0 :         CPubKey pubkey(solverdata[0]);
#     862                 :          0 :         import_data.used_keys.emplace(pubkey.GetID(), false);
#     863                 :          0 :         return "";
#     864                 :          0 :     }
#     865         [ +  + ]:         35 :     case TxoutType::PUBKEYHASH: {
#     866                 :         35 :         CKeyID id = CKeyID(uint160(solverdata[0]));
#     867                 :         35 :         import_data.used_keys[id] = true;
#     868                 :         35 :         return "";
#     869                 :          0 :     }
#     870         [ +  + ]:         30 :     case TxoutType::SCRIPTHASH: {
#     871         [ -  + ]:         30 :         if (script_ctx == ScriptContext::P2SH) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside another P2SH");
#     872         [ -  + ]:         30 :         if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside a P2WSH");
#     873         [ -  + ]:         30 :         CHECK_NONFATAL(script_ctx == ScriptContext::TOP);
#     874                 :         30 :         CScriptID id = CScriptID(uint160(solverdata[0]));
#     875                 :         30 :         auto subscript = std::move(import_data.redeemscript); // Remove redeemscript from import_data to check for superfluous script later.
#     876         [ -  + ]:         30 :         if (!subscript) return "missing redeemscript";
#     877         [ -  + ]:         30 :         if (CScriptID(*subscript) != id) return "redeemScript does not match the scriptPubKey";
#     878                 :         30 :         import_data.import_scripts.emplace(*subscript);
#     879                 :         30 :         return RecurseImportData(*subscript, import_data, ScriptContext::P2SH);
#     880                 :         30 :     }
#     881         [ +  + ]:          5 :     case TxoutType::MULTISIG: {
#     882         [ +  + ]:         20 :         for (size_t i = 1; i + 1< solverdata.size(); ++i) {
#     883                 :         15 :             CPubKey pubkey(solverdata[i]);
#     884                 :         15 :             import_data.used_keys.emplace(pubkey.GetID(), false);
#     885                 :         15 :         }
#     886                 :          5 :         return "";
#     887                 :         30 :     }
#     888         [ +  + ]:          2 :     case TxoutType::WITNESS_V0_SCRIPTHASH: {
#     889         [ -  + ]:          2 :         if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WSH inside another P2WSH");
#     890                 :          2 :         uint256 fullid(solverdata[0]);
#     891                 :          2 :         CScriptID id;
#     892                 :          2 :         CRIPEMD160().Write(fullid.begin(), fullid.size()).Finalize(id.begin());
#     893                 :          2 :         auto subscript = std::move(import_data.witnessscript); // Remove redeemscript from import_data to check for superfluous script later.
#     894         [ -  + ]:          2 :         if (!subscript) return "missing witnessscript";
#     895         [ -  + ]:          2 :         if (CScriptID(*subscript) != id) return "witnessScript does not match the scriptPubKey or redeemScript";
#     896         [ +  + ]:          2 :         if (script_ctx == ScriptContext::TOP) {
#     897                 :          1 :             import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WSH requires the TOP script imported (see script/ismine.cpp)
#     898                 :          1 :         }
#     899                 :          2 :         import_data.import_scripts.emplace(*subscript);
#     900                 :          2 :         return RecurseImportData(*subscript, import_data, ScriptContext::WITNESS_V0);
#     901                 :          2 :     }
#     902         [ +  + ]:         54 :     case TxoutType::WITNESS_V0_KEYHASH: {
#     903         [ -  + ]:         54 :         if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WPKH inside P2WSH");
#     904                 :         54 :         CKeyID id = CKeyID(uint160(solverdata[0]));
#     905                 :         54 :         import_data.used_keys[id] = true;
#     906         [ +  + ]:         54 :         if (script_ctx == ScriptContext::TOP) {
#     907                 :         28 :             import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WPKH requires the TOP script imported (see script/ismine.cpp)
#     908                 :         28 :         }
#     909                 :         54 :         return "";
#     910                 :         54 :     }
#     911         [ -  + ]:          0 :     case TxoutType::NULL_DATA:
#     912                 :          0 :         return "unspendable script";
#     913         [ -  + ]:          0 :     case TxoutType::NONSTANDARD:
#     914         [ -  + ]:          0 :     case TxoutType::WITNESS_UNKNOWN:
#     915         [ -  + ]:          0 :     case TxoutType::WITNESS_V1_TAPROOT:
#     916                 :          0 :         return "unrecognized script";
#     917                 :        126 :     } // no default case, so the compiler can warn about missing cases
#     918                 :          0 :     CHECK_NONFATAL(false);
#     919                 :          0 : }
#     920                 :            : 
#     921                 :            : static UniValue ProcessImportLegacy(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys)
#     922                 :        144 : {
#     923                 :        144 :     UniValue warnings(UniValue::VARR);
#     924                 :            : 
#     925                 :            :     // First ensure scriptPubKey has either a script or JSON with "address" string
#     926                 :        144 :     const UniValue& scriptPubKey = data["scriptPubKey"];
#     927                 :        144 :     bool isScript = scriptPubKey.getType() == UniValue::VSTR;
#     928 [ -  + ][ +  + ]:        144 :     if (!isScript && !(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address"))) {
#         [ +  - ][ +  - ]
#     929                 :          0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "scriptPubKey must be string with script or JSON with address string");
#     930                 :          0 :     }
#     931         [ +  + ]:        144 :     const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
#     932                 :            : 
#     933                 :            :     // Optional fields.
#     934         [ +  + ]:        144 :     const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
#     935         [ +  + ]:        144 :     const std::string& witness_script_hex = data.exists("witnessscript") ? data["witnessscript"].get_str() : "";
#     936         [ +  + ]:        144 :     const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
#     937         [ +  + ]:        144 :     const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
#     938         [ +  + ]:        144 :     const bool internal = data.exists("internal") ? data["internal"].get_bool() : false;
#     939         [ +  + ]:        144 :     const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
#     940                 :            : 
#     941         [ -  + ]:        144 :     if (data.exists("range")) {
#     942                 :          0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for a non-descriptor import");
#     943                 :          0 :     }
#     944                 :            : 
#     945                 :            :     // Generate the script and destination for the scriptPubKey provided
#     946                 :        144 :     CScript script;
#     947         [ +  + ]:        144 :     if (!isScript) {
#     948                 :         80 :         CTxDestination dest = DecodeDestination(output);
#     949         [ +  + ]:         80 :         if (!IsValidDestination(dest)) {
#     950                 :          1 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address \"" + output + "\"");
#     951                 :          1 :         }
#     952         [ +  + ]:         79 :         if (OutputTypeFromDestination(dest) == OutputType::BECH32M) {
#     953                 :          1 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets");
#     954                 :          1 :         }
#     955                 :         78 :         script = GetScriptForDestination(dest);
#     956                 :         78 :     } else {
#     957         [ -  + ]:         64 :         if (!IsHex(output)) {
#     958                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey \"" + output + "\"");
#     959                 :          0 :         }
#     960                 :         64 :         std::vector<unsigned char> vData(ParseHex(output));
#     961                 :         64 :         script = CScript(vData.begin(), vData.end());
#     962                 :         64 :         CTxDestination dest;
#     963 [ +  + ][ +  - ]:         64 :         if (!ExtractDestination(script, dest) && !internal) {
#     964                 :          3 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set to true for nonstandard scriptPubKey imports.");
#     965                 :          3 :         }
#     966                 :         64 :     }
#     967                 :        139 :     script_pub_keys.emplace(script);
#     968                 :            : 
#     969                 :            :     // Parse all arguments
#     970         [ +  + ]:        139 :     if (strRedeemScript.size()) {
#     971         [ -  + ]:         30 :         if (!IsHex(strRedeemScript)) {
#     972                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script \"" + strRedeemScript + "\": must be hex string");
#     973                 :          0 :         }
#     974                 :         30 :         auto parsed_redeemscript = ParseHex(strRedeemScript);
#     975                 :         30 :         import_data.redeemscript = std::make_unique<CScript>(parsed_redeemscript.begin(), parsed_redeemscript.end());
#     976                 :         30 :     }
#     977         [ +  + ]:        139 :     if (witness_script_hex.size()) {
#     978         [ -  + ]:          2 :         if (!IsHex(witness_script_hex)) {
#     979                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid witness script \"" + witness_script_hex + "\": must be hex string");
#     980                 :          0 :         }
#     981                 :          2 :         auto parsed_witnessscript = ParseHex(witness_script_hex);
#     982                 :          2 :         import_data.witnessscript = std::make_unique<CScript>(parsed_witnessscript.begin(), parsed_witnessscript.end());
#     983                 :          2 :     }
#     984         [ +  + ]:        182 :     for (size_t i = 0; i < pubKeys.size(); ++i) {
#     985                 :         43 :         const auto& str = pubKeys[i].get_str();
#     986         [ -  + ]:         43 :         if (!IsHex(str)) {
#     987                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" must be a hex string");
#     988                 :          0 :         }
#     989                 :         43 :         auto parsed_pubkey = ParseHex(str);
#     990                 :         43 :         CPubKey pubkey(parsed_pubkey);
#     991         [ -  + ]:         43 :         if (!pubkey.IsFullyValid()) {
#     992                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" is not a valid public key");
#     993                 :          0 :         }
#     994                 :         43 :         pubkey_map.emplace(pubkey.GetID(), pubkey);
#     995                 :         43 :         ordered_pubkeys.push_back(pubkey.GetID());
#     996                 :         43 :     }
#     997         [ +  + ]:        192 :     for (size_t i = 0; i < keys.size(); ++i) {
#     998                 :         53 :         const auto& str = keys[i].get_str();
#     999                 :         53 :         CKey key = DecodeSecret(str);
#    1000         [ -  + ]:         53 :         if (!key.IsValid()) {
#    1001                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
#    1002                 :          0 :         }
#    1003                 :         53 :         CPubKey pubkey = key.GetPubKey();
#    1004                 :         53 :         CKeyID id = pubkey.GetID();
#    1005         [ -  + ]:         53 :         if (pubkey_map.count(id)) {
#    1006                 :          0 :             pubkey_map.erase(id);
#    1007                 :          0 :         }
#    1008                 :         53 :         privkey_map.emplace(id, key);
#    1009                 :         53 :     }
#    1010                 :            : 
#    1011                 :            : 
#    1012                 :            :     // Verify and process input data
#    1013 [ +  + ][ +  + ]:        139 :     have_solving_data = import_data.redeemscript || import_data.witnessscript || pubkey_map.size() || privkey_map.size();
#         [ +  + ][ +  + ]
#    1014         [ +  + ]:        139 :     if (have_solving_data) {
#    1015                 :            :         // Match up data in import_data with the scriptPubKey in script.
#    1016                 :         94 :         auto error = RecurseImportData(script, import_data, ScriptContext::TOP);
#    1017                 :            : 
#    1018                 :            :         // Verify whether the watchonly option corresponds to the availability of private keys.
#    1019                 :         97 :         bool spendable = std::all_of(import_data.used_keys.begin(), import_data.used_keys.end(), [&](const std::pair<CKeyID, bool>& used_key){ return privkey_map.count(used_key.first) > 0; });
#    1020 [ +  + ][ +  + ]:         94 :         if (!watchOnly && !spendable) {
#    1021                 :         12 :             warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag.");
#    1022                 :         12 :         }
#    1023 [ +  + ][ +  + ]:         94 :         if (watchOnly && spendable) {
#    1024                 :          1 :             warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag.");
#    1025                 :          1 :         }
#    1026                 :            : 
#    1027                 :            :         // Check that all required keys for solvability are provided.
#    1028         [ +  - ]:         94 :         if (error.empty()) {
#    1029         [ +  + ]:        104 :             for (const auto& require_key : import_data.used_keys) {
#    1030         [ +  + ]:        104 :                 if (!require_key.second) continue; // Not a required key
#    1031 [ +  + ][ +  + ]:         89 :                 if (pubkey_map.count(require_key.first) == 0 && privkey_map.count(require_key.first) == 0) {
#    1032                 :          4 :                     error = "some required keys are missing";
#    1033                 :          4 :                 }
#    1034                 :         89 :             }
#    1035                 :         94 :         }
#    1036                 :            : 
#    1037         [ +  + ]:         94 :         if (!error.empty()) {
#    1038                 :          4 :             warnings.push_back("Importing as non-solvable: " + error + ". If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.");
#    1039                 :          4 :             import_data = ImportData();
#    1040                 :          4 :             pubkey_map.clear();
#    1041                 :          4 :             privkey_map.clear();
#    1042                 :          4 :             have_solving_data = false;
#    1043                 :         90 :         } else {
#    1044                 :            :             // RecurseImportData() removes any relevant redeemscript/witnessscript from import_data, so we can use that to discover if a superfluous one was provided.
#    1045         [ -  + ]:         90 :             if (import_data.redeemscript) warnings.push_back("Ignoring redeemscript as this is not a P2SH script.");
#    1046         [ -  + ]:         90 :             if (import_data.witnessscript) warnings.push_back("Ignoring witnessscript as this is not a (P2SH-)P2WSH script.");
#    1047         [ +  + ]:        141 :             for (auto it = privkey_map.begin(); it != privkey_map.end(); ) {
#    1048                 :         51 :                 auto oldit = it++;
#    1049         [ -  + ]:         51 :                 if (import_data.used_keys.count(oldit->first) == 0) {
#    1050                 :          0 :                     warnings.push_back("Ignoring irrelevant private key.");
#    1051                 :          0 :                     privkey_map.erase(oldit);
#    1052                 :          0 :                 }
#    1053                 :         51 :             }
#    1054         [ +  + ]:        131 :             for (auto it = pubkey_map.begin(); it != pubkey_map.end(); ) {
#    1055                 :         41 :                 auto oldit = it++;
#    1056                 :         41 :                 auto key_data_it = import_data.used_keys.find(oldit->first);
#    1057 [ -  + ][ -  + ]:         41 :                 if (key_data_it == import_data.used_keys.end() || !key_data_it->second) {
#                 [ -  + ]
#    1058                 :          0 :                     warnings.push_back("Ignoring public key \"" + HexStr(oldit->first) + "\" as it doesn't appear inside P2PKH or P2WPKH.");
#    1059                 :          0 :                     pubkey_map.erase(oldit);
#    1060                 :          0 :                 }
#    1061                 :         41 :             }
#    1062                 :         90 :         }
#    1063                 :         94 :     }
#    1064                 :            : 
#    1065                 :        139 :     return warnings;
#    1066                 :        139 : }
#    1067                 :            : 
#    1068                 :            : static UniValue ProcessImportDescriptor(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys)
#    1069                 :         43 : {
#    1070                 :         43 :     UniValue warnings(UniValue::VARR);
#    1071                 :            : 
#    1072                 :         43 :     const std::string& descriptor = data["desc"].get_str();
#    1073                 :         43 :     FlatSigningProvider keys;
#    1074                 :         43 :     std::string error;
#    1075                 :         43 :     auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true);
#    1076         [ +  + ]:         43 :     if (!parsed_desc) {
#    1077                 :          1 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
#    1078                 :          1 :     }
#    1079         [ +  + ]:         42 :     if (parsed_desc->GetOutputType() == OutputType::BECH32M) {
#    1080                 :          1 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m descriptors cannot be imported into legacy wallets");
#    1081                 :          1 :     }
#    1082                 :            : 
#    1083                 :         41 :     have_solving_data = parsed_desc->IsSolvable();
#    1084         [ +  + ]:         41 :     const bool watch_only = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
#    1085                 :            : 
#    1086                 :         41 :     int64_t range_start = 0, range_end = 0;
#    1087 [ +  + ][ -  + ]:         41 :     if (!parsed_desc->IsRange() && data.exists("range")) {
#                 [ -  + ]
#    1088                 :          0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
#    1089         [ +  + ]:         41 :     } else if (parsed_desc->IsRange()) {
#    1090         [ +  + ]:         13 :         if (!data.exists("range")) {
#    1091                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor is ranged, please specify the range");
#    1092                 :          1 :         }
#    1093                 :         12 :         std::tie(range_start, range_end) = ParseDescriptorRange(data["range"]);
#    1094                 :         12 :     }
#    1095                 :            : 
#    1096         [ +  + ]:         40 :     const UniValue& priv_keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
#    1097                 :            : 
#    1098                 :            :     // Expand all descriptors to get public keys and scripts, and private keys if available.
#    1099         [ +  + ]:        201 :     for (int i = range_start; i <= range_end; ++i) {
#    1100                 :        161 :         FlatSigningProvider out_keys;
#    1101                 :        161 :         std::vector<CScript> scripts_temp;
#    1102                 :        161 :         parsed_desc->Expand(i, keys, scripts_temp, out_keys);
#    1103                 :        161 :         std::copy(scripts_temp.begin(), scripts_temp.end(), std::inserter(script_pub_keys, script_pub_keys.end()));
#    1104         [ +  + ]:        161 :         for (const auto& key_pair : out_keys.pubkeys) {
#    1105                 :        156 :             ordered_pubkeys.push_back(key_pair.first);
#    1106                 :        156 :         }
#    1107                 :            : 
#    1108         [ +  + ]:        161 :         for (const auto& x : out_keys.scripts) {
#    1109                 :         15 :             import_data.import_scripts.emplace(x.second);
#    1110                 :         15 :         }
#    1111                 :            : 
#    1112                 :        161 :         parsed_desc->ExpandPrivate(i, keys, out_keys);
#    1113                 :            : 
#    1114                 :        161 :         std::copy(out_keys.pubkeys.begin(), out_keys.pubkeys.end(), std::inserter(pubkey_map, pubkey_map.end()));
#    1115                 :        161 :         std::copy(out_keys.keys.begin(), out_keys.keys.end(), std::inserter(privkey_map, privkey_map.end()));
#    1116                 :        161 :         import_data.key_origins.insert(out_keys.origins.begin(), out_keys.origins.end());
#    1117                 :        161 :     }
#    1118                 :            : 
#    1119         [ +  + ]:         41 :     for (size_t i = 0; i < priv_keys.size(); ++i) {
#    1120                 :          1 :         const auto& str = priv_keys[i].get_str();
#    1121                 :          1 :         CKey key = DecodeSecret(str);
#    1122         [ -  + ]:          1 :         if (!key.IsValid()) {
#    1123                 :          0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
#    1124                 :          0 :         }
#    1125                 :          1 :         CPubKey pubkey = key.GetPubKey();
#    1126                 :          1 :         CKeyID id = pubkey.GetID();
#    1127                 :            : 
#    1128                 :            :         // Check if this private key corresponds to a public key from the descriptor
#    1129         [ -  + ]:          1 :         if (!pubkey_map.count(id)) {
#    1130                 :          0 :             warnings.push_back("Ignoring irrelevant private key.");
#    1131                 :          1 :         } else {
#    1132                 :          1 :             privkey_map.emplace(id, key);
#    1133                 :          1 :         }
#    1134                 :          1 :     }
#    1135                 :            : 
#    1136                 :            :     // Check if all the public keys have corresponding private keys in the import for spendability.
#    1137                 :            :     // This does not take into account threshold multisigs which could be spendable without all keys.
#    1138                 :            :     // Thus, threshold multisigs without all keys will be considered not spendable here, even if they are,
#    1139                 :            :     // perhaps triggering a false warning message. This is consistent with the current wallet IsMine check.
#    1140         [ +  + ]:         40 :     bool spendable = std::all_of(pubkey_map.begin(), pubkey_map.end(),
#    1141                 :         40 :         [&](const std::pair<CKeyID, CPubKey>& used_key) {
#    1142                 :         32 :             return privkey_map.count(used_key.first) > 0;
#    1143         [ +  + ]:         32 :         }) && std::all_of(import_data.key_origins.begin(), import_data.key_origins.end(),
#    1144                 :         17 :         [&](const std::pair<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& entry) {
#    1145                 :         17 :             return privkey_map.count(entry.first) > 0;
#    1146                 :         17 :         });
#    1147 [ +  + ][ +  + ]:         40 :     if (!watch_only && !spendable) {
#    1148                 :         10 :         warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag.");
#    1149                 :         10 :     }
#    1150 [ +  + ][ -  + ]:         40 :     if (watch_only && spendable) {
#    1151                 :          0 :         warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag.");
#    1152                 :          0 :     }
#    1153                 :            : 
#    1154                 :         40 :     return warnings;
#    1155                 :         40 : }
#    1156                 :            : 
#    1157                 :            : static UniValue ProcessImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
#    1158                 :        191 : {
#    1159                 :        191 :     UniValue warnings(UniValue::VARR);
#    1160                 :        191 :     UniValue result(UniValue::VOBJ);
#    1161                 :            : 
#    1162                 :        191 :     try {
#    1163         [ +  + ]:        191 :         const bool internal = data.exists("internal") ? data["internal"].get_bool() : false;
#    1164                 :            :         // Internal addresses should not have a label
#    1165 [ +  + ][ +  + ]:        191 :         if (internal && data.exists("label")) {
#                 [ +  + ]
#    1166                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label");
#    1167                 :          1 :         }
#    1168         [ +  + ]:        190 :         const std::string& label = data.exists("label") ? data["label"].get_str() : "";
#    1169         [ +  + ]:        190 :         const bool add_keypool = data.exists("keypool") ? data["keypool"].get_bool() : false;
#    1170                 :            : 
#    1171                 :            :         // Add to keypool only works with privkeys disabled
#    1172 [ +  + ][ +  + ]:        190 :         if (add_keypool && !wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#    1173                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Keys can only be imported to the keypool when private keys are disabled");
#    1174                 :          1 :         }
#    1175                 :            : 
#    1176                 :        189 :         ImportData import_data;
#    1177                 :        189 :         std::map<CKeyID, CPubKey> pubkey_map;
#    1178                 :        189 :         std::map<CKeyID, CKey> privkey_map;
#    1179                 :        189 :         std::set<CScript> script_pub_keys;
#    1180                 :        189 :         std::vector<CKeyID> ordered_pubkeys;
#    1181                 :        189 :         bool have_solving_data;
#    1182                 :            : 
#    1183 [ +  + ][ +  + ]:        189 :         if (data.exists("scriptPubKey") && data.exists("desc")) {
#                 [ +  + ]
#    1184                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Both a descriptor and a scriptPubKey should not be provided.");
#    1185         [ +  + ]:        188 :         } else if (data.exists("scriptPubKey")) {
#    1186                 :        144 :             warnings = ProcessImportLegacy(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys);
#    1187         [ +  + ]:        144 :         } else if (data.exists("desc")) {
#    1188                 :         43 :             warnings = ProcessImportDescriptor(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys);
#    1189                 :         43 :         } else {
#    1190                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Either a descriptor or scriptPubKey must be provided.");
#    1191                 :          1 :         }
#    1192                 :            : 
#    1193                 :            :         // If private keys are disabled, abort if private keys are being imported
#    1194 [ +  + ][ +  + ]:        187 :         if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !privkey_map.empty()) {
#    1195                 :          2 :             throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
#    1196                 :          2 :         }
#    1197                 :            : 
#    1198                 :            :         // Check whether we have any work to do
#    1199         [ +  + ]:        298 :         for (const CScript& script : script_pub_keys) {
#    1200         [ +  + ]:        298 :             if (wallet.IsMine(script) & ISMINE_SPENDABLE) {
#    1201                 :          1 :                 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script (\"" + HexStr(script) + "\")");
#    1202                 :          1 :             }
#    1203                 :        298 :         }
#    1204                 :            : 
#    1205                 :            :         // All good, time to import
#    1206                 :        184 :         wallet.MarkDirty();
#    1207         [ -  + ]:        184 :         if (!wallet.ImportScripts(import_data.import_scripts, timestamp)) {
#    1208                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Error adding script to wallet");
#    1209                 :          0 :         }
#    1210         [ -  + ]:        184 :         if (!wallet.ImportPrivKeys(privkey_map, timestamp)) {
#    1211                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
#    1212                 :          0 :         }
#    1213         [ -  + ]:        184 :         if (!wallet.ImportPubKeys(ordered_pubkeys, pubkey_map, import_data.key_origins, add_keypool, internal, timestamp)) {
#    1214                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
#    1215                 :          0 :         }
#    1216         [ -  + ]:        184 :         if (!wallet.ImportScriptPubKeys(label, script_pub_keys, have_solving_data, !internal, timestamp)) {
#    1217                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
#    1218                 :          0 :         }
#    1219                 :            : 
#    1220                 :        184 :         result.pushKV("success", UniValue(true));
#    1221                 :        184 :     } catch (const UniValue& e) {
#    1222                 :         20 :         result.pushKV("success", UniValue(false));
#    1223                 :         20 :         result.pushKV("error", e);
#    1224                 :         20 :     } catch (...) {
#    1225                 :          0 :         result.pushKV("success", UniValue(false));
#    1226                 :            : 
#    1227                 :          0 :         result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
#    1228                 :          0 :     }
#    1229         [ +  + ]:        191 :     if (warnings.size()) result.pushKV("warnings", warnings);
#    1230                 :        191 :     return result;
#    1231                 :        191 : }
#    1232                 :            : 
#    1233                 :            : static int64_t GetImportTimestamp(const UniValue& data, int64_t now)
#    1234                 :        806 : {
#    1235         [ +  + ]:        806 :     if (data.exists("timestamp")) {
#    1236                 :        805 :         const UniValue& timestamp = data["timestamp"];
#    1237         [ +  + ]:        805 :         if (timestamp.isNum()) {
#    1238                 :        334 :             return timestamp.get_int64();
#    1239 [ +  - ][ +  + ]:        471 :         } else if (timestamp.isStr() && timestamp.get_str() == "now") {
#    1240                 :        470 :             return now;
#    1241                 :        470 :         }
#    1242                 :          1 :         throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
#    1243                 :        805 :     }
#    1244                 :          1 :     throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
#    1245                 :        806 : }
#    1246                 :            : 
#    1247                 :            : RPCHelpMan importmulti()
#    1248                 :       1770 : {
#    1249                 :       1770 :     return RPCHelpMan{"importmulti",
#    1250                 :       1770 :                 "\nImport addresses/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain from the earliest creation time of the imported scripts. Requires a new wallet backup.\n"
#    1251                 :       1770 :                 "If an address/script is imported without all of the private keys required to spend from that address, it will be watchonly. The 'watchonly' option must be set to true in this case or a warning will be returned.\n"
#    1252                 :       1770 :                 "Conversely, if all the private keys are provided and the address/script is spendable, the watchonly option must be set to false, or a warning will be returned.\n"
#    1253                 :       1770 :             "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n"
#    1254                 :       1770 :             "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n"
#    1255                 :       1770 :             "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
#    1256                 :       1770 :                 {
#    1257                 :       1770 :                     {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported",
#    1258                 :       1770 :                         {
#    1259                 :       1770 :                             {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
#    1260                 :       1770 :                                 {
#    1261                 :       1770 :                                     {"desc", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Descriptor to import. If using descriptor, do not also provide address/scriptPubKey, scripts, or pubkeys"},
#    1262                 :       1770 :                                     {"scriptPubKey", RPCArg::Type::STR, RPCArg::Optional::NO, "Type of scriptPubKey (string for script, json for address). Should not be provided if using a descriptor",
#    1263                 :       1770 :                                         /*oneline_description=*/"", {"\"<script>\" | { \"address\":\"<address>\" }", "string / json"}
#    1264                 :       1770 :                                     },
#    1265                 :       1770 :                                     {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Creation time of the key expressed in " + UNIX_EPOCH_TIME + ",\n"
#    1266                 :       1770 :         "                                                              or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
#    1267                 :       1770 :         "                                                              key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
#    1268                 :       1770 :         "                                                              \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
#    1269                 :       1770 :         "                                                              0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
#    1270                 :       1770 :         "                                                              creation time of all keys being imported by the importmulti call will be scanned.",
#    1271                 :       1770 :                                         /*oneline_description=*/"", {"timestamp | \"now\"", "integer / string"}
#    1272                 :       1770 :                                     },
#    1273                 :       1770 :                                     {"redeemscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH or P2SH-P2WSH address/scriptPubKey"},
#    1274                 :       1770 :                                     {"witnessscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH-P2WSH or P2WSH address/scriptPubKey"},
#    1275                 :       1770 :                                     {"pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving pubkeys to import. They must occur in P2PKH or P2WPKH scripts. They are not required when the private key is also provided (see the \"keys\" argument).",
#    1276                 :       1770 :                                         {
#    1277                 :       1770 :                                             {"pubKey", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
#    1278                 :       1770 :                                         }
#    1279                 :       1770 :                                     },
#    1280                 :       1770 :                                     {"keys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving private keys to import. The corresponding public keys must occur in the output or redeemscript.",
#    1281                 :       1770 :                                         {
#    1282                 :       1770 :                                             {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""},
#    1283                 :       1770 :                                         }
#    1284                 :       1770 :                                     },
#    1285                 :       1770 :                                     {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"},
#    1286                 :       1770 :                                     {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be treated as not incoming payments (also known as change)"},
#    1287                 :       1770 :                                     {"watchonly", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be considered watchonly."},
#    1288                 :       1770 :                                     {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false"},
#    1289                 :       1770 :                                     {"keypool", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether imported public keys should be added to the keypool for when users request new addresses. Only allowed when wallet private keys are disabled"},
#    1290                 :       1770 :                                 },
#    1291                 :       1770 :                             },
#    1292                 :       1770 :                         },
#    1293                 :       1770 :                         "\"requests\""},
#    1294                 :       1770 :                     {"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "",
#    1295                 :       1770 :                         {
#    1296                 :       1770 :                             {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Stating if should rescan the blockchain after all imports"},
#    1297                 :       1770 :                         },
#    1298                 :       1770 :                         "\"options\""},
#    1299                 :       1770 :                 },
#    1300                 :       1770 :                 RPCResult{
#    1301                 :       1770 :                     RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result",
#    1302                 :       1770 :                     {
#    1303                 :       1770 :                         {RPCResult::Type::OBJ, "", "",
#    1304                 :       1770 :                         {
#    1305                 :       1770 :                             {RPCResult::Type::BOOL, "success", ""},
#    1306                 :       1770 :                             {RPCResult::Type::ARR, "warnings", /*optional=*/true, "",
#    1307                 :       1770 :                             {
#    1308                 :       1770 :                                 {RPCResult::Type::STR, "", ""},
#    1309                 :       1770 :                             }},
#    1310                 :       1770 :                             {RPCResult::Type::OBJ, "error", /*optional=*/true, "",
#    1311                 :       1770 :                             {
#    1312                 :       1770 :                                 {RPCResult::Type::ELISION, "", "JSONRPC error"},
#    1313                 :       1770 :                             }},
#    1314                 :       1770 :                         }},
#    1315                 :       1770 :                     }
#    1316                 :       1770 :                 },
#    1317                 :       1770 :                 RPCExamples{
#    1318                 :       1770 :                     HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
#    1319                 :       1770 :                                           "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
#    1320                 :       1770 :                     HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'")
#    1321                 :       1770 :                 },
#    1322                 :       1770 :         [&](const RPCHelpMan& self, const JSONRPCRequest& mainRequest) -> UniValue
#    1323                 :       1770 : {
#    1324                 :        186 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(mainRequest);
#    1325         [ -  + ]:        186 :     if (!pwallet) return NullUniValue;
#    1326                 :        186 :     CWallet& wallet{*pwallet};
#    1327                 :            : 
#    1328                 :            :     // Make sure the results are valid at least up to the most recent block
#    1329                 :            :     // the user could have gotten from another RPC command prior to now
#    1330                 :        186 :     wallet.BlockUntilSyncedToCurrentChain();
#    1331                 :            : 
#    1332                 :        186 :     RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
#    1333                 :            : 
#    1334                 :        186 :     EnsureLegacyScriptPubKeyMan(*pwallet, true);
#    1335                 :            : 
#    1336                 :        186 :     const UniValue& requests = mainRequest.params[0];
#    1337                 :            : 
#    1338                 :            :     //Default options
#    1339                 :        186 :     bool fRescan = true;
#    1340                 :            : 
#    1341         [ +  + ]:        186 :     if (!mainRequest.params[1].isNull()) {
#    1342                 :        108 :         const UniValue& options = mainRequest.params[1];
#    1343                 :            : 
#    1344         [ +  - ]:        108 :         if (options.exists("rescan")) {
#    1345                 :        108 :             fRescan = options["rescan"].get_bool();
#    1346                 :        108 :         }
#    1347                 :        108 :     }
#    1348                 :            : 
#    1349                 :        186 :     WalletRescanReserver reserver(*pwallet);
#    1350 [ +  + ][ -  + ]:        186 :     if (fRescan && !reserver.reserve()) {
#    1351                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#    1352                 :          0 :     }
#    1353                 :            : 
#    1354                 :        186 :     int64_t now = 0;
#    1355                 :        186 :     bool fRunScan = false;
#    1356                 :        186 :     int64_t nLowestTimestamp = 0;
#    1357                 :        186 :     UniValue response(UniValue::VARR);
#    1358                 :        186 :     {
#    1359                 :        186 :         LOCK(pwallet->cs_wallet);
#    1360                 :        186 :         EnsureWalletIsUnlocked(*pwallet);
#    1361                 :            : 
#    1362                 :            :         // Verify all timestamps are present before importing any keys.
#    1363         [ -  + ]:        186 :         CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nLowestTimestamp).mtpTime(now)));
#    1364         [ +  + ]:        193 :         for (const UniValue& data : requests.getValues()) {
#    1365                 :        193 :             GetImportTimestamp(data, now);
#    1366                 :        193 :         }
#    1367                 :            : 
#    1368                 :        186 :         const int64_t minimumTimestamp = 1;
#    1369                 :            : 
#    1370         [ +  + ]:        191 :         for (const UniValue& data : requests.getValues()) {
#    1371                 :        191 :             const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
#    1372                 :        191 :             const UniValue result = ProcessImport(*pwallet, data, timestamp);
#    1373                 :        191 :             response.push_back(result);
#    1374                 :            : 
#    1375         [ +  + ]:        191 :             if (!fRescan) {
#    1376                 :         36 :                 continue;
#    1377                 :         36 :             }
#    1378                 :            : 
#    1379                 :            :             // If at least one request was successful then allow rescan.
#    1380         [ +  + ]:        155 :             if (result["success"].get_bool()) {
#    1381                 :        135 :                 fRunScan = true;
#    1382                 :        135 :             }
#    1383                 :            : 
#    1384                 :            :             // Get the lowest timestamp.
#    1385         [ +  + ]:        155 :             if (timestamp < nLowestTimestamp) {
#    1386                 :        128 :                 nLowestTimestamp = timestamp;
#    1387                 :        128 :             }
#    1388                 :        155 :         }
#    1389                 :        186 :     }
#    1390 [ +  + ][ +  + ]:        186 :     if (fRescan && fRunScan && requests.size()) {
#                 [ +  - ]
#    1391                 :        127 :         int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, true /* update */);
#    1392                 :        127 :         {
#    1393                 :        127 :             LOCK(pwallet->cs_wallet);
#    1394                 :        127 :             pwallet->ReacceptWalletTransactions();
#    1395                 :        127 :         }
#    1396                 :            : 
#    1397         [ -  + ]:        127 :         if (pwallet->IsAbortingRescan()) {
#    1398                 :          0 :             throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user.");
#    1399                 :          0 :         }
#    1400         [ +  + ]:        127 :         if (scannedTime > nLowestTimestamp) {
#    1401                 :          1 :             std::vector<UniValue> results = response.getValues();
#    1402                 :          1 :             response.clear();
#    1403                 :          1 :             response.setArray();
#    1404                 :          1 :             size_t i = 0;
#    1405         [ +  + ]:          2 :             for (const UniValue& request : requests.getValues()) {
#    1406                 :            :                 // If key creation date is within the successfully scanned
#    1407                 :            :                 // range, or if the import result already has an error set, let
#    1408                 :            :                 // the result stand unmodified. Otherwise replace the result
#    1409                 :            :                 // with an error message.
#    1410 [ +  + ][ +  + ]:          2 :                 if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
#                 [ -  + ]
#    1411                 :          1 :                     response.push_back(results.at(i));
#    1412                 :          1 :                 } else {
#    1413                 :          1 :                     UniValue result = UniValue(UniValue::VOBJ);
#    1414                 :          1 :                     result.pushKV("success", UniValue(false));
#    1415                 :          1 :                     result.pushKV(
#    1416                 :          1 :                         "error",
#    1417                 :          1 :                         JSONRPCError(
#    1418                 :          1 :                             RPC_MISC_ERROR,
#    1419                 :          1 :                             strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a "
#    1420                 :          1 :                                       "block from time %d, which is after or within %d seconds of key creation, and "
#    1421                 :          1 :                                       "could contain transactions pertaining to the key. As a result, transactions "
#    1422                 :          1 :                                       "and coins using this key may not appear in the wallet. This error could be "
#    1423                 :          1 :                                       "caused by pruning or data corruption (see bitcoind log for details) and could "
#    1424                 :          1 :                                       "be dealt with by downloading and rescanning the relevant blocks (see -reindex "
#    1425                 :          1 :                                       "option and rescanblockchain RPC).",
#    1426                 :          1 :                                 GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
#    1427                 :          1 :                     response.push_back(std::move(result));
#    1428                 :          1 :                 }
#    1429                 :          2 :                 ++i;
#    1430                 :          2 :             }
#    1431                 :          1 :         }
#    1432                 :        127 :     }
#    1433                 :            : 
#    1434                 :        186 :     return response;
#    1435                 :        186 : },
#    1436                 :       1770 :     };
#    1437                 :       1770 : }
#    1438                 :            : 
#    1439                 :            : static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
#    1440                 :        419 : {
#    1441                 :        419 :     UniValue warnings(UniValue::VARR);
#    1442                 :        419 :     UniValue result(UniValue::VOBJ);
#    1443                 :            : 
#    1444                 :        419 :     try {
#    1445         [ +  + ]:        419 :         if (!data.exists("desc")) {
#    1446                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found.");
#    1447                 :          1 :         }
#    1448                 :            : 
#    1449                 :        418 :         const std::string& descriptor = data["desc"].get_str();
#    1450         [ +  + ]:        418 :         const bool active = data.exists("active") ? data["active"].get_bool() : false;
#    1451         [ +  + ]:        418 :         const bool internal = data.exists("internal") ? data["internal"].get_bool() : false;
#    1452         [ +  + ]:        418 :         const std::string& label = data.exists("label") ? data["label"].get_str() : "";
#    1453                 :            : 
#    1454                 :            :         // Parse descriptor string
#    1455                 :        418 :         FlatSigningProvider keys;
#    1456                 :        418 :         std::string error;
#    1457                 :        418 :         auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true);
#    1458         [ +  + ]:        418 :         if (!parsed_desc) {
#    1459                 :          3 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
#    1460                 :          3 :         }
#    1461                 :            : 
#    1462                 :            :         // Range check
#    1463                 :        415 :         int64_t range_start = 0, range_end = 1, next_index = 0;
#    1464 [ +  + ][ +  + ]:        415 :         if (!parsed_desc->IsRange() && data.exists("range")) {
#                 [ +  + ]
#    1465                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
#    1466         [ +  + ]:        414 :         } else if (parsed_desc->IsRange()) {
#    1467         [ +  + ]:        259 :             if (data.exists("range")) {
#    1468                 :         63 :                 auto range = ParseDescriptorRange(data["range"]);
#    1469                 :         63 :                 range_start = range.first;
#    1470                 :         63 :                 range_end = range.second + 1; // Specified range end is inclusive, but we need range end as exclusive
#    1471                 :        196 :             } else {
#    1472                 :        196 :                 warnings.push_back("Range not given, using default keypool range");
#    1473                 :        196 :                 range_start = 0;
#    1474                 :        196 :                 range_end = gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE);
#    1475                 :        196 :             }
#    1476                 :        259 :             next_index = range_start;
#    1477                 :            : 
#    1478         [ +  + ]:        259 :             if (data.exists("next_index")) {
#    1479                 :         25 :                 next_index = data["next_index"].get_int64();
#    1480                 :            :                 // bound checks
#    1481 [ -  + ][ -  + ]:         25 :                 if (next_index < range_start || next_index >= range_end) {
#    1482                 :          0 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range");
#    1483                 :          0 :                 }
#    1484                 :         25 :             }
#    1485                 :        259 :         }
#    1486                 :            : 
#    1487                 :            :         // Active descriptors must be ranged
#    1488 [ +  + ][ +  + ]:        414 :         if (active && !parsed_desc->IsRange()) {
#    1489                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Active descriptors must be ranged");
#    1490                 :          1 :         }
#    1491                 :            : 
#    1492                 :            :         // Ranged descriptors should not have a label
#    1493 [ +  + ][ +  + ]:        413 :         if (data.exists("range") && data.exists("label")) {
#                 [ +  + ]
#    1494                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptors should not have a label");
#    1495                 :          1 :         }
#    1496                 :            : 
#    1497                 :            :         // Internal addresses should not have a label either
#    1498 [ +  + ][ +  + ]:        412 :         if (internal && data.exists("label")) {
#                 [ +  + ]
#    1499                 :          1 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label");
#    1500                 :          1 :         }
#    1501                 :            : 
#    1502                 :            :         // Combo descriptor check
#    1503 [ +  + ][ +  + ]:        411 :         if (active && !parsed_desc->IsSingleType()) {
#    1504                 :          1 :             throw JSONRPCError(RPC_WALLET_ERROR, "Combo descriptors cannot be set to active");
#    1505                 :          1 :         }
#    1506                 :            : 
#    1507                 :            :         // If the wallet disabled private keys, abort if private keys exist
#    1508 [ +  + ][ +  + ]:        410 :         if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) {
#    1509                 :          3 :             throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
#    1510                 :          3 :         }
#    1511                 :            : 
#    1512                 :            :         // Need to ExpandPrivate to check if private keys are available for all pubkeys
#    1513                 :        407 :         FlatSigningProvider expand_keys;
#    1514                 :        407 :         std::vector<CScript> scripts;
#    1515         [ +  + ]:        407 :         if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) {
#    1516                 :          1 :             throw JSONRPCError(RPC_WALLET_ERROR, "Cannot expand descriptor. Probably because of hardened derivations without private keys provided");
#    1517                 :          1 :         }
#    1518                 :        406 :         parsed_desc->ExpandPrivate(0, keys, expand_keys);
#    1519                 :            : 
#    1520                 :            :         // Check if all private keys are provided
#    1521                 :        406 :         bool have_all_privkeys = !expand_keys.keys.empty();
#    1522         [ +  + ]:        447 :         for (const auto& entry : expand_keys.origins) {
#    1523                 :        447 :             const CKeyID& key_id = entry.first;
#    1524                 :        447 :             CKey key;
#    1525         [ +  + ]:        447 :             if (!expand_keys.GetKey(key_id, key)) {
#    1526                 :        220 :                 have_all_privkeys = false;
#    1527                 :        220 :                 break;
#    1528                 :        220 :             }
#    1529                 :        447 :         }
#    1530                 :            : 
#    1531                 :            :         // If private keys are enabled, check some things.
#    1532         [ +  + ]:        406 :         if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#    1533         [ +  + ]:        261 :            if (keys.keys.empty()) {
#    1534                 :          1 :                 throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import descriptor without private keys to a wallet with private keys enabled");
#    1535                 :          1 :            }
#    1536         [ +  + ]:        260 :            if (!have_all_privkeys) {
#    1537                 :         90 :                warnings.push_back("Not all private keys provided. Some wallet functionality may return unexpected errors");
#    1538                 :         90 :            }
#    1539                 :        260 :         }
#    1540                 :            : 
#    1541                 :        405 :         WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index);
#    1542                 :            : 
#    1543                 :            :         // Check if the wallet already contains the descriptor
#    1544                 :        405 :         auto existing_spk_manager = wallet.GetDescriptorScriptPubKeyMan(w_desc);
#    1545         [ +  + ]:        405 :         if (existing_spk_manager) {
#    1546         [ +  + ]:         18 :             if (!existing_spk_manager->CanUpdateToWalletDescriptor(w_desc, error)) {
#    1547                 :          3 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, error);
#    1548                 :          3 :             }
#    1549                 :         18 :         }
#    1550                 :            : 
#    1551                 :            :         // Add descriptor to the wallet
#    1552                 :        402 :         auto spk_manager = wallet.AddWalletDescriptor(w_desc, keys, label, internal);
#    1553         [ -  + ]:        402 :         if (spk_manager == nullptr) {
#    1554                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Could not add descriptor '%s'", descriptor));
#    1555                 :          0 :         }
#    1556                 :            : 
#    1557                 :            :         // Set descriptor as active if necessary
#    1558         [ +  + ]:        402 :         if (active) {
#    1559         [ +  + ]:        176 :             if (!w_desc.descriptor->GetOutputType()) {
#    1560                 :          1 :                 warnings.push_back("Unknown output type, cannot set descriptor to active.");
#    1561                 :        175 :             } else {
#    1562                 :        175 :                 wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal);
#    1563                 :        175 :             }
#    1564                 :        226 :         } else {
#    1565         [ +  + ]:        226 :             if (w_desc.descriptor->GetOutputType()) {
#    1566                 :        112 :                 wallet.DeactivateScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal);
#    1567                 :        112 :             }
#    1568                 :        226 :         }
#    1569                 :            : 
#    1570                 :        402 :         result.pushKV("success", UniValue(true));
#    1571                 :        402 :     } catch (const UniValue& e) {
#    1572                 :         22 :         result.pushKV("success", UniValue(false));
#    1573                 :         22 :         result.pushKV("error", e);
#    1574                 :         22 :     }
#    1575         [ +  + ]:        419 :     if (warnings.size()) result.pushKV("warnings", warnings);
#    1576                 :        419 :     return result;
#    1577                 :        419 : }
#    1578                 :            : 
#    1579                 :            : RPCHelpMan importdescriptors()
#    1580                 :       1974 : {
#    1581                 :       1974 :     return RPCHelpMan{"importdescriptors",
#    1582                 :       1974 :                 "\nImport descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. Requires a new wallet backup.\n"
#    1583                 :       1974 :             "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n"
#    1584                 :       1974 :             "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n",
#    1585                 :       1974 :                 {
#    1586                 :       1974 :                     {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported",
#    1587                 :       1974 :                         {
#    1588                 :       1974 :                             {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
#    1589                 :       1974 :                                 {
#    1590                 :       1974 :                                     {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."},
#    1591                 :       1974 :                                     {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"},
#    1592                 :       1974 :                                     {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"},
#    1593                 :       1974 :                                     {"next_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If a ranged descriptor is set to active, this specifies the next index to generate addresses from"},
#    1594                 :       1974 :                                     {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n"
#    1595                 :       1974 :         "                                                              Use the string \"now\" to substitute the current synced blockchain time.\n"
#    1596                 :       1974 :         "                                                              \"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n"
#    1597                 :       1974 :         "                                                              0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n"
#    1598                 :       1974 :         "                                                              of all descriptors being imported will be scanned.",
#    1599                 :       1974 :                                         /*oneline_description=*/"", {"timestamp | \"now\"", "integer / string"}
#    1600                 :       1974 :                                     },
#    1601                 :       1974 :                                     {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"},
#    1602                 :       1974 :                                     {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"},
#    1603                 :       1974 :                                 },
#    1604                 :       1974 :                             },
#    1605                 :       1974 :                         },
#    1606                 :       1974 :                         "\"requests\""},
#    1607                 :       1974 :                 },
#    1608                 :       1974 :                 RPCResult{
#    1609                 :       1974 :                     RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result",
#    1610                 :       1974 :                     {
#    1611                 :       1974 :                         {RPCResult::Type::OBJ, "", "",
#    1612                 :       1974 :                         {
#    1613                 :       1974 :                             {RPCResult::Type::BOOL, "success", ""},
#    1614                 :       1974 :                             {RPCResult::Type::ARR, "warnings", /*optional=*/true, "",
#    1615                 :       1974 :                             {
#    1616                 :       1974 :                                 {RPCResult::Type::STR, "", ""},
#    1617                 :       1974 :                             }},
#    1618                 :       1974 :                             {RPCResult::Type::OBJ, "error", /*optional=*/true, "",
#    1619                 :       1974 :                             {
#    1620                 :       1974 :                                 {RPCResult::Type::ELISION, "", "JSONRPC error"},
#    1621                 :       1974 :                             }},
#    1622                 :       1974 :                         }},
#    1623                 :       1974 :                     }
#    1624                 :       1974 :                 },
#    1625                 :       1974 :                 RPCExamples{
#    1626                 :       1974 :                     HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, "
#    1627                 :       1974 :                                           "{ \"desc\": \"<my desccriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
#    1628                 :       1974 :                     HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'")
#    1629                 :       1974 :                 },
#    1630                 :       1974 :         [&](const RPCHelpMan& self, const JSONRPCRequest& main_request) -> UniValue
#    1631                 :       1974 : {
#    1632                 :        390 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request);
#    1633         [ -  + ]:        390 :     if (!pwallet) return NullUniValue;
#    1634                 :        390 :     CWallet& wallet{*pwallet};
#    1635                 :            : 
#    1636                 :            :     // Make sure the results are valid at least up to the most recent block
#    1637                 :            :     // the user could have gotten from another RPC command prior to now
#    1638                 :        390 :     wallet.BlockUntilSyncedToCurrentChain();
#    1639                 :            : 
#    1640                 :            :     //  Make sure wallet is a descriptor wallet
#    1641         [ -  + ]:        390 :     if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    1642                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "importdescriptors is not available for non-descriptor wallets");
#    1643                 :          0 :     }
#    1644                 :            : 
#    1645                 :        390 :     RPCTypeCheck(main_request.params, {UniValue::VARR, UniValue::VOBJ});
#    1646                 :            : 
#    1647                 :        390 :     WalletRescanReserver reserver(*pwallet);
#    1648         [ -  + ]:        390 :     if (!reserver.reserve()) {
#    1649                 :          0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
#    1650                 :          0 :     }
#    1651                 :            : 
#    1652                 :        390 :     const UniValue& requests = main_request.params[0];
#    1653                 :        390 :     const int64_t minimum_timestamp = 1;
#    1654                 :        390 :     int64_t now = 0;
#    1655                 :        390 :     int64_t lowest_timestamp = 0;
#    1656                 :        390 :     bool rescan = false;
#    1657                 :        390 :     UniValue response(UniValue::VARR);
#    1658                 :        390 :     {
#    1659                 :        390 :         LOCK(pwallet->cs_wallet);
#    1660                 :        390 :         EnsureWalletIsUnlocked(*pwallet);
#    1661                 :            : 
#    1662         [ -  + ]:        390 :         CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(lowest_timestamp).mtpTime(now)));
#    1663                 :            : 
#    1664                 :            :         // Get all timestamps and extract the lowest timestamp
#    1665         [ +  + ]:        419 :         for (const UniValue& request : requests.getValues()) {
#    1666                 :            :             // This throws an error if "timestamp" doesn't exist
#    1667                 :        419 :             const int64_t timestamp = std::max(GetImportTimestamp(request, now), minimum_timestamp);
#    1668                 :        419 :             const UniValue result = ProcessDescriptorImport(*pwallet, request, timestamp);
#    1669                 :        419 :             response.push_back(result);
#    1670                 :            : 
#    1671         [ +  + ]:        419 :             if (lowest_timestamp > timestamp ) {
#    1672                 :        269 :                 lowest_timestamp = timestamp;
#    1673                 :        269 :             }
#    1674                 :            : 
#    1675                 :            :             // If we know the chain tip, and at least one request was successful then allow rescan
#    1676 [ +  + ][ +  + ]:        419 :             if (!rescan && result["success"].get_bool()) {
#                 [ +  + ]
#    1677                 :        368 :                 rescan = true;
#    1678                 :        368 :             }
#    1679                 :        419 :         }
#    1680                 :        390 :         pwallet->ConnectScriptPubKeyManNotifiers();
#    1681                 :        390 :     }
#    1682                 :            : 
#    1683                 :            :     // Rescan the blockchain using the lowest timestamp
#    1684         [ +  + ]:        390 :     if (rescan) {
#    1685                 :        368 :         int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver, true /* update */);
#    1686                 :        368 :         {
#    1687                 :        368 :             LOCK(pwallet->cs_wallet);
#    1688                 :        368 :             pwallet->ReacceptWalletTransactions();
#    1689                 :        368 :         }
#    1690                 :            : 
#    1691         [ -  + ]:        368 :         if (pwallet->IsAbortingRescan()) {
#    1692                 :          0 :             throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user.");
#    1693                 :          0 :         }
#    1694                 :            : 
#    1695         [ -  + ]:        368 :         if (scanned_time > lowest_timestamp) {
#    1696                 :          0 :             std::vector<UniValue> results = response.getValues();
#    1697                 :          0 :             response.clear();
#    1698                 :          0 :             response.setArray();
#    1699                 :            : 
#    1700                 :            :             // Compose the response
#    1701         [ #  # ]:          0 :             for (unsigned int i = 0; i < requests.size(); ++i) {
#    1702                 :          0 :                 const UniValue& request = requests.getValues().at(i);
#    1703                 :            : 
#    1704                 :            :                 // If the descriptor timestamp is within the successfully scanned
#    1705                 :            :                 // range, or if the import result already has an error set, let
#    1706                 :            :                 // the result stand unmodified. Otherwise replace the result
#    1707                 :            :                 // with an error message.
#    1708 [ #  # ][ #  # ]:          0 :                 if (scanned_time <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
#                 [ #  # ]
#    1709                 :          0 :                     response.push_back(results.at(i));
#    1710                 :          0 :                 } else {
#    1711                 :          0 :                     UniValue result = UniValue(UniValue::VOBJ);
#    1712                 :          0 :                     result.pushKV("success", UniValue(false));
#    1713                 :          0 :                     result.pushKV(
#    1714                 :          0 :                         "error",
#    1715                 :          0 :                         JSONRPCError(
#    1716                 :          0 :                             RPC_MISC_ERROR,
#    1717                 :          0 :                             strprintf("Rescan failed for descriptor with timestamp %d. There was an error reading a "
#    1718                 :          0 :                                       "block from time %d, which is after or within %d seconds of key creation, and "
#    1719                 :          0 :                                       "could contain transactions pertaining to the desc. As a result, transactions "
#    1720                 :          0 :                                       "and coins using this desc may not appear in the wallet. This error could be "
#    1721                 :          0 :                                       "caused by pruning or data corruption (see bitcoind log for details) and could "
#    1722                 :          0 :                                       "be dealt with by downloading and rescanning the relevant blocks (see -reindex "
#    1723                 :          0 :                                       "option and rescanblockchain RPC).",
#    1724                 :          0 :                                 GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
#    1725                 :          0 :                     response.push_back(std::move(result));
#    1726                 :          0 :                 }
#    1727                 :          0 :             }
#    1728                 :          0 :         }
#    1729                 :        368 :     }
#    1730                 :            : 
#    1731                 :        390 :     return response;
#    1732                 :        390 : },
#    1733                 :       1974 :     };
#    1734                 :       1974 : }
#    1735                 :            : 
#    1736                 :            : RPCHelpMan listdescriptors()
#    1737                 :       1599 : {
#    1738                 :       1599 :     return RPCHelpMan{
#    1739                 :       1599 :         "listdescriptors",
#    1740                 :       1599 :         "\nList descriptors imported into a descriptor-enabled wallet.\n",
#    1741                 :       1599 :         {
#    1742                 :       1599 :             {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."}
#    1743                 :       1599 :         },
#    1744                 :       1599 :         RPCResult{RPCResult::Type::OBJ, "", "", {
#    1745                 :       1599 :             {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"},
#    1746                 :       1599 :             {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects",
#    1747                 :       1599 :             {
#    1748                 :       1599 :                 {RPCResult::Type::OBJ, "", "", {
#    1749                 :       1599 :                     {RPCResult::Type::STR, "desc", "Descriptor string representation"},
#    1750                 :       1599 :                     {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"},
#    1751                 :       1599 :                     {RPCResult::Type::BOOL, "active", "Activeness flag"},
#    1752                 :       1599 :                     {RPCResult::Type::BOOL, "internal", true, "Whether this is an internal or external descriptor; defined only for active descriptors"},
#    1753                 :       1599 :                     {RPCResult::Type::ARR_FIXED, "range", true, "Defined only for ranged descriptors", {
#    1754                 :       1599 :                         {RPCResult::Type::NUM, "", "Range start inclusive"},
#    1755                 :       1599 :                         {RPCResult::Type::NUM, "", "Range end inclusive"},
#    1756                 :       1599 :                     }},
#    1757                 :       1599 :                     {RPCResult::Type::NUM, "next", true, "The next index to generate addresses from; defined only for ranged descriptors"},
#    1758                 :       1599 :                 }},
#    1759                 :       1599 :             }}
#    1760                 :       1599 :         }},
#    1761                 :       1599 :         RPCExamples{
#    1762                 :       1599 :             HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "")
#    1763                 :       1599 :             + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true")
#    1764                 :       1599 :         },
#    1765                 :       1599 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#    1766                 :       1599 : {
#    1767                 :         15 :     const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
#    1768         [ -  + ]:         15 :     if (!wallet) return NullUniValue;
#    1769                 :            : 
#    1770         [ +  + ]:         15 :     if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    1771                 :          1 :         throw JSONRPCError(RPC_WALLET_ERROR, "listdescriptors is not available for non-descriptor wallets");
#    1772                 :          1 :     }
#    1773                 :            : 
#    1774 [ +  + ][ +  + ]:         14 :     const bool priv = !request.params[0].isNull() && request.params[0].get_bool();
#    1775         [ +  + ]:         14 :     if (priv) {
#    1776                 :          4 :         EnsureWalletIsUnlocked(*wallet);
#    1777                 :          4 :     }
#    1778                 :            : 
#    1779                 :         14 :     LOCK(wallet->cs_wallet);
#    1780                 :            : 
#    1781                 :         14 :     UniValue descriptors(UniValue::VARR);
#    1782                 :         14 :     const auto active_spk_mans = wallet->GetActiveScriptPubKeyMans();
#    1783         [ +  + ]:         39 :     for (const auto& spk_man : wallet->GetAllScriptPubKeyMans()) {
#    1784                 :         39 :         const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
#    1785         [ -  + ]:         39 :         if (!desc_spk_man) {
#    1786                 :          0 :             throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type.");
#    1787                 :          0 :         }
#    1788                 :         39 :         UniValue spk(UniValue::VOBJ);
#    1789                 :         39 :         LOCK(desc_spk_man->cs_desc_man);
#    1790                 :         39 :         const auto& wallet_descriptor = desc_spk_man->GetWalletDescriptor();
#    1791                 :         39 :         std::string descriptor;
#    1792                 :            : 
#    1793         [ +  + ]:         39 :         if (!desc_spk_man->GetDescriptorString(descriptor, priv)) {
#    1794                 :          1 :             throw JSONRPCError(RPC_WALLET_ERROR, "Can't get descriptor string.");
#    1795                 :          1 :         }
#    1796                 :         38 :         spk.pushKV("desc", descriptor);
#    1797                 :         38 :         spk.pushKV("timestamp", wallet_descriptor.creation_time);
#    1798                 :         38 :         spk.pushKV("active", active_spk_mans.count(desc_spk_man) != 0);
#    1799                 :         38 :         const auto internal = wallet->IsInternalScriptPubKeyMan(desc_spk_man);
#    1800         [ +  + ]:         38 :         if (internal.has_value()) {
#    1801                 :         32 :             spk.pushKV("internal", *internal);
#    1802                 :         32 :         }
#    1803         [ +  + ]:         38 :         if (wallet_descriptor.descriptor->IsRange()) {
#    1804                 :         37 :             UniValue range(UniValue::VARR);
#    1805                 :         37 :             range.push_back(wallet_descriptor.range_start);
#    1806                 :         37 :             range.push_back(wallet_descriptor.range_end - 1);
#    1807                 :         37 :             spk.pushKV("range", range);
#    1808                 :         37 :             spk.pushKV("next", wallet_descriptor.next_index);
#    1809                 :         37 :         }
#    1810                 :         38 :         descriptors.push_back(spk);
#    1811                 :         38 :     }
#    1812                 :            : 
#    1813                 :         13 :     UniValue response(UniValue::VOBJ);
#    1814                 :         13 :     response.pushKV("wallet_name", wallet->GetName());
#    1815                 :         13 :     response.pushKV("descriptors", descriptors);
#    1816                 :            : 
#    1817                 :         13 :     return response;
#    1818                 :         14 : },
#    1819                 :       1599 :     };
#    1820                 :       1599 : }
#    1821                 :            : 
#    1822                 :            : RPCHelpMan backupwallet()
#    1823                 :       1627 : {
#    1824                 :       1627 :     return RPCHelpMan{"backupwallet",
#    1825                 :       1627 :                 "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n",
#    1826                 :       1627 :                 {
#    1827                 :       1627 :                     {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"},
#    1828                 :       1627 :                 },
#    1829                 :       1627 :                 RPCResult{RPCResult::Type::NONE, "", ""},
#    1830                 :       1627 :                 RPCExamples{
#    1831                 :       1627 :                     HelpExampleCli("backupwallet", "\"backup.dat\"")
#    1832                 :       1627 :             + HelpExampleRpc("backupwallet", "\"backup.dat\"")
#    1833                 :       1627 :                 },
#    1834                 :       1627 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#    1835                 :       1627 : {
#    1836                 :         43 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
#    1837         [ -  + ]:         43 :     if (!pwallet) return NullUniValue;
#    1838                 :            : 
#    1839                 :            :     // Make sure the results are valid at least up to the most recent block
#    1840                 :            :     // the user could have gotten from another RPC command prior to now
#    1841                 :         43 :     pwallet->BlockUntilSyncedToCurrentChain();
#    1842                 :            : 
#    1843                 :         43 :     LOCK(pwallet->cs_wallet);
#    1844                 :            : 
#    1845                 :         43 :     std::string strDest = request.params[0].get_str();
#    1846         [ +  + ]:         43 :     if (!pwallet->BackupWallet(strDest)) {
#    1847                 :          8 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
#    1848                 :          8 :     }
#    1849                 :            : 
#    1850                 :         35 :     return NullUniValue;
#    1851                 :         43 : },
#    1852                 :       1627 :     };
#    1853                 :       1627 : }
#    1854                 :            : 
#    1855                 :            : 
#    1856                 :            : RPCHelpMan restorewallet()
#    1857                 :       1596 : {
#    1858                 :       1596 :     return RPCHelpMan{
#    1859                 :       1596 :         "restorewallet",
#    1860                 :       1596 :         "\nRestore and loads a wallet from backup.\n",
#    1861                 :       1596 :         {
#    1862                 :       1596 :             {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"},
#    1863                 :       1596 :             {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."},
#    1864                 :       1596 :             {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
#    1865                 :       1596 :         },
#    1866                 :       1596 :         RPCResult{
#    1867                 :       1596 :             RPCResult::Type::OBJ, "", "",
#    1868                 :       1596 :             {
#    1869                 :       1596 :                 {RPCResult::Type::STR, "name", "The wallet name if restored successfully."},
#    1870                 :       1596 :                 {RPCResult::Type::STR, "warning", "Warning message if wallet was not loaded cleanly."},
#    1871                 :       1596 :             }
#    1872                 :       1596 :         },
#    1873                 :       1596 :         RPCExamples{
#    1874                 :       1596 :             HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
#    1875                 :       1596 :             + HelpExampleRpc("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
#    1876                 :       1596 :             + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
#    1877                 :       1596 :             + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
#    1878                 :       1596 :         },
#    1879                 :       1596 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
#    1880                 :       1596 : {
#    1881                 :            : 
#    1882                 :         12 :     WalletContext& context = EnsureWalletContext(request.context);
#    1883                 :            : 
#    1884                 :         12 :     auto backup_file = fs::u8path(request.params[1].get_str());
#    1885                 :            : 
#    1886                 :         12 :     std::string wallet_name = request.params[0].get_str();
#    1887                 :            : 
#    1888         [ +  - ]:         12 :     std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool());
#    1889                 :            : 
#    1890                 :         12 :     DatabaseStatus status;
#    1891                 :         12 :     bilingual_str error;
#    1892                 :         12 :     std::vector<bilingual_str> warnings;
#    1893                 :            : 
#    1894                 :         12 :     const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings);
#    1895                 :            : 
#    1896                 :         12 :     HandleWalletError(wallet, status, error);
#    1897                 :            : 
#    1898                 :         12 :     UniValue obj(UniValue::VOBJ);
#    1899                 :         12 :     obj.pushKV("name", wallet->GetName());
#    1900                 :         12 :     obj.pushKV("warning", Join(warnings, Untranslated("\n")).original);
#    1901                 :            : 
#    1902                 :         12 :     return obj;
#    1903                 :            : 
#    1904                 :         12 : },
#    1905                 :       1596 :     };
#    1906                 :       1596 : }
#    1907                 :            : } // namespace wallet

Generated by: LCOV version 0-eol-96201-ge66f56f4af6a