LCOV - code coverage report
Current view: top level - src/wallet - wallet.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 89.9 % 2503 2251
Test Date: 2026-11-21 06:10:03 Functions: 97.8 % 225 220
Branches: 56.7 % 4026 2283

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <bitcoin-build-config.h>
       7                 :             : 
       8                 :             : #include <wallet/wallet.h>
       9                 :             : 
      10                 :             : #include <addresstype.h>
      11                 :             : #include <blockfilter.h>
      12                 :             : #include <chain.h>
      13                 :             : #include <coins.h>
      14                 :             : #include <common/args.h>
      15                 :             : #include <common/messages.h>
      16                 :             : #include <common/settings.h>
      17                 :             : #include <common/signmessage.h>
      18                 :             : #include <common/system.h>
      19                 :             : #include <consensus/amount.h>
      20                 :             : #include <consensus/consensus.h>
      21                 :             : #include <consensus/validation.h>
      22                 :             : #include <external_signer.h>
      23                 :             : #include <interfaces/chain.h>
      24                 :             : #include <interfaces/handler.h>
      25                 :             : #include <interfaces/wallet.h>
      26                 :             : #include <kernel/mempool_removal_reason.h>
      27                 :             : #include <kernel/types.h>
      28                 :             : #include <key.h>
      29                 :             : #include <key_io.h>
      30                 :             : #include <node/types.h>
      31                 :             : #include <outputtype.h>
      32                 :             : #include <policy/feerate.h>
      33                 :             : #include <policy/truc_policy.h>
      34                 :             : #include <primitives/block.h>
      35                 :             : #include <primitives/transaction.h>
      36                 :             : #include <psbt.h>
      37                 :             : #include <pubkey.h>
      38                 :             : #include <random.h>
      39                 :             : #include <script/descriptor.h>
      40                 :             : #include <script/interpreter.h>
      41                 :             : #include <script/script.h>
      42                 :             : #include <script/sign.h>
      43                 :             : #include <script/signingprovider.h>
      44                 :             : #include <script/solver.h>
      45                 :             : #include <serialize.h>
      46                 :             : #include <span.h>
      47                 :             : #include <streams.h>
      48                 :             : #include <support/allocators/secure.h>
      49                 :             : #include <support/allocators/zeroafterfree.h>
      50                 :             : #include <support/cleanse.h>
      51                 :             : #include <sync.h>
      52                 :             : #include <tinyformat.h>
      53                 :             : #include <uint256.h>
      54                 :             : #include <univalue.h>
      55                 :             : #include <util/check.h>
      56                 :             : #include <util/expected.h>
      57                 :             : #include <util/fs.h>
      58                 :             : #include <util/fs_helpers.h>
      59                 :             : #include <util/log.h>
      60                 :             : #include <util/moneystr.h>
      61                 :             : #include <util/result.h>
      62                 :             : #include <util/string.h>
      63                 :             : #include <util/time.h>
      64                 :             : #include <util/translation.h>
      65                 :             : #include <wallet/coincontrol.h>
      66                 :             : #include <wallet/context.h>
      67                 :             : #include <wallet/crypter.h>
      68                 :             : #include <wallet/db.h>
      69                 :             : #include <wallet/external_signer_scriptpubkeyman.h>
      70                 :             : #include <wallet/scan.h>
      71                 :             : #include <wallet/scriptpubkeyman.h>
      72                 :             : #include <wallet/transaction.h>
      73                 :             : #include <wallet/types.h>
      74                 :             : #include <wallet/walletdb.h>
      75                 :             : #include <wallet/walletutil.h>
      76                 :             : 
      77                 :             : #include <algorithm>
      78                 :             : #include <condition_variable>
      79                 :             : #include <exception>
      80                 :             : #include <limits>
      81                 :             : #include <optional>
      82                 :             : #include <stdexcept>
      83                 :             : #include <thread>
      84                 :             : #include <tuple>
      85                 :             : #include <utility>
      86                 :             : #include <variant>
      87                 :             : 
      88                 :             : struct KeyOriginInfo;
      89                 :             : 
      90                 :             : using common::AmountErrMsg;
      91                 :             : using common::AmountHighWarn;
      92                 :             : using common::PSBTError;
      93                 :             : using interfaces::FoundBlock;
      94                 :             : using kernel::ChainstateRole;
      95                 :             : using util::ReplaceAll;
      96                 :             : using util::ToString;
      97                 :             : 
      98                 :             : namespace wallet {
      99                 :             : 
     100                 :         193 : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
     101                 :             : {
     102                 :         386 :     const auto update_function = [&wallet_name](common::SettingsValue& setting_value) {
     103         [ +  + ]:         193 :         if (!setting_value.isArray()) setting_value.setArray();
     104         [ +  + ]:         361 :         for (const auto& value : setting_value.getValues()) {
     105   [ +  -  +  + ]:         169 :             if (value.isStr() && value.get_str() == wallet_name) return interfaces::SettingsAction::SKIP_WRITE;
     106                 :             :         }
     107         [ +  - ]:         192 :         setting_value.push_back(wallet_name);
     108                 :         192 :         return interfaces::SettingsAction::WRITE;
     109                 :         193 :     };
     110   [ +  -  +  - ]:         193 :     return chain.updateRwSetting("wallet", update_function);
     111                 :             : }
     112                 :             : 
     113                 :          23 : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
     114                 :             : {
     115                 :          46 :     const auto update_function = [&wallet_name](common::SettingsValue& setting_value) {
     116         [ +  + ]:          23 :         if (!setting_value.isArray()) {
     117   [ +  +  +  - ]:           3 :             if (wallet_name.empty() && setting_value.isNull()) {
     118                 :             :                 // Empty setting suppresses backwards-compatible default wallet autoload.
     119                 :           1 :                 setting_value.setArray();
     120                 :           1 :                 return interfaces::SettingsAction::WRITE;
     121                 :             :             }
     122                 :             :             return interfaces::SettingsAction::SKIP_WRITE;
     123                 :             :         }
     124                 :          20 :         common::SettingsValue new_value(common::SettingsValue::VARR);
     125   [ +  -  +  + ]:          83 :         for (const auto& value : setting_value.getValues()) {
     126   [ +  -  +  -  :          63 :             if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
          +  +  +  -  +  
                      - ]
     127                 :             :         }
     128   [ -  +  -  +  :          20 :         if (new_value.size() == setting_value.size()) return interfaces::SettingsAction::SKIP_WRITE;
                   +  + ]
     129                 :          12 :         setting_value = std::move(new_value);
     130                 :          12 :         return interfaces::SettingsAction::WRITE;
     131                 :          20 :     };
     132   [ +  -  +  - ]:          23 :     return chain.updateRwSetting("wallet", update_function);
     133                 :             : }
     134                 :             : 
     135                 :        1958 : static void UpdateWalletSetting(interfaces::Chain& chain,
     136                 :             :                                 const std::string& wallet_name,
     137                 :             :                                 std::optional<bool> load_on_startup,
     138                 :             :                                 std::vector<bilingual_str>& warnings)
     139                 :             : {
     140         [ +  + ]:        1958 :     if (!load_on_startup) return;
     141   [ +  +  +  + ]:         206 :     if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
     142   [ +  -  +  - ]:           4 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
     143   [ +  +  +  + ]:         204 :     } else if (!load_on_startup.value() && !RemoveWalletSetting(chain, wallet_name)) {
     144   [ +  -  +  - ]:           2 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
     145                 :             :     }
     146                 :             : }
     147                 :             : 
     148                 :             : /**
     149                 :             :  * Refresh mempool status so the wallet is in an internally consistent state and
     150                 :             :  * immediately knows the transaction's status: Whether it can be considered
     151                 :             :  * trusted and is eligible to be abandoned ...
     152                 :             :  */
     153                 :       18209 : static void RefreshMempoolStatus(CWalletTx& tx, interfaces::Chain& chain)
     154                 :             : {
     155         [ +  + ]:       18209 :     if (chain.isInMempool(tx.GetHash())) {
     156         [ -  + ]:        3936 :         tx.m_state = TxStateInMempool();
     157         [ +  + ]:       14273 :     } else if (tx.state<TxStateInMempool>()) {
     158         [ -  + ]:         319 :         tx.m_state = TxStateInactive();
     159                 :             :     }
     160                 :       18209 : }
     161                 :             : 
     162                 :        1023 : bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
     163                 :             : {
     164                 :        1023 :     LOCK(context.wallets_mutex);
     165         [ -  + ]:        1023 :     assert(wallet);
     166         [ +  - ]:        1023 :     std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
     167         [ +  - ]:        1023 :     if (i != context.wallets.end()) return false;
     168         [ +  - ]:        1023 :     context.wallets.push_back(wallet);
     169         [ +  - ]:        1023 :     wallet->ConnectScriptPubKeyManNotifiers();
     170         [ +  - ]:        1023 :     wallet->NotifyCanGetAddressesChanged();
     171                 :             :     return true;
     172                 :        1023 : }
     173                 :             : 
     174                 :        1023 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
     175                 :             : {
     176         [ -  + ]:        1023 :     assert(wallet);
     177                 :             : 
     178                 :        1023 :     interfaces::Chain& chain = wallet->chain();
     179         [ -  + ]:        1023 :     std::string name = wallet->GetName();
     180   [ +  -  +  - ]:        3069 :     WITH_LOCK(wallet->cs_wallet, wallet->WriteBestBlock());
     181                 :             : 
     182                 :             :     // Unregister with the validation interface which also drops shared pointers.
     183         [ +  - ]:        1023 :     wallet->DisconnectChainNotifications();
     184                 :        1023 :     {
     185         [ +  - ]:        1023 :         LOCK(context.wallets_mutex);
     186                 :        1023 :         std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
     187   [ -  +  -  - ]:        1023 :         if (i == context.wallets.end()) return false;
     188         [ +  - ]:        1023 :         context.wallets.erase(i);
     189                 :           0 :     }
     190                 :             :     // Notify unload so that upper layers release the shared pointer.
     191         [ +  - ]:        1023 :     wallet->NotifyUnload();
     192                 :             : 
     193                 :             :     // Write the wallet setting
     194         [ +  - ]:        1023 :     UpdateWalletSetting(chain, name, load_on_start, warnings);
     195                 :             : 
     196                 :             :     return true;
     197                 :        1023 : }
     198                 :             : 
     199                 :           0 : bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
     200                 :             : {
     201                 :           0 :     std::vector<bilingual_str> warnings;
     202         [ #  # ]:           0 :     return RemoveWallet(context, wallet, load_on_start, warnings);
     203                 :           0 : }
     204                 :             : 
     205                 :        1466 : std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context)
     206                 :             : {
     207                 :        1466 :     LOCK(context.wallets_mutex);
     208         [ +  - ]:        1466 :     return context.wallets;
     209                 :        1466 : }
     210                 :             : 
     211                 :        4665 : std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count)
     212                 :             : {
     213                 :        4665 :     LOCK(context.wallets_mutex);
     214         [ -  + ]:        4665 :     count = context.wallets.size();
     215   [ +  +  +  -  :        9321 :     return count == 1 ? context.wallets[0] : nullptr;
                   +  - ]
     216                 :        4665 : }
     217                 :             : 
     218                 :       16449 : std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name)
     219                 :             : {
     220                 :       16449 :     LOCK(context.wallets_mutex);
     221         [ +  + ]:       81131 :     for (const std::shared_ptr<CWallet>& wallet : context.wallets) {
     222   [ +  +  +  -  :       97520 :         if (wallet->GetName() == name) return wallet;
                   +  - ]
     223                 :             :     }
     224                 :          60 :     return nullptr;
     225                 :       16449 : }
     226                 :             : 
     227                 :           1 : std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet)
     228                 :             : {
     229                 :           1 :     LOCK(context.wallets_mutex);
     230         [ +  - ]:           1 :     auto it = context.wallet_load_fns.emplace(context.wallet_load_fns.end(), std::move(load_wallet));
     231   [ +  -  +  -  :           3 :     return interfaces::MakeCleanupHandler([&context, it] { LOCK(context.wallets_mutex); context.wallet_load_fns.erase(it); });
                   +  - ]
     232                 :           1 : }
     233                 :             : 
     234                 :        1046 : void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
     235                 :             : {
     236                 :        1046 :     LOCK(context.wallets_mutex);
     237         [ +  + ]:        1047 :     for (auto& load_wallet : context.wallet_load_fns) {
     238   [ +  -  +  - ]:           1 :         load_wallet(interfaces::MakeWallet(context, wallet));
     239                 :             :     }
     240                 :        1046 : }
     241                 :             : 
     242                 :             : static GlobalMutex g_loading_wallet_mutex;
     243                 :             : static GlobalMutex g_wallet_release_mutex;
     244                 :             : static std::condition_variable g_wallet_release_cv;
     245                 :             : static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
     246                 :             : static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
     247                 :             : 
     248                 :             : // Custom deleter for shared_ptr<CWallet>.
     249                 :        1140 : static void FlushAndDeleteWallet(CWallet* wallet)
     250                 :             : {
     251         [ -  + ]:        1140 :     const std::string name = wallet->GetName();
     252         [ +  - ]:        1140 :     wallet->WalletLogPrintf("Releasing wallet %s..", name);
     253                 :        1140 :     delete wallet;
     254                 :             :     // Wallet is now released, notify WaitForDeleteWallet, if any.
     255                 :        1140 :     {
     256         [ +  - ]:        1140 :         LOCK(g_wallet_release_mutex);
     257         [ +  + ]:        1140 :         if (g_unloading_wallet_set.erase(name) == 0) {
     258                 :             :             // WaitForDeleteWallet was not called for this wallet, all done.
     259         [ +  - ]:          98 :             return;
     260                 :             :         }
     261                 :          98 :     }
     262                 :        1042 :     g_wallet_release_cv.notify_all();
     263                 :        1140 : }
     264                 :             : 
     265                 :        1042 : void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet)
     266                 :             : {
     267                 :             :     // Mark wallet for unloading.
     268         [ -  + ]:        1042 :     const std::string name = wallet->GetName();
     269                 :        1042 :     {
     270         [ +  - ]:        1042 :         LOCK(g_wallet_release_mutex);
     271         [ +  - ]:        1042 :         g_unloading_wallet_set.insert(name);
     272                 :             :         // Do not expect to be the only one removing this wallet.
     273                 :             :         // Multiple threads could simultaneously be waiting for deletion.
     274                 :           0 :     }
     275                 :             : 
     276                 :             :     // Time to ditch our shared_ptr and wait for FlushAndDeleteWallet call.
     277                 :        1042 :     wallet.reset();
     278                 :        1042 :     {
     279         [ +  - ]:        1042 :         WAIT_LOCK(g_wallet_release_mutex, lock);
     280         [ -  + ]:        1042 :         while (g_unloading_wallet_set.contains(name)) {
     281         [ #  # ]:           0 :             g_wallet_release_cv.wait(lock);
     282                 :             :         }
     283                 :        1042 :     }
     284                 :        1042 : }
     285                 :             : 
     286                 :             : namespace {
     287                 :         297 : std::shared_ptr<CWallet> LoadWalletInternal(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     288                 :             : {
     289                 :         297 :     try {
     290         [ +  - ]:         297 :         std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
     291         [ +  + ]:         297 :         if (!database) {
     292   [ +  -  +  -  :         133 :             error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
          +  -  +  -  +  
                      - ]
     293                 :          19 :             return nullptr;
     294                 :             :         }
     295                 :             : 
     296   [ +  -  +  - ]:         278 :         context.chain->initMessage(_("Loading wallet…"));
     297         [ +  - ]:         278 :         std::shared_ptr<CWallet> wallet = CWallet::LoadExisting(context, name, std::move(database), error, warnings);
     298         [ +  + ]:         278 :         if (!wallet) {
     299   [ +  -  +  -  :          84 :             error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
          +  -  +  -  +  
                      - ]
     300                 :          12 :             status = DatabaseStatus::FAILED_LOAD;
     301                 :          12 :             return nullptr;
     302                 :             :         }
     303                 :             : 
     304         [ +  - ]:         266 :         NotifyWalletLoaded(context, wallet);
     305         [ +  - ]:         266 :         AddWallet(context, wallet);
     306         [ +  - ]:         266 :         wallet->postInitProcess();
     307                 :             : 
     308                 :             :         // Write the wallet setting
     309         [ +  - ]:         266 :         UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
     310                 :             : 
     311                 :         266 :         return wallet;
     312         [ -  - ]:         297 :     } catch (const std::runtime_error& e) {
     313   [ -  -  -  - ]:           0 :         error = Untranslated(e.what());
     314                 :           0 :         status = DatabaseStatus::FAILED_LOAD;
     315                 :           0 :         return nullptr;
     316                 :           0 :     }
     317                 :             : }
     318                 :             : } // namespace
     319                 :             : 
     320                 :         301 : std::shared_ptr<CWallet> LoadWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     321                 :             : {
     322         [ +  - ]:         903 :     auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
     323         [ +  + ]:         301 :     if (!result.second) {
     324         [ +  - ]:           8 :         error = Untranslated("Wallet already loading.");
     325                 :           4 :         status = DatabaseStatus::FAILED_LOAD;
     326                 :           4 :         return nullptr;
     327                 :             :     }
     328                 :         297 :     auto wallet = LoadWalletInternal(context, name, load_on_start, options, status, error, warnings);
     329   [ +  -  +  - ]:         594 :     WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
     330         [ -  + ]:         297 :     return wallet;
     331                 :         297 : }
     332                 :             : 
     333                 :         685 : std::shared_ptr<CWallet> CreateWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     334                 :             : {
     335                 :             :     // Wallet must have a non-empty name
     336         [ +  + ]:         685 :     if (name.empty()) {
     337         [ +  - ]:           4 :         error = Untranslated("Wallet name cannot be empty");
     338                 :           2 :         status = DatabaseStatus::FAILED_NEW_UNNAMED;
     339                 :           2 :         return nullptr;
     340                 :             :     }
     341                 :             : 
     342                 :         683 :     uint64_t wallet_creation_flags = options.create_flags;
     343                 :         683 :     const SecureString& passphrase = options.create_passphrase;
     344                 :         683 :     bool born_encrypted = !passphrase.empty();
     345                 :             : 
     346                 :             :     // Only descriptor wallets can be created
     347                 :         683 :     Assert(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS);
     348                 :         683 :     options.require_format = DatabaseFormat::SQLITE;
     349                 :             : 
     350                 :             : 
     351                 :             :     // Private keys must be disabled for an external signer wallet
     352   [ +  +  +  + ]:         683 :     if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     353         [ +  - ]:           2 :         error = Untranslated("Private keys must be disabled when using an external signer");
     354                 :           1 :         status = DatabaseStatus::FAILED_CREATE;
     355                 :           1 :         return nullptr;
     356                 :             :     }
     357                 :             : 
     358                 :             :     // Do not allow a passphrase when private keys are disabled
     359   [ +  +  +  + ]:         682 :     if (born_encrypted && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     360         [ +  - ]:           8 :         error = Untranslated("Passphrase provided but private keys are disabled. A passphrase is only used to encrypt private keys, so cannot be used for wallets with private keys disabled.");
     361                 :           4 :         status = DatabaseStatus::FAILED_CREATE;
     362                 :           4 :         return nullptr;
     363                 :             :     }
     364                 :             : 
     365                 :             :     // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
     366                 :         678 :     std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
     367         [ +  + ]:         678 :     if (!database) {
     368   [ +  -  +  -  :         196 :         error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
          +  -  +  -  +  
                      - ]
     369                 :          28 :         status = DatabaseStatus::FAILED_VERIFY;
     370                 :          28 :         return nullptr;
     371                 :             :     }
     372                 :             : 
     373                 :             :     // Make the wallet
     374   [ +  -  +  - ]:         650 :     context.chain->initMessage(_("Creating wallet…"));
     375         [ +  + ]:         650 :     std::shared_ptr<CWallet> wallet = CWallet::CreateNew(context, name, std::move(database), wallet_creation_flags, born_encrypted, error, warnings);
     376         [ +  + ]:         647 :     if (!wallet) {
     377   [ +  -  +  -  :           7 :         error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
          +  -  +  -  +  
                      - ]
     378                 :           1 :         status = DatabaseStatus::FAILED_CREATE;
     379                 :           1 :         return nullptr;
     380                 :             :     }
     381                 :             : 
     382                 :             :     // Encrypt the wallet
     383         [ +  + ]:         646 :     if (born_encrypted) {
     384   [ +  -  -  + ]:          17 :         if (!wallet->EncryptWallet(passphrase)) {
     385   [ #  #  #  # ]:           0 :             error = Untranslated("Error: Wallet created but failed to encrypt.");
     386                 :           0 :             status = DatabaseStatus::FAILED_ENCRYPT;
     387                 :           0 :             return nullptr;
     388                 :             :         }
     389                 :             :     }
     390                 :             : 
     391   [ +  -  +  - ]:        1938 :     WITH_LOCK(wallet->cs_wallet, wallet->LogStats());
     392         [ +  - ]:         646 :     NotifyWalletLoaded(context, wallet);
     393         [ +  - ]:         646 :     AddWallet(context, wallet);
     394         [ +  - ]:         646 :     wallet->postInitProcess();
     395                 :             : 
     396                 :             :     // Write the wallet settings
     397         [ +  - ]:         646 :     UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
     398                 :             : 
     399                 :         646 :     status = DatabaseStatus::SUCCESS;
     400                 :         646 :     return wallet;
     401                 :         678 : }
     402                 :             : 
     403                 :             : // Re-creates wallet from the backup file by renaming and moving it into the wallet's directory.
     404                 :             : // If 'load_after_restore=true', the wallet object will be fully initialized and appended to the context.
     405                 :          53 : std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& backup_file, const std::string& wallet_name, std::optional<bool> load_on_start, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings, bool load_after_restore, bool allow_unnamed)
     406                 :             : {
     407                 :             :     // Error if the wallet name is empty and allow_unnamed == false
     408                 :             :     // allow_unnamed == true is only used by migration to migrate an unnamed wallet
     409   [ +  +  +  + ]:          53 :     if (!allow_unnamed && wallet_name.empty()) {
     410         [ +  - ]:           2 :         error = Untranslated("Wallet name cannot be empty");
     411                 :           1 :         status = DatabaseStatus::FAILED_NEW_UNNAMED;
     412                 :           1 :         return nullptr;
     413                 :             :     }
     414                 :             : 
     415         [ +  - ]:          52 :     DatabaseOptions options;
     416         [ +  - ]:          52 :     ReadDatabaseArgs(*context.args, options);
     417                 :          52 :     options.require_existing = true;
     418                 :             : 
     419   [ -  +  +  -  :         104 :     const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::u8path(wallet_name));
             +  -  +  - ]
     420   [ +  -  +  - ]:         104 :     auto wallet_file = wallet_path / "wallet.dat";
     421                 :          52 :     std::shared_ptr<CWallet> wallet;
     422                 :          52 :     bool wallet_file_copied = false;
     423                 :          52 :     bool created_parent_dir = false;
     424                 :             : 
     425                 :          52 :     try {
     426   [ +  -  +  + ]:          52 :         if (!fs::exists(backup_file)) {
     427   [ +  -  +  - ]:           2 :             error = Untranslated("Backup file does not exist");
     428                 :           1 :             status = DatabaseStatus::FAILED_INVALID_BACKUP_FILE;
     429                 :           1 :             return nullptr;
     430                 :             :         }
     431                 :             : 
     432                 :             :         // Wallet directories are allowed to exist, but must not contain a .dat file.
     433                 :             :         // Any existing wallet database is treated as a hard failure to prevent overwriting.
     434   [ +  -  +  + ]:          51 :         if (fs::exists(wallet_path)) {
     435                 :             :             // If this is a file, it is the db and we don't want to overwrite it.
     436   [ +  -  -  + ]:          11 :             if (!fs::is_directory(wallet_path)) {
     437   [ #  #  #  #  :           0 :                 error = Untranslated(strprintf("Failed to restore wallet. Database file exists '%s'.", fs::PathToString(wallet_path)));
                   #  # ]
     438                 :           0 :                 status = DatabaseStatus::FAILED_ALREADY_EXISTS;
     439                 :           0 :                 return nullptr;
     440                 :             :             }
     441                 :             : 
     442                 :             :             // Check we are not going to overwrite an existing db file
     443   [ +  -  +  + ]:          11 :             if (fs::exists(wallet_file)) {
     444   [ -  +  +  -  :           6 :                 error = Untranslated(strprintf("Failed to restore wallet. Database file exists in '%s'.", fs::PathToString(wallet_file)));
                   +  - ]
     445                 :           2 :                 status = DatabaseStatus::FAILED_ALREADY_EXISTS;
     446                 :           2 :                 return nullptr;
     447                 :             :             }
     448                 :             :         } else {
     449                 :             :             // The directory doesn't exist, create it
     450   [ +  -  -  + ]:          40 :             if (!TryCreateDirectories(wallet_path)) {
     451   [ #  #  #  #  :           0 :                 error = Untranslated(strprintf("Failed to restore database path '%s'.", fs::PathToString(wallet_path)));
                   #  # ]
     452                 :           0 :                 status = DatabaseStatus::FAILED_ALREADY_EXISTS;
     453                 :           0 :                 return nullptr;
     454                 :             :             }
     455                 :             :             created_parent_dir = true;
     456                 :             :         }
     457                 :             : 
     458         [ +  - ]:          49 :         fs::copy_file(backup_file, wallet_file, fs::copy_options::none);
     459                 :          49 :         wallet_file_copied = true;
     460                 :             : 
     461         [ +  + ]:          49 :         if (load_after_restore) {
     462   [ +  -  -  + ]:          86 :             wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
     463                 :             :         }
     464         [ -  - ]:           0 :     } catch (const std::exception& e) {
     465         [ -  - ]:           0 :         assert(!wallet);
     466   [ -  -  -  -  :           0 :         if (!error.empty()) error += Untranslated("\n");
             -  -  -  - ]
     467   [ -  -  -  -  :           0 :         error += Untranslated(strprintf("Unexpected exception: %s", e.what()));
                   -  - ]
     468                 :           0 :     }
     469                 :             : 
     470                 :             :     // Remove created wallet path only when loading fails
     471   [ +  -  +  + ]:          43 :     if (load_after_restore && !wallet) {
     472   [ +  -  +  - ]:          14 :         if (wallet_file_copied) fs::remove(wallet_file);
     473                 :             :         // Clean up the parent directory if we created it during restoration.
     474                 :             :         // As we have created it, it must be empty after deleting the wallet file.
     475         [ +  - ]:          14 :         if (created_parent_dir) {
     476   [ +  -  +  - ]:          14 :             Assume(fs::is_empty(wallet_path));
     477         [ +  - ]:          14 :             fs::remove(wallet_path);
     478                 :             :         }
     479                 :             :     }
     480                 :             : 
     481                 :          49 :     return wallet;
     482                 :         156 : }
     483                 :             : 
     484                 :        1240 : CWallet::CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
     485                 :        1240 :     : m_chain(chain),
     486                 :        2480 :       m_name(name),
     487         [ +  - ]:        1240 :       m_database(std::move(database)),
     488   [ +  -  +  -  :        2480 :       m_scanner(std::make_unique<ChainScanner>(*this))
          -  +  +  -  +  
             -  +  -  +  
                      - ]
     489                 :             : {
     490                 :        1240 : }
     491                 :             : 
     492                 :        2422 : CWallet::~CWallet()
     493                 :             : {
     494                 :             :     // Should not have slots connected at this point.
     495         [ -  + ]:        1240 :     assert(NotifyUnload.empty());
     496                 :        2422 : }
     497                 :             : 
     498                 :        5546 : ChainScanner& CWallet::Scanner() { return *m_scanner; }
     499                 :         454 : const ChainScanner& CWallet::Scanner() const { return *m_scanner; }
     500                 :             : 
     501                 :             : /** @defgroup mapWallet
     502                 :             :  *
     503                 :             :  * @{
     504                 :             :  */
     505                 :             : 
     506                 :       87563 : const CWalletTx* CWallet::GetWalletTx(const Txid& hash) const
     507                 :             : {
     508                 :       87563 :     AssertLockHeld(cs_wallet);
     509                 :       87563 :     const auto it = mapWallet.find(hash);
     510         [ +  + ]:       87563 :     if (it == mapWallet.end())
     511                 :             :         return nullptr;
     512                 :       87153 :     return &(it->second);
     513                 :             : }
     514                 :             : 
     515                 :         532 : void CWallet::UpgradeDescriptorCache()
     516                 :             : {
     517   [ +  +  +  +  :         532 :     if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) || IsLocked() || IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
                   +  + ]
     518                 :         523 :         return;
     519                 :             :     }
     520                 :             : 
     521         [ +  + ]:          55 :     for (ScriptPubKeyMan* spkm : GetAllScriptPubKeyMans()) {
     522         [ +  - ]:          46 :         DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
     523         [ +  - ]:          46 :         desc_spkm->UpgradeDescriptorCache();
     524                 :             :     }
     525                 :           9 :     SetWalletFlag(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
     526                 :             : }
     527                 :             : 
     528                 :             : /* Given a wallet passphrase string and an unencrypted master key, determine the proper key
     529                 :             :  * derivation parameters (should take at least 100ms) and encrypt the master key. */
     530                 :          43 : static bool EncryptMasterKey(const SecureString& wallet_passphrase, const CKeyingMaterial& plain_master_key, CMasterKey& master_key)
     531                 :             : {
     532                 :          43 :     constexpr MillisecondsDouble target_time{100};
     533                 :          43 :     CCrypter crypter;
     534         [ +  - ]:          43 :     CMasterKey updated_master_key{master_key};
     535                 :             : 
     536                 :             :     // Get the weighted average of iterations we can do in 100ms over 2 runs.
     537         [ +  + ]:          95 :     for (int i = 0; i < 2; i++){
     538                 :          69 :         auto start_time{NodeClock::now()};
     539   [ -  +  +  - ]:          69 :         const bool key_set{crypter.SetKeyFromPassphrase(wallet_passphrase, updated_master_key.vchSalt, updated_master_key.nDeriveIterations, updated_master_key.nDerivationMethod)};
     540                 :          69 :         auto elapsed_time{NodeClock::now() - start_time};
     541         [ +  - ]:          69 :         if (!key_set) {
     542                 :             :             return false;
     543                 :             :         }
     544                 :             : 
     545         [ +  + ]:          69 :         if (elapsed_time <= 0s) {
     546                 :             :             // We are probably in a test with a mocked clock.
     547                 :          17 :             updated_master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
     548                 :          17 :             break;
     549                 :             :         }
     550                 :             : 
     551                 :             :         // target_iterations : elapsed_iterations :: target_time : elapsed_time
     552                 :          52 :         const double target_iterations{updated_master_key.nDeriveIterations * target_time / elapsed_time};
     553   [ +  -  +  - ]:          52 :         if (target_iterations < 1 || target_iterations > std::numeric_limits<unsigned int>::max()) {
     554                 :             :             return false;
     555                 :             :         }
     556                 :             :         // Get the weighted average with previous runs. Use 64-bit math so the
     557                 :             :         // sum cannot wrap; the average of two unsigned int values fits in one.
     558                 :          52 :         updated_master_key.nDeriveIterations = (uint64_t{updated_master_key.nDeriveIterations} * i + static_cast<unsigned int>(target_iterations)) / (i + 1);
     559                 :             :     }
     560                 :             : 
     561         [ +  + ]:          43 :     if (updated_master_key.nDeriveIterations < CMasterKey::DEFAULT_DERIVE_ITERATIONS) {
     562                 :           1 :         updated_master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS;
     563                 :             :     }
     564                 :             : 
     565   [ -  +  +  -  :          43 :     if (!crypter.SetKeyFromPassphrase(wallet_passphrase, updated_master_key.vchSalt, updated_master_key.nDeriveIterations, updated_master_key.nDerivationMethod)) {
                   +  - ]
     566                 :             :         return false;
     567                 :             :     }
     568   [ +  -  +  - ]:          43 :     if (!crypter.Encrypt(plain_master_key, updated_master_key.vchCryptedKey)) {
     569                 :             :         return false;
     570                 :             :     }
     571                 :             : 
     572                 :          43 :     master_key = std::move(updated_master_key);
     573                 :          43 :     return true;
     574                 :          43 : }
     575                 :             : 
     576                 :          98 : static bool DecryptMasterKey(const SecureString& wallet_passphrase, const CMasterKey& master_key, CKeyingMaterial& plain_master_key)
     577                 :             : {
     578                 :          98 :     CCrypter crypter;
     579   [ -  +  +  -  :          98 :     if (!crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod)) {
                   +  - ]
     580                 :             :         return false;
     581                 :             :     }
     582   [ -  +  +  -  :          98 :     if (!crypter.Decrypt(master_key.vchCryptedKey, plain_master_key)) {
                   +  + ]
     583                 :          11 :         return false;
     584                 :             :     }
     585                 :             : 
     586                 :             :     return true;
     587                 :          98 : }
     588                 :             : 
     589                 :          11 : static util::Unexpected<WalletError> UnlockPassphraseError(const SecureString& passphrase)
     590                 :             : {
     591         [ +  + ]:          11 :     bilingual_str message;
     592         [ +  + ]:          11 :     if (passphrase.find('\0') != std::string::npos) {
     593                 :             :         // The passphrase has a null character (see #27067 for details)
     594         [ +  - ]:           6 :         message = _("Error: The wallet passphrase entered is incorrect. "
     595                 :             :                     "It contains a null character (ie - a zero byte). "
     596                 :             :                     "If the passphrase was set with a version of this software prior to 25.0, "
     597                 :             :                     "please try again with only the characters up to — but not including — "
     598                 :             :                     "the first null character. If this is successful, please set a new "
     599                 :           3 :                     "passphrase to avoid this issue in the future.");
     600         [ +  + ]:           8 :     } else if (passphrase.empty()) {
     601         [ +  - ]:           2 :         message = _("Error: The wallet passphrase was not provided");
     602                 :             :     } else {
     603         [ +  - ]:          14 :         message = _("Error: The wallet passphrase entered was incorrect.");
     604                 :             :     }
     605                 :          22 :     return util::Unexpected{WalletError{WalletErrorCode::PassphraseIncorrect, std::move(message)}};
     606                 :          11 : }
     607                 :             : 
     608                 :          92 : util::Expected<void, WalletError> CWallet::Unlock(const SecureString& strWalletPassphrase)
     609                 :             : {
     610                 :          92 :     CKeyingMaterial plain_master_key;
     611                 :             : 
     612                 :          92 :     {
     613         [ +  - ]:          92 :         LOCK(cs_wallet);
     614   [ +  -  +  + ]:         101 :         for (const auto& [_, master_key] : mapMasterKeys)
     615                 :             :         {
     616   [ +  -  +  + ]:          92 :             if (!DecryptMasterKey(strWalletPassphrase, master_key, plain_master_key)) {
     617                 :           9 :                 continue; // try another master key
     618                 :             :             }
     619   [ +  -  +  - ]:          83 :             if (Unlock(plain_master_key)) {
     620                 :             :                 // Now that we've unlocked, upgrade the descriptor cache
     621         [ +  - ]:          83 :                 UpgradeDescriptorCache();
     622                 :             : 
     623   [ +  +  -  + ]:          83 :                 if (!m_last_decrypted_features || *m_last_decrypted_features != WALLET_CLIENT_FEATURES) {
     624                 :             :                     // Write the current wallet client features to LAST_DECRYPTED_FEATURES.
     625                 :             :                     // This must be done after all automatic upgrades so that those upgrades can be
     626                 :             :                     // performed in an upgrade-downgrade-upgrade scenario.
     627         [ +  - ]:          38 :                     WalletBatch batch(GetDatabase());
     628   [ +  -  +  - ]:          38 :                     if (batch.WriteLastDecryptedFeatures()) {
     629         [ +  - ]:          38 :                         SetLastDecryptedFeatures(WALLET_CLIENT_FEATURES);
     630                 :             :                     }
     631                 :          38 :                 }
     632                 :             : 
     633         [ +  - ]:          83 :                 return {};
     634                 :             :             }
     635                 :             :         }
     636                 :          83 :     }
     637         [ +  - ]:          27 :     return UnlockPassphraseError(strWalletPassphrase);
     638                 :          92 : }
     639                 :             : 
     640                 :           6 : util::Expected<void, WalletError> CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
     641                 :             : {
     642                 :           6 :     bool fWasLocked = IsLocked();
     643                 :             : 
     644                 :           6 :     {
     645         [ +  - ]:           6 :         LOCK2(m_relock_mutex, cs_wallet);
     646         [ +  - ]:           6 :         Lock();
     647                 :             : 
     648                 :           6 :         CKeyingMaterial plain_master_key;
     649   [ +  -  +  - ]:           6 :         for (auto& [master_key_id, master_key] : mapMasterKeys)
     650                 :             :         {
     651   [ +  -  +  + ]:           6 :             if (!DecryptMasterKey(strOldWalletPassphrase, master_key, plain_master_key)) {
     652         [ +  - ]:           6 :                 return UnlockPassphraseError(strOldWalletPassphrase);
     653                 :             :             }
     654   [ +  -  +  - ]:           4 :             if (Unlock(plain_master_key))
     655                 :             :             {
     656   [ +  -  +  - ]:           4 :                 if (fWasLocked) Lock();
     657         [ +  - ]:           4 :                 CMasterKey new_master_key{master_key};
     658   [ +  -  -  + ]:           4 :                 if (!EncryptMasterKey(strNewWalletPassphrase, plain_master_key, new_master_key)) {
     659         [ #  # ]:           0 :                     return util::Unexpected{WalletError{WalletErrorCode::GenericError, _("Error: Unable to encrypt encryption key with new passphrase")}};
     660                 :             :                 }
     661   [ +  -  +  -  :           8 :                 if (!WalletBatch(GetDatabase()).WriteMasterKey(master_key_id, new_master_key)) {
                   +  + ]
     662         [ +  - ]:           4 :                     return util::Unexpected{WalletError{WalletErrorCode::GenericError, _("Error: Writing the new encryption key to the wallet database failed")}};
     663                 :             :                 }
     664         [ +  - ]:           3 :                 WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i", new_master_key.nDeriveIterations);
     665                 :           3 :                 master_key = std::move(new_master_key);
     666                 :           3 :                 return {};
     667                 :           4 :             }
     668                 :             :         }
     669   [ -  -  -  -  :          18 :     }
             +  -  +  - ]
     670                 :             : 
     671                 :           0 :     return UnlockPassphraseError(strOldWalletPassphrase);
     672                 :             : }
     673                 :             : 
     674                 :       59680 : void CWallet::SetLastBlockProcessedInMem(int block_height, uint256 block_hash)
     675                 :             : {
     676                 :       59680 :     AssertLockHeld(cs_wallet);
     677                 :             : 
     678                 :       59680 :     m_last_block_processed = block_hash;
     679                 :       59680 :     m_last_block_processed_height = block_height;
     680                 :       59680 : }
     681                 :             : 
     682                 :        4213 : void CWallet::SetLastBlockProcessed(int block_height, uint256 block_hash)
     683                 :             : {
     684                 :        4213 :     AssertLockHeld(cs_wallet);
     685                 :             : 
     686                 :        4213 :     SetLastBlockProcessedInMem(block_height, block_hash);
     687                 :        4213 :     WriteBestBlock();
     688                 :        4213 : }
     689                 :             : 
     690                 :        4500 : std::set<Txid> CWallet::GetConflicts(const Txid& txid) const
     691                 :             : {
     692                 :        4500 :     std::set<Txid> result;
     693                 :        4500 :     AssertLockHeld(cs_wallet);
     694                 :             : 
     695                 :        4500 :     const auto it = mapWallet.find(txid);
     696         [ +  - ]:        9000 :     if (it == mapWallet.end())
     697                 :             :         return result;
     698         [ +  - ]:        4500 :     const CWalletTx& wtx = it->second;
     699                 :             : 
     700         [ +  - ]:        4500 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
     701                 :             : 
     702   [ +  -  +  -  :       15803 :     for (const CTxIn& txin : wtx.GetTx()->vin)
                   +  + ]
     703                 :             :     {
     704         [ +  + ]:        6803 :         if (mapTxSpends.count(txin.prevout) <= 1)
     705                 :        6432 :             continue;  // No conflict if zero or one spends
     706                 :         371 :         range = mapTxSpends.equal_range(txin.prevout);
     707         [ +  + ]:        7656 :         for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
     708         [ +  - ]:         853 :             result.insert(_it->second);
     709                 :             :     }
     710                 :             :     return result;
     711                 :           0 : }
     712                 :             : 
     713                 :         255 : bool CWallet::HasWalletSpend(const CTransactionRef& tx) const
     714                 :             : {
     715                 :         255 :     AssertLockHeld(cs_wallet);
     716                 :         255 :     const Txid& txid = tx->GetHash();
     717   [ -  +  +  + ]:         892 :     for (unsigned int i = 0; i < tx->vout.size(); ++i) {
     718         [ +  + ]:         640 :         if (IsSpent(COutPoint(txid, i))) {
     719                 :             :             return true;
     720                 :             :         }
     721                 :             :     }
     722                 :             :     return false;
     723                 :             : }
     724                 :             : 
     725                 :          14 : void CWallet::Close()
     726                 :             : {
     727                 :          14 :     GetDatabase().Close();
     728                 :          14 : }
     729                 :             : 
     730                 :       19613 : std::set<CWalletTx*, WalletTxOrderComparator> CWallet::GetMalleatedVariants(const CWalletTx& wtx)
     731                 :             : {
     732                 :       19613 :     AssertLockHeld(cs_wallet);
     733         [ +  - ]:       19613 :     std::set<CWalletTx*, WalletTxOrderComparator> txs;
     734                 :             : 
     735                 :             :     // Coinbases cannot be malleated
     736   [ +  -  +  + ]:       19613 :     if (wtx.IsCoinBase()) return txs;
     737                 :             : 
     738                 :             :     // Only transactions that have non-witness inputs can be malleated
     739   [ +  +  +  -  :       17685 :     if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.IsNull(); })) {
             +  -  +  + ]
     740                 :             :         return txs;
     741                 :             :     }
     742                 :             : 
     743                 :             :     // All variants spend wtx's first input, so a single lookup finds every candidate
     744                 :        1010 :     bool found_self = false;
     745   [ +  -  +  - ]:        1010 :     const auto [begin, end] = mapTxSpends.equal_range(wtx.GetTx()->vin.front().prevout);
     746         [ +  + ]:        2079 :     for (auto it = begin; it != end; ++it) {
     747                 :        1069 :         auto entry = mapWallet.find(it->second);
     748   [ -  +  +  - ]:        2138 :         if (!Assume(entry != mapWallet.end())) continue; // sanity-check: mapTxSpends has txs that are in mapWallet
     749         [ +  + ]:        1069 :         const bool is_self = &entry->second == &wtx;
     750                 :        1069 :         found_self |= is_self;
     751   [ +  +  +  -  :        1069 :         if (is_self || wtx.IsMalleation(entry->second)) {
                   +  + ]
     752         [ +  - ]:        1029 :             Assume(txs.insert(&entry->second).second);
     753                 :             :         }
     754                 :             :     }
     755                 :             :     // wtx should always be found as this function is always called after AddToSpends
     756         [ +  - ]:        1010 :     Assert(found_self);
     757                 :             :     return txs;
     758                 :           0 : }
     759                 :             : 
     760                 :       19506 : void CWallet::SyncMalleatedTxMetadata(WalletBatch& batch, const CWalletTx& wtx)
     761                 :             : {
     762                 :       19506 :     const auto txs = GetMalleatedVariants(wtx);
     763         [ +  + ]:       19506 :     if (txs.size() <= 1) return; // no variants, nothing to do
     764                 :             : 
     765                 :             :     // First tx is the oldest one (smallest nOrderPos)
     766                 :          15 :     const CWalletTx* copyFrom = *txs.begin();
     767                 :             : 
     768                 :             :     // The metadata that is kept in sync between malleated variants.
     769                 :             :     // nTimeReceived, nOrderPos and cached members are not copied on purpose.
     770                 :          30 :     const auto metadata = [](auto& tx) {
     771                 :          15 :         return std::tie(tx.m_from, tx.m_message, tx.m_comment, tx.m_comment_to,
     772                 :          15 :                         tx.m_replaces_txid, tx.m_replaced_by_txid,
     773                 :          15 :                         tx.m_messages, tx.m_payment_requests, tx.nTimeSmart);
     774                 :             :     };
     775                 :             : 
     776                 :             :     // Now copy data from copyFrom to rest:
     777         [ +  + ]:          45 :     for (CWalletTx* copyTo : txs) {
     778         [ +  + ]:          30 :         if (copyTo == copyFrom) continue;
     779         [ +  - ]:          15 :         metadata(*copyTo) = metadata(*copyFrom);
     780         [ +  - ]:          15 :         (void)batch.WriteTxMetadata(*copyTo);
     781                 :             :     }
     782                 :       19506 : }
     783                 :             : 
     784                 :             : /**
     785                 :             :  * Outpoint is spent if any non-conflicted transaction
     786                 :             :  * spends it:
     787                 :             :  */
     788                 :      449569 : bool CWallet::IsSpent(const COutPoint& outpoint) const
     789                 :             : {
     790                 :      449569 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
     791                 :      449569 :     range = mapTxSpends.equal_range(outpoint);
     792                 :             : 
     793         [ +  + ]:      450989 :     for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
     794                 :      298464 :         const Txid& txid = it->second;
     795                 :      298464 :         const auto mit = mapWallet.find(txid);
     796         [ +  - ]:      299884 :         if (mit != mapWallet.end()) {
     797         [ +  + ]:      298464 :             const auto& wtx = mit->second;
     798   [ +  +  +  +  :      298527 :             if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted())
                   +  + ]
     799                 :             :                 return true; // Spent
     800                 :             :         }
     801                 :             :     }
     802                 :             :     return false;
     803                 :             : }
     804                 :             : 
     805                 :       83791 : CWallet::SpendType CWallet::HowSpent(const COutPoint& outpoint) const
     806                 :             : {
     807                 :       83791 :     SpendType st{SpendType::UNSPENT};
     808                 :             : 
     809                 :       83791 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
     810                 :       83791 :     range = mapTxSpends.equal_range(outpoint);
     811                 :             : 
     812         [ +  + ]:       85599 :     for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
     813                 :       52333 :         const Txid& txid = it->second;
     814                 :       52333 :         const auto mit = mapWallet.find(txid);
     815         [ +  - ]:       54141 :         if (mit != mapWallet.end()) {
     816         [ +  + ]:       52333 :             const auto& wtx = mit->second;
     817         [ +  + ]:       52333 :             if (wtx.isConfirmed()) return SpendType::CONFIRMED;
     818         [ +  + ]:        1808 :             if (wtx.InMempool()) {
     819                 :             :                 st = SpendType::MEMPOOL;
     820   [ +  +  +  +  :        2144 :             } else if (!wtx.isAbandoned() && !wtx.isBlockConflicted() && !wtx.isMempoolConflicted()) {
                   +  + ]
     821         [ +  + ]:         147 :                 if (st == SpendType::UNSPENT) st = SpendType::NONMEMPOOL;
     822                 :             :             }
     823                 :             :         }
     824                 :             :     }
     825                 :             :     return st;
     826                 :             : }
     827                 :             : 
     828                 :       12143 : void CWallet::AddToSpends(const COutPoint& outpoint, const Txid& txid)
     829                 :             : {
     830                 :       12143 :     mapTxSpends.insert(std::make_pair(outpoint, txid));
     831                 :             : 
     832                 :       12143 :     UnlockCoin(outpoint);
     833                 :       12143 : }
     834                 :             : 
     835                 :             : 
     836                 :       31753 : void CWallet::AddToSpends(const CWalletTx& wtx)
     837                 :             : {
     838         [ +  + ]:       31753 :     if (wtx.IsCoinBase()) // Coinbases don't spend anything!
     839                 :             :         return;
     840                 :             : 
     841   [ +  -  +  + ]:       25197 :     for (const CTxIn& txin : wtx.GetTx()->vin)
     842                 :       12143 :         AddToSpends(txin.prevout, wtx.GetHash());
     843                 :             : }
     844                 :             : 
     845                 :          39 : bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
     846                 :             : {
     847                 :             :     // Only descriptor wallets can be encrypted
     848                 :          39 :     Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
     849                 :             : 
     850         [ +  - ]:          39 :     if (HasEncryptionKeys())
     851                 :             :         return false;
     852                 :             : 
     853                 :          39 :     CKeyingMaterial plain_master_key;
     854                 :             : 
     855         [ +  - ]:          39 :     plain_master_key.resize(WALLET_CRYPTO_KEY_SIZE);
     856         [ -  + ]:          39 :     GetStrongRandBytes(plain_master_key);
     857                 :             : 
     858         [ +  - ]:          39 :     CMasterKey master_key;
     859                 :             : 
     860         [ +  - ]:          39 :     master_key.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
     861         [ -  + ]:          39 :     GetStrongRandBytes(master_key.vchSalt);
     862                 :             : 
     863   [ +  -  +  - ]:          39 :     if (!EncryptMasterKey(strWalletPassphrase, plain_master_key, master_key)) {
     864                 :             :         return false;
     865                 :             :     }
     866         [ +  - ]:          39 :     WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i", master_key.nDeriveIterations);
     867                 :             : 
     868                 :          39 :     {
     869   [ +  -  +  - ]:          39 :         LOCK2(m_relock_mutex, cs_wallet);
     870                 :          39 :         const unsigned int new_master_key_id{nMasterKeyMaxID + 1};
     871   [ +  -  +  -  :          39 :         if (!RunWithinTxn(GetDatabase(), /*process_desc=*/"wallet encryption", [&](WalletBatch& batch) {
                   +  + ]
     872         [ +  + ]:          39 :                 if (!batch.WriteMasterKey(new_master_key_id, master_key)) {
     873                 :             :                     return false;
     874                 :             :                 }
     875         [ +  + ]:         139 :                 for (const auto& spk_man_pair : m_spk_managers) {
     876         [ +  + ]:         103 :                     if (!spk_man_pair.second->Encrypt(plain_master_key, &batch)) {
     877                 :             :                         return false;
     878                 :             :                     }
     879                 :             :                 }
     880                 :             :                 return true;
     881                 :             :             })) {
     882                 :             :             return false;
     883                 :             :         }
     884                 :             : 
     885                 :          35 :         nMasterKeyMaxID = new_master_key_id;
     886         [ +  - ]:          35 :         mapMasterKeys[new_master_key_id] = std::move(master_key);
     887                 :             : 
     888         [ +  - ]:          35 :         Lock();
     889   [ +  -  +  - ]:          35 :         if (!Unlock(strWalletPassphrase)) {
     890                 :             :             return false;
     891                 :             :         }
     892                 :             : 
     893         [ +  - ]:          35 :         SetupWalletGeneration();
     894                 :             : 
     895         [ +  - ]:          35 :         Lock();
     896                 :             : 
     897                 :             :         // Need to completely rewrite the wallet file; if we don't, the database might keep
     898                 :             :         // bits of the unencrypted private key in slack space in the database file.
     899         [ +  - ]:          35 :         GetDatabase().Rewrite();
     900   [ +  -  +  - ]:          43 :     }
     901         [ +  - ]:          35 :     NotifyStatusChanged(this);
     902                 :             : 
     903                 :             :     return true;
     904                 :          39 : }
     905                 :             : 
     906                 :           0 : DBErrors CWallet::ReorderTransactions()
     907                 :             : {
     908                 :           0 :     LOCK(cs_wallet);
     909         [ #  # ]:           0 :     WalletBatch batch(GetDatabase());
     910                 :             : 
     911                 :             :     // Old wallets didn't have any defined order for transactions
     912                 :             :     // Probably a bad idea to change the output of this
     913                 :             : 
     914                 :             :     // First: get all CWalletTx into a sorted-by-time multimap.
     915                 :           0 :     typedef std::multimap<int64_t, CWalletTx*> TxItems;
     916                 :           0 :     TxItems txByTime;
     917                 :             : 
     918   [ #  #  #  # ]:           0 :     for (auto& entry : mapWallet)
     919                 :             :     {
     920                 :           0 :         CWalletTx* wtx = &entry.second;
     921         [ #  # ]:           0 :         txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
     922                 :             :     }
     923                 :             : 
     924                 :           0 :     nOrderPosNext = 0;
     925                 :           0 :     std::vector<int64_t> nOrderPosOffsets;
     926         [ #  # ]:           0 :     for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
     927                 :             :     {
     928         [ #  # ]:           0 :         CWalletTx *const pwtx = (*it).second;
     929                 :           0 :         int64_t& nOrderPos = pwtx->nOrderPos;
     930                 :             : 
     931         [ #  # ]:           0 :         if (nOrderPos == -1)
     932                 :             :         {
     933                 :           0 :             nOrderPos = nOrderPosNext++;
     934         [ #  # ]:           0 :             nOrderPosOffsets.push_back(nOrderPos);
     935                 :             : 
     936   [ #  #  #  # ]:           0 :             if (!batch.WriteTxMetadata(*pwtx))
     937                 :             :                 return DBErrors::LOAD_FAIL;
     938                 :             :         }
     939                 :             :         else
     940                 :             :         {
     941                 :           0 :             int64_t nOrderPosOff = 0;
     942         [ #  # ]:           0 :             for (const int64_t& nOffsetStart : nOrderPosOffsets)
     943                 :             :             {
     944         [ #  # ]:           0 :                 if (nOrderPos >= nOffsetStart)
     945                 :           0 :                     ++nOrderPosOff;
     946                 :             :             }
     947                 :           0 :             nOrderPos += nOrderPosOff;
     948         [ #  # ]:           0 :             nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
     949                 :             : 
     950         [ #  # ]:           0 :             if (!nOrderPosOff)
     951                 :           0 :                 continue;
     952                 :             : 
     953                 :             :             // Since we're changing the order, write it back
     954   [ #  #  #  # ]:           0 :             if (!batch.WriteTxMetadata(*pwtx))
     955                 :             :                 return DBErrors::LOAD_FAIL;
     956                 :             :         }
     957                 :             :     }
     958         [ #  # ]:           0 :     batch.WriteOrderPosNext(nOrderPosNext);
     959                 :             : 
     960                 :             :     return DBErrors::LOAD_OK;
     961         [ #  # ]:           0 : }
     962                 :             : 
     963                 :       19506 : int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
     964                 :             : {
     965                 :       19506 :     AssertLockHeld(cs_wallet);
     966                 :       19506 :     int64_t nRet = nOrderPosNext++;
     967         [ +  - ]:       19506 :     if (batch) {
     968                 :       19506 :         batch->WriteOrderPosNext(nOrderPosNext);
     969                 :             :     } else {
     970         [ #  # ]:           0 :         WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
     971                 :             :     }
     972                 :       19506 :     return nRet;
     973                 :             : }
     974                 :             : 
     975                 :         988 : void CWallet::MarkDirty()
     976                 :             : {
     977                 :         988 :     {
     978                 :         988 :         LOCK(cs_wallet);
     979   [ +  +  +  - ]:        4930 :         for (auto& [_, wtx] : mapWallet)
     980                 :        3942 :             wtx.MarkDirty();
     981                 :         988 :     }
     982                 :         988 : }
     983                 :             : 
     984                 :         107 : bool CWallet::MarkReplaced(const Txid& originalHash, const Txid& newHash)
     985                 :             : {
     986                 :         107 :     LOCK(cs_wallet);
     987                 :             : 
     988                 :         107 :     auto mi = mapWallet.find(originalHash);
     989                 :             : 
     990                 :             :     // There is a bug if MarkReplaced is not called on an existing wallet transaction.
     991         [ -  + ]:         107 :     assert(mi != mapWallet.end());
     992                 :             : 
     993         [ +  - ]:         107 :     CWalletTx& wtx = (*mi).second;
     994                 :             : 
     995                 :             :     // Ensure for now that we're not overwriting data
     996         [ +  - ]:         107 :     Assert(!wtx.m_replaced_by_txid);
     997                 :             : 
     998         [ -  + ]:         107 :     wtx.m_replaced_by_txid = newHash;
     999                 :             : 
    1000                 :             :     // Refresh mempool status without waiting for transactionRemovedFromMempool or transactionAddedToMempool
    1001         [ +  - ]:         107 :     RefreshMempoolStatus(wtx, chain());
    1002                 :             : 
    1003         [ +  - ]:         107 :     WalletBatch batch(GetDatabase());
    1004                 :             : 
    1005                 :         107 :     bool success = true;
    1006   [ +  -  -  + ]:         107 :     if (!batch.WriteTxMetadata(wtx)) {
    1007   [ #  #  #  #  :           0 :         WalletLogPrintf("%s: Updating batch tx %s failed", __func__, wtx.GetHash().ToString());
                   #  # ]
    1008                 :           0 :         success = false;
    1009                 :             :     }
    1010                 :             : 
    1011                 :             :     // The new transaction also replaces any malleated variants of wtx,
    1012                 :             :     // so bumpfee refuses to bump them afterwards
    1013   [ +  -  +  + ]:         120 :     for (CWalletTx* variant : GetMalleatedVariants(wtx)) {
    1014         [ +  + ]:          13 :         if (variant == &wtx) continue;
    1015         [ -  + ]:           4 :         variant->m_replaced_by_txid = newHash;
    1016   [ +  -  -  + ]:           4 :         if (!batch.WriteTxMetadata(*variant)) {
    1017   [ #  #  #  #  :           0 :             WalletLogPrintf("%s: Updating variant tx %s failed", __func__, variant->GetHash().ToString());
                   #  # ]
    1018                 :           0 :             success = false;
    1019                 :             :         }
    1020                 :             :     }
    1021                 :             : 
    1022         [ +  - ]:         107 :     NotifyTransactionChanged(originalHash, CT_UPDATED);
    1023                 :             : 
    1024                 :         107 :     return success;
    1025         [ +  - ]:         214 : }
    1026                 :             : 
    1027                 :        2093 : void CWallet::SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
    1028                 :             : {
    1029                 :        2093 :     AssertLockHeld(cs_wallet);
    1030                 :        2093 :     const CWalletTx* srctx = GetWalletTx(hash);
    1031         [ +  + ]:        2093 :     if (!srctx) return;
    1032                 :             : 
    1033                 :        1945 :     CTxDestination dst;
    1034   [ +  -  +  -  :        3890 :     if (ExtractDestination(srctx->GetTx()->vout[n].scriptPubKey, dst)) {
             +  -  +  - ]
    1035   [ +  -  +  + ]:        1945 :         if (IsMine(dst)) {
    1036   [ +  -  +  + ]:        1263 :             if (used != IsAddressPreviouslySpent(dst)) {
    1037         [ +  - ]:          46 :                 if (used) {
    1038         [ +  - ]:          46 :                     tx_destinations.insert(dst);
    1039                 :             :                 }
    1040         [ +  - ]:          46 :                 SetAddressPreviouslySpent(batch, dst, used);
    1041                 :             :             }
    1042                 :             :         }
    1043                 :             :     }
    1044                 :        1945 : }
    1045                 :             : 
    1046                 :         443 : bool CWallet::IsSpentKey(const CScript& scriptPubKey) const
    1047                 :             : {
    1048                 :         443 :     AssertLockHeld(cs_wallet);
    1049                 :         443 :     CTxDestination dest;
    1050   [ +  -  +  - ]:         443 :     if (!ExtractDestination(scriptPubKey, dest)) {
    1051                 :             :         return false;
    1052                 :             :     }
    1053   [ +  -  +  + ]:         443 :     if (IsAddressPreviouslySpent(dest)) {
    1054                 :           8 :         return true;
    1055                 :             :     }
    1056                 :             :     return false;
    1057                 :         443 : }
    1058                 :             : 
    1059                 :       28455 : CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx, bool rescanning_old_block)
    1060                 :             : {
    1061                 :       28455 :     LOCK(cs_wallet);
    1062                 :             : 
    1063         [ +  - ]:       28455 :     WalletBatch batch(GetDatabase());
    1064                 :             : 
    1065         [ +  - ]:       28455 :     Txid hash = tx->GetHash();
    1066                 :             : 
    1067   [ +  -  +  + ]:       28455 :     if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
    1068                 :             :         // Mark used destinations
    1069                 :         922 :         std::set<CTxDestination> tx_destinations;
    1070                 :             : 
    1071         [ +  + ]:        3015 :         for (const CTxIn& txin : tx->vin) {
    1072                 :        2093 :             const COutPoint& op = txin.prevout;
    1073         [ +  - ]:        2093 :             SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
    1074                 :             :         }
    1075                 :             : 
    1076         [ +  - ]:         922 :         MarkDestinationsDirty(tx_destinations);
    1077                 :         922 :     }
    1078                 :             : 
    1079                 :             :     // Inserts only if not already there, returns tx inserted or tx found
    1080         [ +  - ]:       28455 :     auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(tx, state));
    1081         [ +  + ]:       28455 :     CWalletTx& wtx = (*ret.first).second;
    1082                 :       28455 :     bool fInsertedNew = ret.second;
    1083   [ +  +  +  -  :       28455 :     bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
                   -  + ]
    1084         [ +  + ]:       28455 :     if (fInsertedNew) {
    1085         [ +  - ]:       19506 :         wtx.nTimeReceived = GetTime();
    1086         [ +  - ]:       19506 :         wtx.nOrderPos = IncOrderPosNext(&batch);
    1087   [ +  -  +  - ]:       19506 :         wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
    1088         [ +  - ]:       19506 :         wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block);
    1089         [ +  - ]:       19506 :         AddToSpends(wtx);
    1090         [ +  - ]:       19506 :         SyncMalleatedTxMetadata(batch, wtx);
    1091                 :             : 
    1092                 :             :         // Update birth time when tx time is older than it.
    1093   [ +  -  +  - ]:       19506 :         MaybeUpdateBirthTime(wtx.GetTxTime());
    1094                 :             : 
    1095   [ +  -  +  - ]:       19506 :         if (!batch.WriteFullTx(wtx)) {
    1096                 :             :             return nullptr;
    1097                 :             :         }
    1098                 :             :     }
    1099                 :             : 
    1100                 :        8949 :     if (!fInsertedNew)
    1101                 :             :     {
    1102                 :        8949 :         try {
    1103   [ +  -  +  -  :       26844 :             fUpdated |= wtx.Update(tx, state, batch, fUpdated);
                   +  + ]
    1104         [ -  - ]:           0 :         } catch (const std::ios_base::failure& e) {
    1105         [ -  - ]:           0 :             WalletLogPrintf("Error: Unable to write tx update, %s", e.what());
    1106                 :           0 :             return nullptr;
    1107                 :           0 :         }
    1108                 :             :     }
    1109                 :             : 
    1110                 :             :     // Mark inactive coinbase transactions and their descendants as abandoned
    1111   [ +  -  +  + ]:       28455 :     if (wtx.IsCoinBase() && wtx.isInactive()) {
    1112         [ +  - ]:         546 :         std::vector<CWalletTx*> txs{&wtx};
    1113                 :             : 
    1114                 :         546 :         TxStateInactive inactive_state = TxStateInactive{/*abandoned=*/true};
    1115                 :             : 
    1116         [ +  + ]:        1093 :         while (!txs.empty()) {
    1117                 :         547 :             CWalletTx* desc_tx = txs.back();
    1118         [ +  + ]:         547 :             txs.pop_back();
    1119         [ +  + ]:         547 :             desc_tx->m_state = inactive_state;
    1120                 :             :             // Break caches since we have changed the state
    1121                 :         547 :             desc_tx->MarkDirty();
    1122         [ +  - ]:         547 :             batch.WriteTxMetadata(*desc_tx);
    1123   [ +  -  +  - ]:         547 :             MarkInputsDirty(desc_tx->GetTx());
    1124   [ +  -  -  +  :        3282 :             for (unsigned int i = 0; i < desc_tx->GetTx()->vout.size(); ++i) {
             +  -  +  + ]
    1125         [ +  - ]:        1094 :                 COutPoint outpoint(desc_tx->GetHash(), i);
    1126                 :        1094 :                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(outpoint);
    1127         [ +  + ]:        1095 :                 for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
    1128                 :           1 :                     const auto wit = mapWallet.find(it->second);
    1129         [ +  - ]:           1 :                     if (wit != mapWallet.end()) {
    1130         [ +  - ]:           1 :                         txs.push_back(&wit->second);
    1131                 :             :                     }
    1132                 :             :                 }
    1133                 :             :             }
    1134                 :             :         }
    1135                 :         546 :     }
    1136                 :             : 
    1137                 :             :     //// debug print
    1138         [ +  - ]:       28455 :     std::string status{"no-change"};
    1139         [ +  + ]:       28455 :     if (fInsertedNew || fUpdated) {
    1140   [ +  +  +  + ]:       24130 :         status = fInsertedNew ? (fUpdated ? "new, update" : "new") : "update";
    1141                 :             :     }
    1142   [ +  -  +  - ]:       85365 :     WalletLogPrintf("AddToWallet %s %s %s", hash.ToString(), status, TxStateString(state));
    1143                 :             : 
    1144                 :             :     // Break debit/credit balance caches:
    1145                 :       28455 :     wtx.MarkDirty();
    1146                 :             : 
    1147                 :             :     // Cache the outputs that belong to the wallet
    1148         [ +  - ]:       28455 :     RefreshTXOsFromTx(wtx);
    1149                 :             : 
    1150                 :             :     // Notify UI of new or updated transaction
    1151   [ +  +  +  - ]:       37404 :     NotifyTransactionChanged(hash, fInsertedNew ? CT_NEW : CT_UPDATED);
    1152                 :             : 
    1153                 :             : #if HAVE_SYSTEM
    1154                 :             :     // notify an external script when a wallet transaction comes in or is updated
    1155         [ -  + ]:       28455 :     std::string strCmd = m_notify_tx_changed_script;
    1156                 :             : 
    1157         [ +  + ]:       28455 :     if (!strCmd.empty())
    1158                 :             :     {
    1159   [ +  -  -  +  :          27 :         ReplaceAll(strCmd, "%s", hash.GetHex());
                   +  - ]
    1160         [ +  + ]:          27 :         if (auto* conf = wtx.state<TxStateConfirmed>())
    1161                 :             :         {
    1162   [ +  -  +  - ]:          44 :             ReplaceAll(strCmd, "%b", conf->confirmed_block_hash.GetHex());
    1163   [ +  -  +  - ]:          66 :             ReplaceAll(strCmd, "%h", ToString(conf->confirmed_block_height));
    1164                 :             :         } else {
    1165         [ +  - ]:           5 :             ReplaceAll(strCmd, "%b", "unconfirmed");
    1166         [ +  - ]:           5 :             ReplaceAll(strCmd, "%h", "-1");
    1167                 :             :         }
    1168                 :             : #ifndef WIN32
    1169                 :             :         // Substituting the wallet name isn't currently supported on windows
    1170                 :             :         // because windows shell escaping has not been implemented yet:
    1171                 :             :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
    1172                 :             :         // A few ways it could be implemented in the future are described in:
    1173                 :             :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
    1174   [ +  -  +  - ]:          54 :         ReplaceAll(strCmd, "%w", ShellEscape(GetName()));
    1175                 :             : #endif
    1176         [ +  - ]:          27 :         std::thread t(runCommand, strCmd);
    1177         [ +  - ]:          27 :         t.detach(); // thread runs free
    1178                 :          27 :     }
    1179                 :             : #endif
    1180                 :             : 
    1181                 :       28455 :     return &wtx;
    1182         [ +  - ]:       85365 : }
    1183                 :             : 
    1184                 :       12247 : bool CWallet::LoadToWallet(CWalletTx&& wtx_in)
    1185                 :             : {
    1186                 :       12247 :     const auto& ins = mapWallet.emplace(wtx_in.GetHash(), std::move(wtx_in));
    1187         [ +  - ]:       12247 :     CWalletTx& wtx = ins.first->second;
    1188         [ +  - ]:       12247 :     if (!ins.second) {
    1189                 :             :         return false;
    1190                 :             :     }
    1191                 :             :     // If wallet doesn't have a chain (e.g when using bitcoin-wallet tool),
    1192                 :             :     // don't bother to update txn.
    1193         [ +  + ]:       12247 :     if (HaveChain()) {
    1194                 :       11742 :       wtx.updateState(chain());
    1195                 :             :     }
    1196                 :       12247 :     wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
    1197                 :       12247 :     AddToSpends(wtx);
    1198   [ +  -  +  + ]:       37448 :     for (const CTxIn& txin : wtx.GetTx()->vin) {
    1199                 :       12954 :         auto it = mapWallet.find(txin.prevout.hash);
    1200         [ +  + ]:       12954 :         if (it != mapWallet.end()) {
    1201         [ +  + ]:        1011 :             CWalletTx& prevtx = it->second;
    1202         [ +  + ]:       12957 :             if (auto* prev = prevtx.state<TxStateBlockConflicted>()) {
    1203                 :           3 :                 MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, wtx.GetHash());
    1204                 :             :             }
    1205                 :             :         }
    1206                 :             :     }
    1207                 :             : 
    1208                 :             :     // Update birth time when tx time is older than it.
    1209                 :       12247 :     MaybeUpdateBirthTime(wtx.GetTxTime());
    1210                 :             : 
    1211                 :             :     // Make sure the tx outputs are known by the wallet
    1212                 :       12247 :     RefreshTXOsFromTx(wtx);
    1213                 :       12247 :     return true;
    1214                 :             : }
    1215                 :             : 
    1216                 :      173857 : bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const SyncTxState& state, bool rescanning_old_block)
    1217                 :             : {
    1218         [ +  + ]:      173857 :     const CTransaction& tx = *ptx;
    1219                 :      173857 :     {
    1220                 :      173857 :         AssertLockHeld(cs_wallet);
    1221                 :             : 
    1222         [ +  + ]:      173857 :         if (auto* conf = std::get_if<TxStateConfirmed>(&state)) {
    1223         [ +  + ]:      362724 :             for (const CTxIn& txin : tx.vin) {
    1224                 :      200930 :                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
    1225         [ +  + ]:      209306 :                 while (range.first != range.second) {
    1226         [ +  + ]:        8376 :                     if (range.first->second != tx.GetHash()) {
    1227   [ +  -  +  -  :         480 :                         WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)", tx.GetHash().ToString(), conf->confirmed_block_hash.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
             +  -  +  - ]
    1228                 :         240 :                         MarkConflicted(conf->confirmed_block_hash, conf->confirmed_block_height, range.first->second);
    1229                 :             :                     }
    1230                 :        8376 :                     range.first++;
    1231                 :             :                 }
    1232                 :             :             }
    1233                 :             :         }
    1234                 :             : 
    1235                 :      173857 :         bool fExisted = mapWallet.contains(tx.GetHash());
    1236   [ +  +  +  +  :      173857 :         if (fExisted || IsMine(tx) || IsFromMe(tx))
                   +  + ]
    1237                 :             :         {
    1238                 :             :             /* Check if any keys in the wallet keypool that were supposed to be unused
    1239                 :             :              * have appeared in a new transaction. If so, remove those keys from the keypool.
    1240                 :             :              * This can happen when restoring an old wallet backup that does not contain
    1241                 :             :              * the mostly recently created transactions from newer versions of the wallet.
    1242                 :             :              */
    1243                 :             : 
    1244                 :             :             // loop though all outputs
    1245         [ +  + ]:      137661 :             for (const CTxOut& txout: tx.vout) {
    1246         [ +  + ]:      159581 :                 for (const auto& spk_man : GetScriptPubKeyMans(txout.scriptPubKey)) {
    1247   [ +  -  +  + ]:       73132 :                     for (auto &dest : spk_man->MarkUnusedAddresses(txout.scriptPubKey)) {
    1248                 :             :                         // If internal flag is not defined try to infer it from the ScriptPubKeyMan
    1249         [ +  - ]:       24435 :                         if (!dest.internal.has_value()) {
    1250         [ +  - ]:       24435 :                             dest.internal = IsInternalScriptPubKeyMan(spk_man);
    1251                 :             :                         }
    1252                 :             : 
    1253                 :             :                         // skip if can't determine whether it's a receiving address or not
    1254         [ +  + ]:       24435 :                         if (!dest.internal.has_value()) continue;
    1255                 :             : 
    1256                 :             :                         // If this is a receiving address and it's not in the address book yet
    1257                 :             :                         // (e.g. it wasn't generated on this node or we're restoring from backup)
    1258                 :             :                         // add it to the address book for proper transaction accounting
    1259   [ +  +  +  -  :       16225 :                         if (!*dest.internal && !FindAddressBookEntry(dest.dest, /* allow_change= */ false)) {
                   +  + ]
    1260   [ +  -  +  - ]:       20356 :                             SetAddressBook(dest.dest, "", AddressPurpose::RECEIVE);
    1261                 :             :                         }
    1262                 :       48697 :                     }
    1263                 :      110884 :                 }
    1264                 :             :             }
    1265                 :             : 
    1266                 :             :             // Block disconnection override an abandoned tx as unconfirmed
    1267                 :             :             // which means user may have to call abandontransaction again
    1268         [ +  - ]:       53554 :             TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
    1269   [ +  -  +  -  :       80331 :             CWalletTx* wtx = AddToWallet(MakeTransactionRef(tx), tx_state, /*update_wtx=*/nullptr, rescanning_old_block);
                   +  - ]
    1270         [ -  + ]:       26777 :             if (!wtx) {
    1271                 :             :                 // Can only be nullptr if there was a db write error (missing db, read-only db or a db engine internal writing error).
    1272                 :             :                 // As we only store arriving transaction in this process, and we don't want an inconsistent state, let's throw an error.
    1273         [ #  # ]:           0 :                 throw std::runtime_error("DB error adding transaction to wallet, write failed");
    1274                 :             :             }
    1275                 :             :             return true;
    1276                 :             :         }
    1277                 :             :     }
    1278                 :             :     return false;
    1279                 :             : }
    1280                 :             : 
    1281                 :           0 : bool CWallet::TransactionCanBeAbandoned(const Txid& hashTx) const
    1282                 :             : {
    1283                 :           0 :     LOCK(cs_wallet);
    1284         [ #  # ]:           0 :     const CWalletTx* wtx = GetWalletTx(hashTx);
    1285   [ #  #  #  #  :           0 :     return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 && !wtx->InMempool();
          #  #  #  #  #  
                #  #  # ]
    1286                 :           0 : }
    1287                 :             : 
    1288                 :          62 : void CWallet::UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
    1289                 :             : {
    1290                 :             :     // Find all other txs in our wallet that spend utxos from this parent
    1291                 :             :     // so that we can mark them as mempool-conflicted by this new tx.
    1292   [ -  +  +  -  :         484 :     for (long unsigned int i = 0; i < parent_wtx.GetTx()->vout.size(); i++) {
                   +  + ]
    1293   [ +  -  +  + ]:         405 :         for (auto range = mapTxSpends.equal_range(COutPoint(parent_wtx.GetTx()->GetHash(), i)); range.first != range.second; range.first++) {
    1294         [ +  + ]:          45 :             const Txid& sibling_txid = range.first->second;
    1295                 :             :             // Skip the child_tx itself
    1296         [ +  + ]:          45 :             if (sibling_txid == child_txid) continue;
    1297         [ +  - ]:          34 :             RecursiveUpdateTxState(/*batch=*/nullptr, sibling_txid, [&child_txid, add_conflict](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    1298   [ +  +  +  + ]:          17 :                 return add_conflict ? (wtx.mempool_conflicts.insert(child_txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED)
    1299         [ +  + ]:           9 :                                     : (wtx.mempool_conflicts.erase(child_txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED);
    1300                 :             :             });
    1301                 :             :         }
    1302                 :             :     }
    1303                 :          62 : }
    1304                 :             : 
    1305                 :       33776 : void CWallet::MarkInputsDirty(const CTransactionRef& tx)
    1306                 :             : {
    1307         [ +  + ]:       76967 :     for (const CTxIn& txin : tx->vin) {
    1308                 :       43191 :         auto it = mapWallet.find(txin.prevout.hash);
    1309         [ +  + ]:       63581 :         if (it != mapWallet.end()) {
    1310                 :       20390 :             it->second.MarkDirty();
    1311                 :             :         }
    1312                 :             :     }
    1313                 :       33776 : }
    1314                 :             : 
    1315                 :          10 : bool CWallet::AbandonTransaction(const Txid& hashTx)
    1316                 :             : {
    1317                 :          10 :     LOCK(cs_wallet);
    1318                 :          10 :     auto it = mapWallet.find(hashTx);
    1319         [ -  + ]:          10 :     assert(it != mapWallet.end());
    1320   [ +  -  +  - ]:          10 :     return AbandonTransaction(it->second);
    1321                 :          10 : }
    1322                 :             : 
    1323                 :         442 : bool CWallet::AbandonTransaction(CWalletTx& tx)
    1324                 :             : {
    1325                 :             :     // Can't mark abandoned if confirmed or in mempool
    1326   [ +  +  +  + ]:         442 :     if (GetTxDepthInMainChain(tx) != 0 || tx.InMempool()) {
    1327                 :           3 :         return false;
    1328                 :             :     }
    1329                 :             : 
    1330                 :         899 :     auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    1331                 :             :         // If the orig tx was not in block/mempool, none of its spends can be.
    1332         [ +  - ]:         460 :         assert(!wtx.isConfirmed());
    1333         [ -  + ]:         460 :         assert(!wtx.InMempool());
    1334                 :             :         // If already conflicted or abandoned, no need to set abandoned
    1335   [ +  -  +  - ]:         460 :         if (!wtx.isBlockConflicted() && !wtx.isAbandoned()) {
    1336         [ +  - ]:         352 :             wtx.m_state = TxStateInactive{/*abandoned=*/true};
    1337                 :         352 :             return TxUpdate::NOTIFY_CHANGED;
    1338                 :             :         }
    1339                 :             :         return TxUpdate::UNCHANGED;
    1340                 :             :     };
    1341                 :             : 
    1342                 :             :     // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
    1343                 :             :     // States are not permanent, so these transactions can become unabandoned if they are re-added to the
    1344                 :             :     // mempool, or confirmed in a block, or conflicted.
    1345                 :             :     // Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
    1346                 :             :     // states change will remain abandoned and will require manual broadcast if the user wants them.
    1347                 :             : 
    1348   [ +  -  +  - ]:         439 :     RecursiveUpdateTxState(tx.GetHash(), try_updating_state);
    1349                 :             : 
    1350                 :         439 :     return true;
    1351                 :             : }
    1352                 :             : 
    1353                 :         243 : void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx)
    1354                 :             : {
    1355                 :         243 :     LOCK(cs_wallet);
    1356                 :             : 
    1357                 :             :     // If number of conflict confirms cannot be determined, this means
    1358                 :             :     // that the block is still unknown or not yet part of the main chain,
    1359                 :             :     // for example when loading the wallet during a reindex. Do nothing in that
    1360                 :             :     // case.
    1361   [ +  +  +  - ]:         243 :     if (m_last_block_processed_height < 0 || conflicting_height < 0) {
    1362                 :             :         return;
    1363                 :             :     }
    1364                 :         240 :     int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
    1365         [ +  - ]:         240 :     if (conflictconfirms >= 0)
    1366                 :             :         return;
    1367                 :             : 
    1368                 :         487 :     auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    1369         [ +  + ]:         247 :         if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
    1370                 :             :             // Block is 'more conflicted' than current confirm; update.
    1371                 :             :             // Mark transaction as conflicted with this block.
    1372                 :         211 :             wtx.m_state = TxStateBlockConflicted{hashBlock, conflicting_height};
    1373                 :         211 :             return TxUpdate::CHANGED;
    1374                 :             :         }
    1375                 :             :         return TxUpdate::UNCHANGED;
    1376                 :         240 :     };
    1377                 :             : 
    1378                 :             :     // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
    1379   [ +  -  +  -  :         480 :     RecursiveUpdateTxState(hashTx, try_updating_state);
                   +  - ]
    1380                 :             : 
    1381                 :         243 : }
    1382                 :             : 
    1383                 :         695 : void CWallet::RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
    1384                 :         695 :     WalletBatch batch(GetDatabase());
    1385         [ +  - ]:         695 :     RecursiveUpdateTxState(&batch, tx_hash, try_updating_state);
    1386                 :         695 : }
    1387                 :             : 
    1388                 :       15188 : void CWallet::RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) {
    1389         [ +  - ]:       15188 :     std::set<Txid> todo;
    1390                 :       15188 :     std::set<Txid> done;
    1391                 :             : 
    1392         [ +  - ]:       15188 :     todo.insert(tx_hash);
    1393                 :             : 
    1394         [ +  + ]:       30421 :     while (!todo.empty()) {
    1395                 :       15233 :         Txid now = *todo.begin();
    1396                 :       15233 :         todo.erase(now);
    1397         [ +  - ]:       15233 :         done.insert(now);
    1398                 :       15233 :         auto it = mapWallet.find(now);
    1399         [ -  + ]:       15233 :         assert(it != mapWallet.end());
    1400         [ +  - ]:       15233 :         CWalletTx& wtx = it->second;
    1401                 :             : 
    1402         [ +  - ]:       15233 :         TxUpdate update_state = try_updating_state(wtx);
    1403         [ +  + ]:       15233 :         if (update_state != TxUpdate::UNCHANGED) {
    1404                 :        6456 :             wtx.MarkDirty();
    1405   [ +  +  +  - ]:        6456 :             if (batch) batch->WriteTxMetadata(wtx);
    1406                 :             :             // Iterate over all its outputs, and update those tx states as well (if applicable)
    1407   [ +  -  -  +  :       38816 :             for (unsigned int i = 0; i < wtx.GetTx()->vout.size(); ++i) {
             +  -  +  + ]
    1408                 :       12952 :                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
    1409         [ +  + ]:       12997 :                 for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
    1410         [ +  - ]:          45 :                     if (!done.contains(iter->second)) {
    1411         [ +  - ]:          45 :                         todo.insert(iter->second);
    1412                 :             :                     }
    1413                 :             :                 }
    1414                 :             :             }
    1415                 :             : 
    1416         [ +  + ]:        6456 :             if (update_state == TxUpdate::NOTIFY_CHANGED) {
    1417   [ +  -  +  - ]:         352 :                 NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
    1418                 :             :             }
    1419                 :             : 
    1420                 :             :             // If a transaction changes its tx state, that usually changes the balance
    1421                 :             :             // available of the outputs it spends. So force those to be recomputed
    1422   [ +  -  +  - ]:       12912 :             MarkInputsDirty(wtx.GetTx());
    1423                 :             :         }
    1424                 :             :     }
    1425                 :       15188 : }
    1426                 :             : 
    1427                 :      173852 : bool CWallet::SyncTransaction(const CTransactionRef& ptx, const SyncTxState& state, bool rescanning_old_block)
    1428                 :             : {
    1429         [ +  + ]:      173852 :     if (!AddToWalletIfInvolvingMe(ptx, state, rescanning_old_block))
    1430                 :             :         return false; // Not one of ours
    1431                 :             : 
    1432                 :             :     // If a transaction changes 'conflicted' state, that changes the balance
    1433                 :             :     // available of the outputs it spends. So force those to be
    1434                 :             :     // recomputed, also:
    1435                 :       26773 :     MarkInputsDirty(ptx);
    1436                 :       26773 :     return true;
    1437                 :             : }
    1438                 :             : 
    1439                 :        8494 : void CWallet::transactionAddedToMempool(const CTransactionRef& tx) {
    1440                 :        8494 :     LOCK(cs_wallet);
    1441         [ +  - ]:        8494 :     SyncTransaction(tx, TxStateInMempool{});
    1442                 :             : 
    1443                 :        8494 :     auto it = mapWallet.find(tx->GetHash());
    1444         [ +  + ]:        8494 :     if (it != mapWallet.end()) {
    1445         [ +  - ]:        4022 :         RefreshMempoolStatus(it->second, chain());
    1446                 :             :     }
    1447                 :             : 
    1448                 :        8494 :     const Txid& txid = tx->GetHash();
    1449                 :             : 
    1450         [ +  + ]:       24085 :     for (const CTxIn& tx_in : tx->vin) {
    1451                 :             :         // For each wallet transaction spending this prevout..
    1452         [ +  + ]:       27406 :         for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
    1453         [ +  + ]:       11815 :             const Txid& spent_id = range.first->second;
    1454                 :             :             // Skip the recently added tx
    1455         [ +  + ]:       11815 :             if (spent_id == txid) continue;
    1456         [ +  - ]:        5966 :             RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    1457         [ +  + ]:        2990 :                 return wtx.mempool_conflicts.insert(txid).second ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
    1458                 :             :             });
    1459                 :             :         }
    1460                 :             : 
    1461                 :             :     }
    1462                 :             : 
    1463         [ +  + ]:        8494 :     if (tx->version == TRUC_VERSION) {
    1464                 :             :         // Unconfirmed TRUC transactions are only allowed a 1-parent-1-child topology.
    1465                 :             :         // For any unconfirmed v3 parents (there should be a maximum of 1 except in reorgs),
    1466                 :             :         // record this child so the wallet doesn't try to spend any other outputs
    1467         [ +  + ]:         543 :         for (const CTxIn& tx_in : tx->vin) {
    1468                 :         400 :             auto parent_it = mapWallet.find(tx_in.prevout.hash);
    1469         [ +  + ]:         548 :             if (parent_it != mapWallet.end()) {
    1470         [ +  + ]:         148 :                 CWalletTx& parent_wtx = parent_it->second;
    1471         [ +  + ]:         148 :                 if (parent_wtx.isUnconfirmed()) {
    1472         [ -  + ]:          31 :                     parent_wtx.truc_child_in_mempool = tx->GetHash();
    1473                 :             :                     // Even though these siblings do not spend the same utxos, they can't
    1474                 :             :                     // be present in the mempool at the same time because of TRUC policy rules
    1475         [ +  - ]:          31 :                     UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/true);
    1476                 :             :                 }
    1477                 :             :             }
    1478                 :             :         }
    1479                 :             :     }
    1480                 :        8494 : }
    1481                 :             : 
    1482                 :       59327 : void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {
    1483                 :       59327 :     LOCK(cs_wallet);
    1484                 :       59327 :     auto it = mapWallet.find(tx->GetHash());
    1485         [ +  + ]:       59327 :     if (it != mapWallet.end()) {
    1486         [ +  - ]:       14080 :         RefreshMempoolStatus(it->second, chain());
    1487                 :             :     }
    1488                 :             :     // Handle transactions that were removed from the mempool because they
    1489                 :             :     // conflict with transactions in a newly connected block.
    1490         [ +  + ]:       59327 :     if (reason == MemPoolRemovalReason::CONFLICT) {
    1491                 :             :         // Trigger external -walletnotify notifications for these transactions.
    1492                 :             :         // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
    1493                 :             :         //
    1494                 :             :         // 1. The transactionRemovedFromMempool callback does not currently
    1495                 :             :         //    provide the conflicting block's hash and height, and for backwards
    1496                 :             :         //    compatibility reasons it may not be not safe to store conflicted
    1497                 :             :         //    wallet transactions with a null block hash. See
    1498                 :             :         //    https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
    1499                 :             :         // 2. For most of these transactions, the wallet's internal conflict
    1500                 :             :         //    detection in the blockConnected handler will subsequently call
    1501                 :             :         //    MarkConflicted and update them with CONFLICTED status anyway. This
    1502                 :             :         //    applies to any wallet transaction that has inputs spent in the
    1503                 :             :         //    block, or that has ancestors in the wallet with inputs spent by
    1504                 :             :         //    the block.
    1505                 :             :         // 3. Longstanding behavior since the sync implementation in
    1506                 :             :         //    https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
    1507                 :             :         //    implementation before that was to mark these transactions
    1508                 :             :         //    unconfirmed rather than conflicted.
    1509                 :             :         //
    1510                 :             :         // Nothing described above should be seen as an unchangeable requirement
    1511                 :             :         // when improving this code in the future. The wallet's heuristics for
    1512                 :             :         // distinguishing between conflicted and unconfirmed transactions are
    1513                 :             :         // imperfect, and could be improved in general, see
    1514                 :             :         // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
    1515         [ +  - ]:          41 :         SyncTransaction(tx, TxStateInactive{});
    1516                 :             :     }
    1517                 :             : 
    1518                 :       59327 :     const Txid& txid = tx->GetHash();
    1519                 :             : 
    1520         [ +  + ]:      125257 :     for (const CTxIn& tx_in : tx->vin) {
    1521                 :             :         // Iterate over all wallet transactions spending txin.prev
    1522                 :             :         // and recursively mark them as no longer conflicting with
    1523                 :             :         // txid
    1524         [ +  + ]:       77423 :         for (auto range = mapTxSpends.equal_range(tx_in.prevout); range.first != range.second; range.first++) {
    1525         [ +  - ]:       11493 :             const Txid& spent_id = range.first->second;
    1526                 :             : 
    1527         [ +  - ]:       22986 :             RecursiveUpdateTxState(/*batch=*/nullptr, spent_id, [&txid](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    1528         [ +  + ]:       11499 :                 return wtx.mempool_conflicts.erase(txid) ? TxUpdate::CHANGED : TxUpdate::UNCHANGED;
    1529                 :             :             });
    1530                 :             :         }
    1531                 :             :     }
    1532                 :             : 
    1533         [ +  + ]:       59327 :     if (tx->version == TRUC_VERSION) {
    1534                 :             :         // If this tx has a parent, unset its truc_child_in_mempool to make it possible
    1535                 :             :         // to spend from the parent again. If this tx was replaced by another
    1536                 :             :         // child of the same parent, transactionAddedToMempool
    1537                 :             :         // will update truc_child_in_mempool
    1538         [ +  + ]:         543 :         for (const CTxIn& tx_in : tx->vin) {
    1539                 :         400 :             auto parent_it = mapWallet.find(tx_in.prevout.hash);
    1540         [ +  + ]:         548 :             if (parent_it != mapWallet.end()) {
    1541         [ +  + ]:         148 :                 CWalletTx& parent_wtx = parent_it->second;
    1542         [ +  + ]:         148 :                 if (parent_wtx.truc_child_in_mempool == tx->GetHash()) {
    1543         [ +  - ]:          31 :                     parent_wtx.truc_child_in_mempool = std::nullopt;
    1544         [ +  - ]:          31 :                     UpdateTrucSiblingConflicts(parent_wtx, txid, /*add_conflict=*/false);
    1545                 :             :                 }
    1546                 :             :             }
    1547                 :             :         }
    1548                 :             :     }
    1549                 :       59327 : }
    1550                 :             : 
    1551                 :       54517 : void CWallet::blockConnected(const ChainstateRole& role, const interfaces::BlockInfo& block)
    1552                 :             : {
    1553         [ +  + ]:       54517 :     if (role.historical) {
    1554                 :             :         return;
    1555                 :             :     }
    1556         [ -  + ]:       54417 :     assert(block.data);
    1557                 :       54417 :     LOCK(cs_wallet);
    1558                 :             : 
    1559                 :             :     // Update the best block in memory first. This will set the best block's height, which is
    1560                 :             :     // needed by MarkConflicted.
    1561         [ +  - ]:       54417 :     SetLastBlockProcessedInMem(block.height, block.hash);
    1562                 :             : 
    1563                 :             :     // No need to scan block if it was created before the wallet birthday.
    1564                 :             :     // Uses chain max time and twice the grace period to adjust time for block time variability.
    1565   [ +  +  +  - ]:       54417 :     if (block.chain_time_max < m_birth_time.load() - (TIMESTAMP_WINDOW * 2)) return;
    1566                 :             : 
    1567                 :             :     // Scan block
    1568                 :             :     bool wallet_updated = false;
    1569   [ -  +  +  + ]:      108938 :     for (size_t index = 0; index < block.data->vtx.size(); index++) {
    1570         [ +  - ]:       58992 :         wallet_updated |= SyncTransaction(block.data->vtx[index], TxStateConfirmed{block.hash, block.height, static_cast<int>(index)});
    1571         [ +  - ]:       58992 :         transactionRemovedFromMempool(block.data->vtx[index], MemPoolRemovalReason::BLOCK);
    1572                 :             :     }
    1573                 :             : 
    1574                 :             :     // Update on disk if this block resulted in us updating a tx, or periodically every 144 blocks (~1 day)
    1575   [ +  +  +  + ]:       49946 :     if (wallet_updated || block.height % 144 == 0) {
    1576         [ +  - ]:       11492 :         WriteBestBlock();
    1577                 :             :     }
    1578                 :       54417 : }
    1579                 :             : 
    1580                 :        3460 : void CWallet::blockDisconnected(const interfaces::BlockInfo& block)
    1581                 :             : {
    1582         [ -  + ]:        3460 :     assert(block.data);
    1583                 :        3460 :     LOCK(cs_wallet);
    1584                 :             : 
    1585                 :             :     // At block disconnection, this will change an abandoned transaction to
    1586                 :             :     // be unconfirmed, whether or not the transaction is added back to the mempool.
    1587                 :             :     // User may have to call abandontransaction again. It may be addressed in the
    1588                 :             :     // future with a stickier abandoned state or even removing abandontransaction call.
    1589                 :        3460 :     int disconnect_height = block.height;
    1590                 :             : 
    1591   [ -  +  +  + ]:        6988 :     for (size_t index = 0; index < block.data->vtx.size(); index++) {
    1592         [ +  - ]:        3528 :         const CTransactionRef& ptx = block.data->vtx[index];
    1593                 :             :         // Coinbase transactions are not only inactive but also abandoned,
    1594                 :             :         // meaning they should never be relayed standalone via the p2p protocol.
    1595         [ +  - ]:        3528 :         SyncTransaction(ptx, TxStateInactive{/*abandoned=*/index == 0});
    1596                 :             : 
    1597         [ +  + ]:        7169 :         for (const CTxIn& tx_in : ptx->vin) {
    1598                 :             :             // No other wallet transactions conflicted with this transaction
    1599         [ +  + ]:        3641 :             if (!mapTxSpends.contains(tx_in.prevout)) continue;
    1600                 :             : 
    1601                 :         109 :             std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
    1602                 :             : 
    1603                 :             :             // For all of the spends that conflict with this transaction
    1604         [ +  + ]:        3774 :             for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
    1605         [ +  + ]:         133 :                 CWalletTx& wtx = mapWallet.find(_it->second)->second;
    1606                 :             : 
    1607         [ +  + ]:         133 :                 if (!wtx.isBlockConflicted()) continue;
    1608                 :             : 
    1609                 :          36 :                 auto try_updating_state = [&](CWalletTx& tx) {
    1610         [ +  - ]:          20 :                     if (!tx.isBlockConflicted()) return TxUpdate::UNCHANGED;
    1611         [ +  + ]:          20 :                     if (tx.state<TxStateBlockConflicted>()->conflicting_block_height >= disconnect_height) {
    1612         [ -  + ]:          19 :                         tx.m_state = TxStateInactive{};
    1613                 :          19 :                         return TxUpdate::CHANGED;
    1614                 :             :                     }
    1615                 :             :                     return TxUpdate::UNCHANGED;
    1616                 :          16 :                 };
    1617                 :             : 
    1618   [ +  -  +  - ]:          32 :                 RecursiveUpdateTxState(wtx.GetTx()->GetHash(), try_updating_state);
    1619                 :             :             }
    1620                 :             :         }
    1621                 :             :     }
    1622                 :             : 
    1623                 :             :     // Update the best block
    1624   [ +  -  +  - ]:        3460 :     SetLastBlockProcessed(block.height - 1, *Assert(block.prev_hash));
    1625                 :        3460 : }
    1626                 :             : 
    1627                 :       52331 : void CWallet::updatedBlockTip()
    1628                 :             : {
    1629                 :       52331 :     m_best_block_time = GetTime();
    1630                 :       52331 : }
    1631                 :             : 
    1632                 :        7014 : void CWallet::BlockUntilSyncedToCurrentChain() const {
    1633                 :        7014 :     AssertLockNotHeld(cs_wallet);
    1634                 :             :     // Skip the queue-draining stuff if we know we're caught up with
    1635                 :             :     // chain().Tip(), otherwise put a callback in the validation interface queue and wait
    1636                 :             :     // for the queue to drain enough to execute it (indicating we are caught up
    1637                 :             :     // at least with the time we entered this function).
    1638         [ +  - ]:       14028 :     uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
    1639                 :        7014 :     chain().waitForNotificationsIfTipChanged(last_block_hash);
    1640                 :        7014 : }
    1641                 :             : 
    1642                 :             : // Note that this function doesn't distinguish between a 0-valued input,
    1643                 :             : // and a not-"is mine" input.
    1644                 :        3024 : CAmount CWallet::GetDebit(const CTxIn &txin) const
    1645                 :             : {
    1646                 :        3024 :     LOCK(cs_wallet);
    1647         [ +  - ]:        3024 :     auto txo = GetTXO(txin.prevout);
    1648         [ +  + ]:        3024 :     if (txo) {
    1649                 :        1579 :         return txo->GetTxOut().nValue;
    1650                 :             :     }
    1651                 :             :     return 0;
    1652                 :        3024 : }
    1653                 :             : 
    1654                 :      627046 : bool CWallet::IsMine(const CTxOut& txout) const
    1655                 :             : {
    1656                 :      627046 :     AssertLockHeld(cs_wallet);
    1657                 :      627046 :     return IsMine(txout.scriptPubKey);
    1658                 :             : }
    1659                 :             : 
    1660                 :       32224 : bool CWallet::IsMine(const CTxDestination& dest) const
    1661                 :             : {
    1662                 :       32224 :     AssertLockHeld(cs_wallet);
    1663         [ +  - ]:       32224 :     return IsMine(GetScriptForDestination(dest));
    1664                 :             : }
    1665                 :             : 
    1666                 :      662685 : bool CWallet::IsMine(const CScript& script) const
    1667                 :             : {
    1668                 :      662685 :     AssertLockHeld(cs_wallet);
    1669                 :             : 
    1670                 :             :     // Search the cache so that IsMine is called only on the relevant SPKMs instead of on everything in m_spk_managers
    1671                 :      662685 :     const auto& it = m_cached_spks.find(script);
    1672         [ +  + ]:      662685 :     if (it != m_cached_spks.end()) {
    1673                 :      206942 :         bool res = false;
    1674         [ +  + ]:      413946 :         for (const auto& spkm : it->second) {
    1675   [ +  +  +  - ]:      413946 :             res = res || spkm->IsMine(script);
    1676                 :             :         }
    1677                 :      206942 :         Assume(res);
    1678                 :      206942 :         return res;
    1679                 :             :     }
    1680                 :             : 
    1681                 :             :     return false;
    1682                 :             : }
    1683                 :             : 
    1684                 :      165408 : bool CWallet::IsMine(const CTransaction& tx) const
    1685                 :             : {
    1686                 :      165408 :     AssertLockHeld(cs_wallet);
    1687         [ +  + ]:      514761 :     for (const CTxOut& txout : tx.vout)
    1688         [ +  + ]:      367448 :         if (IsMine(txout))
    1689                 :             :             return true;
    1690                 :             :     return false;
    1691                 :             : }
    1692                 :             : 
    1693                 :        3049 : bool CWallet::IsMine(const COutPoint& outpoint) const
    1694                 :             : {
    1695                 :        3049 :     AssertLockHeld(cs_wallet);
    1696                 :        3049 :     auto wtx = GetWalletTx(outpoint.hash);
    1697         [ +  + ]:        3049 :     if (!wtx) {
    1698                 :             :         return false;
    1699                 :             :     }
    1700   [ -  +  +  -  :        6054 :     if (outpoint.n >= wtx->GetTx()->vout.size()) {
                   +  - ]
    1701                 :             :         return false;
    1702                 :             :     }
    1703   [ +  -  +  - ]:        6054 :     return IsMine(wtx->GetTx()->vout[outpoint.n]);
    1704                 :             : }
    1705                 :             : 
    1706                 :      156817 : bool CWallet::IsFromMe(const CTransaction& tx) const
    1707                 :             : {
    1708                 :      156817 :     LOCK(cs_wallet);
    1709         [ +  + ]:      350174 :     for (const CTxIn& txin : tx.vin) {
    1710   [ +  -  +  + ]:      196883 :         if (GetTXO(txin.prevout)) return true;
    1711                 :             :     }
    1712                 :             :     return false;
    1713                 :      156817 : }
    1714                 :             : 
    1715                 :        1943 : CAmount CWallet::GetDebit(const CTransaction& tx) const
    1716                 :             : {
    1717                 :        1943 :     CAmount nDebit = 0;
    1718         [ +  + ]:        4954 :     for (const CTxIn& txin : tx.vin)
    1719                 :             :     {
    1720                 :        3011 :         nDebit += GetDebit(txin);
    1721         [ -  + ]:        3011 :         if (!MoneyRange(nDebit))
    1722   [ #  #  #  # ]:           0 :             throw std::runtime_error(std::string(__func__) + ": value out of range");
    1723                 :             :     }
    1724                 :        1943 :     return nDebit;
    1725                 :             : }
    1726                 :             : 
    1727                 :           4 : bool CWallet::IsHDEnabled() const
    1728                 :             : {
    1729                 :             :     // All Active ScriptPubKeyMans must be HD for this to be true
    1730                 :           4 :     bool result = false;
    1731         [ +  + ]:          36 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
    1732   [ +  -  -  + ]:          32 :         if (!spk_man->IsHDEnabled()) return false;
    1733                 :          32 :         result = true;
    1734                 :             :     }
    1735                 :           4 :     return result;
    1736                 :             : }
    1737                 :             : 
    1738                 :       11586 : bool CWallet::CanGetAddresses(bool internal) const
    1739                 :             : {
    1740                 :       11586 :     LOCK(cs_wallet);
    1741         [ +  + ]:       11586 :     if (m_spk_managers.empty()) return false;
    1742         [ +  + ]:       12486 :     for (OutputType t : OUTPUT_TYPES) {
    1743         [ +  - ]:       12473 :         auto spk_man = GetScriptPubKeyMan(t, internal);
    1744   [ +  +  +  -  :       12473 :         if (spk_man && spk_man->CanGetAddresses(internal)) {
                   -  + ]
    1745                 :             :             return true;
    1746                 :             :         }
    1747                 :             :     }
    1748                 :             :     return false;
    1749                 :       11586 : }
    1750                 :             : 
    1751                 :          85 : void CWallet::SetWalletFlag(uint64_t flags)
    1752                 :             : {
    1753                 :          85 :     WalletBatch batch(GetDatabase());
    1754         [ +  - ]:          85 :     return SetWalletFlagWithDB(batch, flags);
    1755                 :          85 : }
    1756                 :             : 
    1757                 :         127 : void CWallet::SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags)
    1758                 :             : {
    1759                 :         127 :     LOCK(cs_wallet);
    1760         [ +  - ]:         127 :     m_wallet_flags |= flags;
    1761   [ +  -  -  + ]:         127 :     if (!batch.WriteWalletFlags(m_wallet_flags))
    1762   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1763                 :         127 : }
    1764                 :             : 
    1765                 :           1 : void CWallet::UnsetWalletFlag(uint64_t flag)
    1766                 :             : {
    1767                 :           1 :     WalletBatch batch(GetDatabase());
    1768         [ +  - ]:           1 :     UnsetWalletFlagWithDB(batch, flag);
    1769                 :           1 : }
    1770                 :             : 
    1771                 :        4189 : void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
    1772                 :             : {
    1773                 :        4189 :     LOCK(cs_wallet);
    1774         [ +  - ]:        4189 :     m_wallet_flags &= ~flag;
    1775   [ +  -  -  + ]:        4189 :     if (!batch.WriteWalletFlags(m_wallet_flags))
    1776   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1777                 :        4189 : }
    1778                 :             : 
    1779                 :        4188 : void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
    1780                 :             : {
    1781                 :        4188 :     UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
    1782                 :        4188 : }
    1783                 :             : 
    1784                 :      219448 : bool CWallet::IsWalletFlagSet(uint64_t flag) const
    1785                 :             : {
    1786                 :      219448 :     return (m_wallet_flags & flag);
    1787                 :             : }
    1788                 :             : 
    1789                 :        1139 : bool CWallet::LoadWalletFlags(uint64_t flags)
    1790                 :             : {
    1791                 :        1139 :     LOCK(cs_wallet);
    1792         [ +  - ]:        1139 :     if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
    1793                 :             :         // contains unknown non-tolerable wallet flags
    1794                 :             :         return false;
    1795                 :             :     }
    1796                 :        1139 :     m_wallet_flags = flags;
    1797                 :             : 
    1798                 :        1139 :     return true;
    1799                 :        1139 : }
    1800                 :             : 
    1801                 :         696 : void CWallet::InitWalletFlags(uint64_t flags)
    1802                 :             : {
    1803                 :         696 :     LOCK(cs_wallet);
    1804                 :             : 
    1805                 :             :     // We should never be writing unknown non-tolerable wallet flags
    1806         [ -  + ]:         696 :     assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
    1807                 :             :     // This should only be used once, when creating a new wallet - so current flags are expected to be blank
    1808         [ -  + ]:         696 :     assert(m_wallet_flags == 0);
    1809                 :             : 
    1810   [ +  -  +  -  :        1392 :     if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
                   -  + ]
    1811   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1812                 :             :     }
    1813                 :             : 
    1814   [ +  -  +  - ]:         696 :     Assert(LoadWalletFlags(flags));
    1815                 :         696 : }
    1816                 :             : 
    1817                 :         461 : uint64_t CWallet::GetWalletFlags() const
    1818                 :             : {
    1819                 :         461 :     return m_wallet_flags;
    1820                 :             : }
    1821                 :             : 
    1822                 :       40348 : void CWallet::MaybeUpdateBirthTime(int64_t time)
    1823                 :             : {
    1824         [ +  + ]:       40348 :     int64_t birthtime = m_birth_time.load();
    1825         [ +  + ]:       40348 :     if (time < birthtime) {
    1826                 :        1604 :         m_birth_time = time;
    1827                 :             :     }
    1828                 :       40348 : }
    1829                 :             : 
    1830                 :        1877 : bool CWallet::SubmitTxMemoryPoolAndRelay(CWalletTx& wtx,
    1831                 :             :                                          std::string& err_string,
    1832                 :             :                                          node::TxBroadcast broadcast_method) const
    1833                 :             : {
    1834                 :        1877 :     AssertLockHeld(cs_wallet);
    1835                 :             : 
    1836                 :             :     // Can't relay if wallet is not broadcasting
    1837         [ +  - ]:        1877 :     if (!GetBroadcastTransactions()) return false;
    1838                 :             :     // Don't relay abandoned transactions
    1839         [ +  + ]:        1877 :     if (wtx.isAbandoned()) return false;
    1840                 :             :     // Don't try to submit coinbase transactions. These would fail anyway but would
    1841                 :             :     // cause log spam.
    1842         [ +  - ]:        1877 :     if (wtx.IsCoinBase()) return false;
    1843                 :             :     // Don't try to submit conflicted or confirmed transactions.
    1844         [ +  - ]:        1877 :     if (GetTxDepthInMainChain(wtx) != 0) return false;
    1845                 :             : 
    1846                 :        1877 :     const char* what{""};
    1847   [ +  +  -  - ]:        1877 :     switch (broadcast_method) {
    1848                 :        1707 :     case node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL:
    1849                 :        1707 :         what = "to mempool and for broadcast to peers";
    1850                 :        1707 :         break;
    1851                 :         170 :     case node::TxBroadcast::MEMPOOL_NO_BROADCAST:
    1852                 :         170 :         what = "to mempool without broadcast";
    1853                 :         170 :         break;
    1854                 :           0 :     case node::TxBroadcast::NO_MEMPOOL_PRIVATE_BROADCAST:
    1855                 :           0 :         what = "for private broadcast without adding to the mempool";
    1856                 :           0 :         break;
    1857                 :             :     }
    1858         [ +  - ]:        1877 :     WalletLogPrintf("Submitting wtx %s %s", wtx.GetHash().ToString(), what);
    1859                 :             :     // We must set TxStateInMempool here. Even though it will also be set later by the
    1860                 :             :     // entered-mempool callback, if we did not there would be a race where a
    1861                 :             :     // user could call sendmoney in a loop and hit spurious out of funds errors
    1862                 :             :     // because we think that this newly generated transaction's change is
    1863                 :             :     // unavailable as we're not yet aware that it is in the mempool.
    1864                 :             :     //
    1865                 :             :     // If broadcast fails for any reason, trying to set wtx.m_state here would be incorrect.
    1866                 :             :     // If transaction was previously in the mempool, it should be updated when
    1867                 :             :     // TransactionRemovedFromMempool fires.
    1868   [ +  -  +  - ]:        1877 :     bool ret = chain().broadcastTransaction(wtx.GetTx(), m_max_tx_fee, m_max_tx_fee_rate, broadcast_method, err_string);
    1869   [ +  +  +  + ]:        3628 :     if (ret) wtx.m_state = TxStateInMempool{};
    1870                 :             :     return ret;
    1871                 :             : }
    1872                 :             : 
    1873                 :        4500 : std::set<Txid> CWallet::GetTxConflicts(const CWalletTx& wtx) const
    1874                 :             : {
    1875                 :        4500 :     AssertLockHeld(cs_wallet);
    1876                 :             : 
    1877                 :        4500 :     const Txid myHash{wtx.GetHash()};
    1878                 :        4500 :     std::set<Txid> result{GetConflicts(myHash)};
    1879                 :        4500 :     result.erase(myHash);
    1880                 :        4500 :     return result;
    1881                 :             : }
    1882                 :             : 
    1883                 :         108 : bool CWallet::ShouldResend() const
    1884                 :             : {
    1885                 :             :     // Don't attempt to resubmit if the wallet is configured to not broadcast
    1886         [ +  - ]:         108 :     if (!fBroadcastTransactions) return false;
    1887                 :             : 
    1888                 :             :     // During reindex, importing and IBD, old wallet transactions become
    1889                 :             :     // unconfirmed. Don't resend them as that would spam other nodes.
    1890                 :             :     // We only allow forcing mempool submission when not relaying to avoid this spam.
    1891         [ +  + ]:         108 :     if (!chain().isReadyToBroadcast()) return false;
    1892                 :             : 
    1893                 :             :     // Do this infrequently and randomly to avoid giving away
    1894                 :             :     // that these are our transactions.
    1895         [ +  + ]:          85 :     if (NodeClock::now() < m_next_resend) return false;
    1896                 :             : 
    1897                 :             :     return true;
    1898                 :             : }
    1899                 :             : 
    1900                 :        1262 : NodeClock::time_point CWallet::GetDefaultNextResend() { return FastRandomContext{}.rand_uniform_delay(NodeClock::now() + 12h, 24h); }
    1901                 :             : 
    1902                 :             : // Resubmit transactions from the wallet to the mempool, optionally asking the
    1903                 :             : // mempool to relay them. On startup, we will do this for all unconfirmed
    1904                 :             : // transactions but will not ask the mempool to relay them. We do this on startup
    1905                 :             : // to ensure that our own mempool is aware of our transactions. There
    1906                 :             : // is a privacy side effect here as not broadcasting on startup also means that we won't
    1907                 :             : // inform the world of our wallet's state, particularly if the wallet (or node) is not
    1908                 :             : // yet synced.
    1909                 :             : //
    1910                 :             : // Otherwise this function is called periodically in order to relay our unconfirmed txs.
    1911                 :             : // We do this on a random timer to slightly obfuscate which transactions
    1912                 :             : // come from our wallet.
    1913                 :             : //
    1914                 :             : // TODO: Ideally, we'd only resend transactions that we think should have been
    1915                 :             : // mined in the most recent block. Any transaction that wasn't in the top
    1916                 :             : // blockweight of transactions in the mempool shouldn't have been mined,
    1917                 :             : // and so is probably just sitting in the mempool waiting to be confirmed.
    1918                 :             : // Rebroadcasting does nothing to speed up confirmation and only damages
    1919                 :             : // privacy.
    1920                 :             : //
    1921                 :             : // The `force` option results in all unconfirmed transactions being submitted to
    1922                 :             : // the mempool. This does not necessarily result in those transactions being relayed,
    1923                 :             : // that depends on the `broadcast_method` option. Periodic rebroadcast uses the pattern
    1924                 :             : // broadcast_method=TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL force=false, while loading into
    1925                 :             : // the mempool (on start, or after import) uses
    1926                 :             : // broadcast_method=TxBroadcast::MEMPOOL_NO_BROADCAST force=true.
    1927                 :        1705 : void CWallet::ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force)
    1928                 :             : {
    1929                 :             :     // Don't attempt to resubmit if the wallet is configured to not broadcast,
    1930                 :             :     // even if forcing.
    1931         [ +  + ]:        1705 :     if (!fBroadcastTransactions) return;
    1932                 :             : 
    1933                 :        1702 :     int submitted_tx_count = 0;
    1934                 :             : 
    1935                 :        1702 :     { // cs_wallet scope
    1936                 :        1702 :         LOCK(cs_wallet);
    1937                 :             : 
    1938                 :             :         // First filter for the transactions we want to rebroadcast.
    1939                 :             :         // We use a set with WalletTxOrderComparator so that rebroadcasting occurs in insertion order
    1940                 :        1702 :         std::set<CWalletTx*, WalletTxOrderComparator> to_submit;
    1941   [ +  +  +  + ]:       22453 :         for (auto& [txid, wtx] : mapWallet) {
    1942                 :             :             // Only rebroadcast unconfirmed txs
    1943         [ +  + ]:       20751 :             if (!wtx.isUnconfirmed()) continue;
    1944                 :             : 
    1945                 :             :             // Attempt to rebroadcast all txes more than 5 minutes older than
    1946                 :             :             // the last block, or all txs if forcing.
    1947   [ +  +  +  + ]:         222 :             if (!force && wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
    1948         [ +  - ]:         212 :             to_submit.insert(&wtx);
    1949                 :             :         }
    1950                 :             :         // Now try submitting the transactions to the memory pool and (optionally) relay them.
    1951         [ +  + ]:        1914 :         for (auto wtx : to_submit) {
    1952         [ +  - ]:         212 :             std::string unused_err_string;
    1953   [ +  -  +  + ]:         212 :             if (SubmitTxMemoryPoolAndRelay(*wtx, unused_err_string, broadcast_method)) ++submitted_tx_count;
    1954                 :         212 :         }
    1955         [ +  - ]:        1702 :     } // cs_wallet
    1956                 :             : 
    1957         [ +  + ]:        1702 :     if (submitted_tx_count > 0) {
    1958                 :          88 :         WalletLogPrintf("%s: resubmit %u unconfirmed transactions", __func__, submitted_tx_count);
    1959                 :             :     }
    1960                 :             : }
    1961                 :             : 
    1962                 :             : /** @} */ // end of mapWallet
    1963                 :             : 
    1964                 :          93 : void MaybeResendWalletTxs(WalletContext& context)
    1965                 :             : {
    1966         [ +  + ]:         201 :     for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
    1967   [ +  -  +  + ]:         108 :         if (!pwallet->ShouldResend()) continue;
    1968         [ +  - ]:          22 :         pwallet->ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*force=*/false);
    1969         [ +  - ]:         108 :         pwallet->SetNextResend();
    1970                 :             :     }
    1971                 :          93 : }
    1972                 :             : 
    1973                 :             : 
    1974                 :        2720 : bool CWallet::SignTransaction(CMutableTransaction& tx) const
    1975                 :             : {
    1976                 :        2720 :     AssertLockHeld(cs_wallet);
    1977                 :             : 
    1978                 :             :     // Build coins map
    1979                 :        2720 :     std::map<COutPoint, Coin> coins;
    1980         [ +  + ]:       13628 :     for (auto& input : tx.vin) {
    1981                 :       10908 :         const auto mi = mapWallet.find(input.prevout.hash);
    1982   [ +  -  +  -  :       21816 :         if(mi == mapWallet.end() || input.prevout.n >= mi->second.GetTx()->vout.size()) {
          -  +  +  -  +  
                      - ]
    1983                 :             :             return false;
    1984                 :             :         }
    1985         [ +  + ]:       10908 :         const CWalletTx& wtx = mi->second;
    1986         [ +  + ]:       10908 :         int prev_height = wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height : 0;
    1987   [ +  -  +  -  :       21816 :         coins[input.prevout] = Coin(wtx.GetTx()->vout[input.prevout.n], prev_height, wtx.IsCoinBase());
             +  -  +  - ]
    1988                 :             :     }
    1989         [ +  - ]:        2720 :     std::map<int, bilingual_str> input_errors;
    1990         [ +  - ]:        2720 :     return SignTransaction(tx, coins, SIGHASH_DEFAULT, input_errors);
    1991                 :        5440 : }
    1992                 :             : 
    1993                 :        3032 : bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
    1994                 :             : {
    1995                 :             :     // Try to sign with all ScriptPubKeyMans
    1996         [ +  + ]:       17558 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
    1997                 :             :         // spk_man->SignTransaction will return true if the transaction is complete,
    1998                 :             :         // so we can exit early and return true if that happens
    1999   [ +  -  +  + ]:       17548 :         if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
    2000                 :        3022 :             return true;
    2001                 :             :         }
    2002                 :             :     }
    2003                 :             : 
    2004                 :             :     // At this point, one input was not fully signed otherwise we would have exited already
    2005                 :          10 :     return false;
    2006                 :             : }
    2007                 :             : 
    2008                 :        1434 : std::optional<PSBTError> CWallet::FillPSBT(PartiallySignedTransaction& psbtx, const common::PSBTFillOptions& options, bool& complete, size_t* n_signed) const
    2009                 :             : {
    2010         [ -  + ]:        1434 :     if (n_signed) {
    2011                 :           0 :         *n_signed = 0;
    2012                 :             :     }
    2013                 :        1434 :     LOCK(cs_wallet);
    2014                 :             :     // Get all of the previous transactions
    2015         [ +  + ]:        5436 :     for (PSBTInput& input : psbtx.inputs) {
    2016   [ +  -  +  + ]:        4002 :         if (PSBTInputSigned(input)) {
    2017                 :          18 :             continue;
    2018                 :             :         }
    2019                 :             : 
    2020                 :             :         // If we have no utxo, grab it from the wallet.
    2021         [ +  + ]:        3984 :         if (!input.non_witness_utxo) {
    2022                 :        2476 :             const Txid& txhash = input.prev_txid;
    2023                 :        2476 :             const auto it = mapWallet.find(txhash);
    2024         [ +  + ]:        6162 :             if (it != mapWallet.end()) {
    2025         [ +  - ]:        2160 :                 const CWalletTx& wtx = it->second;
    2026                 :             :                 // We only need the non_witness_utxo, which is a superset of the witness_utxo.
    2027                 :             :                 //   The signing code will switch to the smaller witness_utxo if this is ok.
    2028   [ +  -  -  + ]:        2160 :                 input.non_witness_utxo = wtx.GetTx();
    2029                 :             :             }
    2030                 :             :         }
    2031                 :             :     }
    2032                 :             : 
    2033         [ +  - ]:        1434 :     std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
    2034         [ -  + ]:        1434 :     if (!txdata_res) {
    2035                 :           0 :         return PSBTError::INVALID_TX;
    2036                 :             :     }
    2037         [ +  - ]:        1434 :     const PrecomputedTransactionData& txdata = *txdata_res;
    2038                 :             : 
    2039                 :             :     // Fill in information from ScriptPubKeyMans
    2040   [ +  -  +  + ]:       11788 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
    2041                 :       10363 :         int n_signed_this_spkm = 0;
    2042         [ +  - ]:       10363 :         const auto error{spk_man->FillPSBT(psbtx, txdata, options, &n_signed_this_spkm)};
    2043         [ +  + ]:       10363 :         if (error) {
    2044                 :           9 :             return error;
    2045                 :             :         }
    2046                 :             : 
    2047         [ -  + ]:       10354 :         if (n_signed) {
    2048                 :           0 :             (*n_signed) += n_signed_this_spkm;
    2049                 :             :         }
    2050                 :           9 :     }
    2051                 :             : 
    2052         [ +  - ]:        1425 :     RemoveUnnecessaryTransactions(psbtx);
    2053                 :             : 
    2054                 :             :     // Complete if every input is now signed
    2055                 :        1425 :     complete = true;
    2056   [ -  +  +  + ]:        5417 :     for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
    2057         [ +  - ]:        3992 :         complete &= PSBTInputSignedAndVerified(psbtx, i, &txdata);
    2058                 :             :     }
    2059                 :             : 
    2060                 :        1425 :     return {};
    2061         [ +  - ]:        2868 : }
    2062                 :             : 
    2063                 :           9 : SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
    2064                 :             : {
    2065                 :           9 :     SignatureData sigdata;
    2066         [ +  - ]:           9 :     CScript script_pub_key = GetScriptForDestination(pkhash);
    2067         [ +  - ]:          92 :     for (const auto& spk_man_pair : m_spk_managers) {
    2068   [ +  -  +  + ]:          92 :         if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
    2069         [ +  - ]:           9 :             LOCK(cs_wallet);  // DescriptorScriptPubKeyMan calls IsLocked which can lock cs_wallet in a deadlocking order
    2070   [ +  -  +  - ]:           9 :             return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
    2071                 :           9 :         }
    2072                 :             :     }
    2073                 :             :     return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    2074                 :           9 : }
    2075                 :             : 
    2076                 :        3851 : OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
    2077                 :             : {
    2078                 :             :     // If -changetype is specified, always use that change type.
    2079         [ +  + ]:        3851 :     if (change_type) {
    2080                 :         265 :         return *change_type;
    2081                 :             :     }
    2082                 :             : 
    2083                 :             :     // if m_default_address_type is legacy, use legacy address as change.
    2084         [ +  + ]:        3586 :     if (m_default_address_type == OutputType::LEGACY) {
    2085                 :             :         return OutputType::LEGACY;
    2086                 :             :     }
    2087                 :             : 
    2088                 :        3560 :     bool any_tr{false};
    2089                 :        3560 :     bool any_wpkh{false};
    2090                 :        3560 :     bool any_sh{false};
    2091                 :        3560 :     bool any_pkh{false};
    2092                 :             : 
    2093         [ +  + ]:       42849 :     for (const auto& recipient : vecSend) {
    2094         [ +  - ]:       39289 :         if (std::get_if<WitnessV1Taproot>(&recipient.dest)) {
    2095                 :             :             any_tr = true;
    2096         [ +  - ]:       38938 :         } else if (std::get_if<WitnessV0KeyHash>(&recipient.dest)) {
    2097                 :             :             any_wpkh = true;
    2098         [ +  - ]:       46469 :         } else if (std::get_if<ScriptHash>(&recipient.dest)) {
    2099                 :             :             any_sh = true;
    2100         [ +  - ]:       45394 :         } else if (std::get_if<PKHash>(&recipient.dest)) {
    2101                 :        5973 :             any_pkh = true;
    2102                 :             :         }
    2103                 :             :     }
    2104                 :             : 
    2105                 :        3560 :     const bool has_bech32m_spkman(GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/true));
    2106         [ +  + ]:        3560 :     if (has_bech32m_spkman && any_tr) {
    2107                 :             :         // Currently tr is the only type supported by the BECH32M spkman
    2108                 :             :         return OutputType::BECH32M;
    2109                 :             :     }
    2110                 :        3213 :     const bool has_bech32_spkman(GetScriptPubKeyMan(OutputType::BECH32, /*internal=*/true));
    2111         [ +  + ]:        3213 :     if (has_bech32_spkman && any_wpkh) {
    2112                 :             :         // Currently wpkh is the only type supported by the BECH32 spkman
    2113                 :             :         return OutputType::BECH32;
    2114                 :             :     }
    2115                 :         404 :     const bool has_p2sh_segwit_spkman(GetScriptPubKeyMan(OutputType::P2SH_SEGWIT, /*internal=*/true));
    2116         [ +  + ]:         404 :     if (has_p2sh_segwit_spkman && any_sh) {
    2117                 :             :         // Currently sh_wpkh is the only type supported by the P2SH_SEGWIT spkman
    2118                 :             :         // As of 2021 about 80% of all SH are wrapping WPKH, so use that
    2119                 :             :         return OutputType::P2SH_SEGWIT;
    2120                 :             :     }
    2121                 :         349 :     const bool has_legacy_spkman(GetScriptPubKeyMan(OutputType::LEGACY, /*internal=*/true));
    2122         [ +  + ]:         349 :     if (has_legacy_spkman && any_pkh) {
    2123                 :             :         // Currently pkh is the only type supported by the LEGACY spkman
    2124                 :             :         return OutputType::LEGACY;
    2125                 :             :     }
    2126                 :             : 
    2127         [ +  + ]:         270 :     if (has_bech32m_spkman) {
    2128                 :             :         return OutputType::BECH32M;
    2129                 :             :     }
    2130         [ +  + ]:          32 :     if (has_bech32_spkman) {
    2131                 :             :         return OutputType::BECH32;
    2132                 :             :     }
    2133                 :             :     // else use m_default_address_type for change
    2134                 :          18 :     return m_default_address_type;
    2135                 :             : }
    2136                 :             : 
    2137                 :        1672 : void CWallet::CommitTransaction(
    2138                 :             :     CTransactionRef tx,
    2139                 :             :     std::optional<Txid> replaces_txid,
    2140                 :             :     std::optional<std::string> comment,
    2141                 :             :     std::optional<std::string> comment_to,
    2142                 :             :     const std::vector<std::string>& messages,
    2143                 :             :     const std::vector<std::string>& payment_requests
    2144                 :             : )
    2145                 :             : {
    2146                 :        1672 :     LOCK(cs_wallet);
    2147   [ +  -  +  -  :        3344 :     WalletLogPrintf("CommitTransaction:\n%s", util::RemoveSuffixView(tx->ToString(), "\n"));
                   +  - ]
    2148                 :             : 
    2149                 :             :     // Add tx to wallet, because if it has change it's also ours,
    2150                 :             :     // otherwise just for transaction history.
    2151   [ +  -  +  -  :        5016 :     CWalletTx* wtx = AddToWallet(tx, TxStateInactive{}, [&](CWalletTx& wtx, bool new_tx) {
             +  -  +  - ]
    2152         [ +  + ]:        1672 :         if (replaces_txid) wtx.m_replaces_txid = replaces_txid;
    2153         [ +  + ]:        1672 :         if (comment) wtx.m_comment = comment;
    2154         [ +  + ]:        1672 :         if (comment_to) wtx.m_comment_to = comment_to;
    2155         [ -  + ]:        1672 :         if (!messages.empty()) wtx.m_messages = messages;
    2156         [ -  + ]:        1672 :         if (!payment_requests.empty()) wtx.m_payment_requests = payment_requests;
    2157                 :        1672 :         return true;
    2158                 :             :     });
    2159                 :             : 
    2160                 :             :     // wtx can only be null if the db write failed.
    2161         [ -  + ]:        1672 :     if (!wtx) {
    2162   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": Wallet db error, transaction commit failed");
    2163                 :             :     }
    2164                 :             : 
    2165                 :             :     // Notify that old coins are spent
    2166         [ +  + ]:        5784 :     for (const CTxIn& txin : tx->vin) {
    2167         [ +  - ]:        4112 :         CWalletTx &coin = mapWallet.at(txin.prevout.hash);
    2168                 :        4112 :         coin.MarkDirty();
    2169   [ +  -  +  - ]:        4112 :         NotifyTransactionChanged(coin.GetHash(), CT_UPDATED);
    2170                 :             :     }
    2171                 :             : 
    2172         [ +  + ]:        1672 :     if (!fBroadcastTransactions) {
    2173                 :             :         // Don't submit tx to the mempool
    2174         [ +  - ]:           7 :         return;
    2175                 :             :     }
    2176                 :             : 
    2177         [ +  - ]:        1665 :     std::string err_string;
    2178   [ +  -  +  + ]:        1665 :     if (!SubmitTxMemoryPoolAndRelay(*wtx, err_string, node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL)) {
    2179         [ +  - ]:           4 :         WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s", err_string);
    2180                 :             :         // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
    2181                 :             :     }
    2182         [ +  - ]:        3337 : }
    2183                 :             : 
    2184                 :         455 : DBErrors CWallet::PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings)
    2185                 :             : {
    2186                 :         455 :     LOCK(cs_wallet);
    2187                 :             : 
    2188         [ +  - ]:         455 :     Assert(m_spk_managers.empty());
    2189         [ +  - ]:         455 :     Assert(m_wallet_flags == 0);
    2190   [ +  -  +  - ]:         455 :     DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
    2191                 :             : 
    2192         [ +  + ]:         455 :     if (m_spk_managers.empty()) {
    2193         [ -  + ]:          28 :         assert(m_external_spk_managers.empty());
    2194         [ -  + ]:          28 :         assert(m_internal_spk_managers.empty());
    2195                 :             :     }
    2196                 :             : 
    2197         [ +  - ]:         455 :     const auto wallet_file = m_database->Filename();
    2198   [ +  -  +  -  :         455 :     switch (nLoadWalletRet) {
          -  +  +  -  -  
                      + ]
    2199                 :             :     case DBErrors::LOAD_OK:
    2200                 :             :         break;
    2201                 :           1 :     case DBErrors::NONCRITICAL_ERROR:
    2202         [ +  - ]:           2 :         warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
    2203                 :             :                                        " or address metadata may be missing or incorrect."),
    2204                 :             :             wallet_file));
    2205                 :           1 :         break;
    2206                 :           0 :     case DBErrors::NEED_RESCAN:
    2207         [ #  # ]:           0 :         warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
    2208                 :             :                                        " Rescanning wallet."), wallet_file));
    2209                 :           0 :         break;
    2210                 :           3 :     case DBErrors::CORRUPT:
    2211         [ +  - ]:           3 :         error = strprintf(_("Error loading %s: Wallet corrupted"), wallet_file);
    2212                 :           3 :         break;
    2213                 :           0 :     case DBErrors::TOO_NEW:
    2214         [ #  # ]:           0 :         error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), wallet_file, CLIENT_NAME);
    2215                 :           0 :         break;
    2216                 :           0 :     case DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED:
    2217         [ #  # ]:           0 :         error = strprintf(_("Error loading %s: External signer wallet being loaded without external signer support compiled"), wallet_file);
    2218                 :           0 :         break;
    2219                 :           1 :     case DBErrors::UNKNOWN_DESCRIPTOR:
    2220         [ +  - ]:           1 :         error = strprintf(_("Unrecognized descriptor found. Loading wallet %s\n\n"
    2221                 :             :                             "The wallet might have been created on a newer version.\n"
    2222                 :           1 :                             "Please try running the latest software version.\n"), wallet_file);
    2223                 :           1 :         break;
    2224                 :           1 :     case DBErrors::UNEXPECTED_LEGACY_ENTRY:
    2225         [ +  - ]:           1 :         error = strprintf(_("Unexpected legacy entry in descriptor wallet found. Loading wallet %s\n\n"
    2226                 :           1 :                             "The wallet might have been tampered with or created with malicious intent.\n"), wallet_file);
    2227                 :           1 :         break;
    2228                 :           0 :     case DBErrors::LEGACY_WALLET:
    2229         [ #  # ]:           0 :         error = strprintf(_("Error loading %s: Wallet is a legacy wallet. Please migrate to a descriptor wallet using the migration tool (migratewallet RPC)."), wallet_file);
    2230                 :           0 :         break;
    2231                 :           0 :     case DBErrors::LOAD_FAIL:
    2232         [ #  # ]:           0 :         error = strprintf(_("Error loading %s"), wallet_file);
    2233                 :           0 :         break;
    2234                 :             :     } // no default case, so the compiler can warn about missing cases
    2235                 :         455 :     return nLoadWalletRet;
    2236         [ +  - ]:         910 : }
    2237                 :             : 
    2238                 :           1 : util::Result<void> CWallet::RemoveTxs(std::vector<Txid>& txs_to_remove)
    2239                 :             : {
    2240                 :           1 :     AssertLockHeld(cs_wallet);
    2241         [ +  - ]:           1 :     bilingual_str str_err;  // future: make RunWithinTxn return a util::Result
    2242   [ +  -  +  - ]:           1 :     bool was_txn_committed = RunWithinTxn(GetDatabase(), /*process_desc=*/"remove transactions", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
    2243                 :           1 :         util::Result<void> result{RemoveTxs(batch, txs_to_remove)};
    2244   [ -  +  -  - ]:           1 :         if (!result) str_err = util::ErrorString(result);
    2245                 :           1 :         return result.has_value();
    2246                 :           1 :     });
    2247   [ -  +  -  - ]:           1 :     if (!str_err.empty()) return util::Error{str_err};
    2248   [ -  +  -  - ]:           1 :     if (!was_txn_committed) return util::Error{_("Error starting/committing db txn for wallet transactions removal process")};
    2249                 :           1 :     return {}; // all good
    2250                 :           1 : }
    2251                 :             : 
    2252                 :           7 : util::Result<void> CWallet::RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove)
    2253                 :             : {
    2254                 :           7 :     AssertLockHeld(cs_wallet);
    2255         [ -  + ]:           7 :     if (!batch.HasActiveTxn()) return util::Error{strprintf(_("The transactions removal process can only be executed within a db txn"))};
    2256                 :             : 
    2257                 :             :     // Check for transaction existence and remove entries from disk
    2258                 :           7 :     std::vector<decltype(mapWallet)::const_iterator> erased_txs;
    2259                 :           7 :     bilingual_str str_err;
    2260         [ +  + ]:          19 :     for (const Txid& hash : txs_to_remove) {
    2261                 :          12 :         auto it_wtx = mapWallet.find(hash);
    2262         [ -  + ]:          12 :         if (it_wtx == mapWallet.end()) {
    2263   [ #  #  #  # ]:           0 :             return util::Error{strprintf(_("Transaction %s does not belong to this wallet"), hash.GetHex())};
    2264                 :             :         }
    2265   [ +  -  -  + ]:          12 :         if (!batch.EraseTx(hash)) {
    2266   [ #  #  #  # ]:           0 :             return util::Error{strprintf(_("Failure removing transaction: %s"), hash.GetHex())};
    2267                 :             :         }
    2268         [ +  - ]:          12 :         erased_txs.emplace_back(it_wtx);
    2269                 :             :     }
    2270                 :             : 
    2271                 :             :     // Register callback to update the memory state only when the db txn is actually dumped to disk
    2272   [ -  -  +  -  :          28 :     batch.RegisterTxnListener({.on_commit=[&, erased_txs]() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
                   +  - ]
    2273                 :             :         // Update the in-memory state and notify upper layers about the removals
    2274         [ +  + ]:          19 :         for (const auto& it : erased_txs) {
    2275                 :          12 :             const Txid hash{it->first};
    2276                 :          12 :             wtxOrdered.erase(it->second.m_it_wtxOrdered);
    2277   [ +  -  +  + ]:          38 :             for (const auto& txin : it->second.GetTx()->vin) {
    2278                 :          14 :                 auto range = mapTxSpends.equal_range(txin.prevout);
    2279         [ +  - ]:          28 :                 for (auto iter = range.first; iter != range.second; ++iter) {
    2280         [ +  - ]:          14 :                     if (iter->second == hash) {
    2281                 :          14 :                         mapTxSpends.erase(iter);
    2282                 :          14 :                         break;
    2283                 :             :                     }
    2284                 :             :                 }
    2285                 :             :             }
    2286   [ -  +  +  -  :          66 :             for (unsigned int i = 0; i < it->second.GetTx()->vout.size(); ++i) {
                   +  + ]
    2287                 :          21 :                 m_txos.erase(COutPoint(hash, i));
    2288                 :             :             }
    2289                 :          12 :             mapWallet.erase(it);
    2290                 :          12 :             NotifyTransactionChanged(hash, CT_DELETED);
    2291                 :             :         }
    2292                 :             : 
    2293                 :           7 :         MarkDirty();
    2294                 :           7 :     }, .on_abort={}});
    2295                 :             : 
    2296                 :           7 :     return {};
    2297   [ +  -  +  - ]:          14 : }
    2298                 :             : 
    2299                 :           0 : void CWallet::ClearInMemoryTxStateForTest()
    2300                 :             : {
    2301                 :           0 :     AssertLockHeld(cs_wallet);
    2302                 :           0 :     mapWallet.clear();
    2303                 :           0 :     wtxOrdered.clear();
    2304                 :           0 :     mapTxSpends.clear();
    2305                 :           0 :     m_txos.clear();
    2306                 :           0 :     m_locked_coins.clear();
    2307                 :           0 :     nOrderPosNext = 0;
    2308                 :           0 : }
    2309                 :             : 
    2310                 :       28269 : bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
    2311                 :             : {
    2312                 :       28269 :     bool fUpdated = false;
    2313                 :       28269 :     bool is_mine;
    2314                 :       28269 :     std::optional<AddressPurpose> purpose;
    2315                 :       28269 :     {
    2316                 :       28269 :         LOCK(cs_wallet);
    2317                 :       28269 :         std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
    2318   [ +  +  -  + ]:       28269 :         fUpdated = mi != m_address_book.end() && !mi->second.IsChange();
    2319                 :             : 
    2320   [ +  +  +  - ]:       28269 :         CAddressBookData& record = mi != m_address_book.end() ? mi->second : m_address_book[address];
    2321         [ -  + ]:       56538 :         record.SetLabel(strName);
    2322         [ +  - ]:       28269 :         is_mine = IsMine(address);
    2323         [ +  - ]:       28269 :         if (new_purpose) { /* update purpose only if requested */
    2324                 :       28269 :             record.purpose = new_purpose;
    2325                 :             :         }
    2326         [ +  - ]:       28269 :         purpose = record.purpose;
    2327                 :           0 :     }
    2328                 :             : 
    2329                 :       28269 :     const std::string& encoded_dest = EncodeDestination(address);
    2330   [ +  -  +  -  :       56538 :     if (new_purpose && !batch.WritePurpose(encoded_dest, PurposeToString(*new_purpose))) {
          +  -  -  +  -  
                      + ]
    2331         [ #  # ]:           0 :         WalletLogPrintf("Error: fail to write address book 'purpose' entry");
    2332                 :             :         return false;
    2333                 :             :     }
    2334   [ +  -  -  + ]:       28269 :     if (!batch.WriteName(encoded_dest, strName)) {
    2335         [ #  # ]:           0 :         WalletLogPrintf("Error: fail to write address book 'name' entry");
    2336                 :             :         return false;
    2337                 :             :     }
    2338                 :             : 
    2339                 :             :     // In very old wallets, address purpose may not be recorded so we derive it from IsMine
    2340                 :       56538 :     NotifyAddressBookChanged(address, strName, is_mine,
    2341   [ +  -  +  - ]:       56538 :                              purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND),
    2342   [ +  +  +  + ]:       56499 :                              (fUpdated ? CT_UPDATED : CT_NEW));
    2343                 :             :     return true;
    2344                 :       28269 : }
    2345                 :             : 
    2346                 :       28269 : bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose)
    2347                 :             : {
    2348                 :       28269 :     WalletBatch batch(GetDatabase());
    2349         [ +  - ]:       28269 :     return SetAddressBookWithDB(batch, address, strName, purpose);
    2350                 :       28269 : }
    2351                 :             : 
    2352                 :           0 : bool CWallet::DelAddressBook(const CTxDestination& address)
    2353                 :             : {
    2354         [ #  # ]:           0 :     return RunWithinTxn(GetDatabase(), /*process_desc=*/"address book entry removal", [&](WalletBatch& batch){
    2355                 :           0 :         return DelAddressBookWithDB(batch, address);
    2356                 :           0 :     });
    2357                 :             : }
    2358                 :             : 
    2359                 :          28 : bool CWallet::DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address)
    2360                 :             : {
    2361                 :          28 :     const std::string& dest = EncodeDestination(address);
    2362                 :          28 :     {
    2363         [ +  - ]:          28 :         LOCK(cs_wallet);
    2364                 :             :         // If we want to delete receiving addresses, we should avoid calling EraseAddressData because it will delete the previously_spent value. Could instead just erase the label so it becomes a change address, and keep the data.
    2365                 :             :         // NOTE: This isn't a problem for sending addresses because they don't have any data that needs to be kept.
    2366                 :             :         // When adding new address data, it should be considered here whether to retain or delete it.
    2367   [ +  -  -  + ]:          28 :         if (IsMine(address)) {
    2368         [ #  # ]:           0 :             WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s", __func__, CLIENT_BUGREPORT);
    2369                 :             :             return false;
    2370                 :             :         }
    2371                 :             :         // Delete data rows associated with this address
    2372   [ +  -  -  + ]:          28 :         if (!batch.EraseAddressData(address)) {
    2373         [ #  # ]:           0 :             WalletLogPrintf("Error: cannot erase address book entry data");
    2374                 :             :             return false;
    2375                 :             :         }
    2376                 :             : 
    2377                 :             :         // Delete purpose entry
    2378   [ +  -  -  + ]:          28 :         if (!batch.ErasePurpose(dest)) {
    2379         [ #  # ]:           0 :             WalletLogPrintf("Error: cannot erase address book entry purpose");
    2380                 :             :             return false;
    2381                 :             :         }
    2382                 :             : 
    2383                 :             :         // Delete name entry
    2384   [ +  -  -  + ]:          28 :         if (!batch.EraseName(dest)) {
    2385         [ #  # ]:           0 :             WalletLogPrintf("Error: cannot erase address book entry name");
    2386                 :             :             return false;
    2387                 :             :         }
    2388                 :             : 
    2389                 :             :         // finally, remove it from the map
    2390         [ +  - ]:          28 :         m_address_book.erase(address);
    2391                 :           0 :     }
    2392                 :             : 
    2393                 :             :     // All good, signal changes
    2394         [ +  - ]:          28 :     NotifyAddressBookChanged(address, "", /*is_mine=*/false, AddressPurpose::SEND, CT_DELETED);
    2395                 :             :     return true;
    2396                 :          28 : }
    2397                 :             : 
    2398                 :         454 : size_t CWallet::KeypoolCountExternalKeys() const
    2399                 :             : {
    2400                 :         454 :     AssertLockHeld(cs_wallet);
    2401                 :             : 
    2402                 :         454 :     unsigned int count = 0;
    2403         [ +  + ]:        1885 :     for (auto spk_man : m_external_spk_managers) {
    2404                 :        1431 :         count += spk_man.second->GetKeyPoolSize();
    2405                 :             :     }
    2406                 :             : 
    2407                 :         454 :     return count;
    2408                 :             : }
    2409                 :             : 
    2410                 :        1547 : unsigned int CWallet::GetKeyPoolSize() const
    2411                 :             : {
    2412                 :        1547 :     AssertLockHeld(cs_wallet);
    2413                 :             : 
    2414                 :        1547 :     unsigned int count = 0;
    2415         [ +  + ]:       10637 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    2416         [ +  - ]:        9090 :         count += spk_man->GetKeyPoolSize();
    2417                 :             :     }
    2418                 :        1547 :     return count;
    2419                 :             : }
    2420                 :             : 
    2421                 :        1197 : bool CWallet::TopUpKeyPool(unsigned int kpSize)
    2422                 :             : {
    2423                 :        1197 :     LOCK(cs_wallet);
    2424                 :        1197 :     bool res = true;
    2425   [ +  -  +  + ]:        7829 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    2426         [ +  - ]:        6632 :         res &= spk_man->TopUp(kpSize);
    2427                 :             :     }
    2428         [ +  - ]:        1197 :     return res;
    2429                 :        1197 : }
    2430                 :             : 
    2431                 :       17303 : util::Result<CTxDestination> CWallet::GetNewDestination(const OutputType type, const std::string& label)
    2432                 :             : {
    2433                 :       17303 :     LOCK(cs_wallet);
    2434         [ +  - ]:       17303 :     auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
    2435         [ +  + ]:       17303 :     if (!spk_man) {
    2436   [ +  -  +  - ]:           6 :         return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
    2437                 :             :     }
    2438                 :             : 
    2439         [ +  - ]:       17301 :     auto op_dest = spk_man->GetNewDestination(type);
    2440         [ +  + ]:       17301 :     if (op_dest) {
    2441         [ +  - ]:       17296 :         SetAddressBook(*op_dest, label, AddressPurpose::RECEIVE);
    2442                 :             :     }
    2443                 :             : 
    2444                 :       17301 :     return op_dest;
    2445                 :       34604 : }
    2446                 :             : 
    2447                 :         343 : util::Result<CTxDestination> CWallet::GetNewChangeDestination(const OutputType type)
    2448                 :             : {
    2449                 :         343 :     LOCK(cs_wallet);
    2450                 :             : 
    2451         [ +  - ]:         343 :     ReserveDestination reservedest(this, type);
    2452         [ +  - ]:         343 :     auto op_dest = reservedest.GetReservedDestination(true);
    2453   [ +  +  +  - ]:         343 :     if (op_dest) reservedest.KeepDestination();
    2454                 :             : 
    2455                 :         343 :     return op_dest;
    2456         [ +  - ]:         686 : }
    2457                 :             : 
    2458                 :         922 : void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
    2459   [ +  +  +  + ]:      257333 :     for (auto& entry : mapWallet) {
    2460                 :      256411 :         CWalletTx& wtx = entry.second;
    2461         [ +  + ]:      256411 :         if (wtx.m_is_cache_empty) continue;
    2462   [ -  +  +  -  :         228 :         for (unsigned int i = 0; i < wtx.GetTx()->vout.size(); i++) {
                   +  + ]
    2463                 :          75 :             CTxDestination dst;
    2464   [ +  -  +  -  :         150 :             if (ExtractDestination(wtx.GetTx()->vout[i].scriptPubKey, dst) && destinations.contains(dst)) {
          +  +  +  +  +  
                +  -  - ]
    2465                 :           2 :                 wtx.MarkDirty();
    2466                 :           2 :                 break;
    2467                 :             :             }
    2468                 :          75 :         }
    2469                 :             :     }
    2470                 :         922 : }
    2471                 :             : 
    2472                 :         134 : void CWallet::ForEachAddrBookEntry(const ListAddrBookFunc& func) const
    2473                 :             : {
    2474                 :         134 :     AssertLockHeld(cs_wallet);
    2475         [ +  + ]:        1522 :     for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book) {
    2476                 :        1388 :         const auto& entry = item.second;
    2477         [ +  - ]:        2776 :         func(item.first, entry.GetLabel(), entry.IsChange(), entry.purpose);
    2478                 :             :     }
    2479                 :         134 : }
    2480                 :             : 
    2481                 :          24 : std::vector<CTxDestination> CWallet::ListAddrBookAddresses(const std::optional<AddrBookFilter>& _filter) const
    2482                 :             : {
    2483                 :          24 :     AssertLockHeld(cs_wallet);
    2484                 :          24 :     std::vector<CTxDestination> result;
    2485   [ +  -  +  - ]:          24 :     AddrBookFilter filter = _filter ? *_filter : AddrBookFilter();
    2486         [ +  - ]:          24 :     ForEachAddrBookEntry([&result, &filter](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
    2487                 :             :         // Filter by change
    2488   [ +  -  +  - ]:         209 :         if (filter.ignore_change && is_change) return;
    2489                 :             :         // Filter by label
    2490   [ +  -  +  + ]:         209 :         if (filter.m_op_label && *filter.m_op_label != label) return;
    2491                 :             :         // All good
    2492                 :          43 :         result.emplace_back(dest);
    2493                 :             :     });
    2494                 :          24 :     return result;
    2495                 :          24 : }
    2496                 :             : 
    2497                 :          42 : std::set<std::string> CWallet::ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const
    2498                 :             : {
    2499                 :          42 :     AssertLockHeld(cs_wallet);
    2500         [ +  - ]:          42 :     std::set<std::string> label_set;
    2501         [ +  - ]:          42 :     ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label,
    2502                 :             :                              bool _is_change, const std::optional<AddressPurpose>& _purpose) {
    2503         [ +  - ]:         497 :         if (_is_change) return;
    2504   [ +  +  +  - ]:         497 :         if (!purpose || purpose == _purpose) {
    2505                 :         482 :             label_set.insert(_label);
    2506                 :             :         }
    2507                 :             :     });
    2508                 :          42 :     return label_set;
    2509                 :           0 : }
    2510                 :             : 
    2511                 :        2272 : util::Result<CTxDestination> ReserveDestination::GetReservedDestination(bool internal)
    2512                 :             : {
    2513                 :        2272 :     m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
    2514         [ +  + ]:        2272 :     if (!m_spk_man) {
    2515                 :          24 :         return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
    2516                 :             :     }
    2517                 :             : 
    2518         [ +  - ]:        2260 :     if (nIndex == -1) {
    2519                 :        2260 :         int64_t index;
    2520                 :        2260 :         auto op_address = m_spk_man->GetReservedDestination(type, internal, index);
    2521         [ +  + ]:        2260 :         if (!op_address) return op_address;
    2522                 :        2256 :         nIndex = index;
    2523         [ +  - ]:        4512 :         address = *op_address;
    2524                 :        2260 :     }
    2525                 :        2256 :     return address;
    2526                 :             : }
    2527                 :             : 
    2528                 :        4075 : void ReserveDestination::KeepDestination()
    2529                 :             : {
    2530         [ +  + ]:        4075 :     if (nIndex != -1) {
    2531                 :        2149 :         m_spk_man->KeepDestination(nIndex, type);
    2532                 :             :     }
    2533                 :        4075 :     nIndex = -1;
    2534                 :        4075 :     address = CNoDestination();
    2535                 :        4075 : }
    2536                 :             : 
    2537                 :        4194 : void ReserveDestination::ReturnDestination()
    2538                 :             : {
    2539         [ +  + ]:        4194 :     if (nIndex != -1) {
    2540                 :         107 :         m_spk_man->ReturnDestination(nIndex, fInternal, address);
    2541                 :             :     }
    2542                 :        4194 :     nIndex = -1;
    2543                 :        4194 :     address = CNoDestination();
    2544                 :        4194 : }
    2545                 :             : 
    2546                 :           5 : util::Result<void> CWallet::DisplayAddress(const CTxDestination& dest)
    2547                 :             : {
    2548                 :           5 :     CScript scriptPubKey = GetScriptForDestination(dest);
    2549   [ +  -  +  - ]:           5 :     for (const auto& spk_man : GetScriptPubKeyMans(scriptPubKey)) {
    2550         [ +  - ]:           5 :         auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan *>(spk_man);
    2551         [ -  + ]:           5 :         if (signer_spk_man == nullptr) {
    2552                 :           0 :             continue;
    2553                 :             :         }
    2554         [ +  + ]:           5 :         auto signer{ExternalSignerScriptPubKeyMan::GetExternalSigner()};
    2555   [ -  +  -  -  :           4 :         if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
                   -  - ]
    2556         [ +  - ]:           4 :         return signer_spk_man->DisplayAddress(dest, *signer);
    2557                 :           5 :     }
    2558         [ #  # ]:           0 :     return util::Error{_("There is no ScriptPubKeyManager for this address")};
    2559                 :           4 : }
    2560                 :             : 
    2561                 :          86 : void CWallet::LoadLockedCoin(const COutPoint& coin, bool persistent)
    2562                 :             : {
    2563                 :          86 :     AssertLockHeld(cs_wallet);
    2564                 :          86 :     m_locked_coins.emplace(coin, persistent);
    2565                 :          86 : }
    2566                 :             : 
    2567                 :          83 : bool CWallet::LockCoin(const COutPoint& output, bool persist)
    2568                 :             : {
    2569                 :          83 :     AssertLockHeld(cs_wallet);
    2570                 :          83 :     LoadLockedCoin(output, persist);
    2571         [ +  + ]:          83 :     if (persist) {
    2572                 :           3 :         WalletBatch batch(GetDatabase());
    2573         [ +  - ]:           3 :         return batch.WriteLockedUTXO(output);
    2574                 :           3 :     }
    2575                 :             :     return true;
    2576                 :             : }
    2577                 :             : 
    2578                 :       12145 : bool CWallet::UnlockCoin(const COutPoint& output)
    2579                 :             : {
    2580                 :       12145 :     AssertLockHeld(cs_wallet);
    2581                 :       12145 :     auto locked_coin_it = m_locked_coins.find(output);
    2582         [ +  + ]:       12145 :     if (locked_coin_it != m_locked_coins.end()) {
    2583                 :          10 :         bool persisted = locked_coin_it->second;
    2584                 :          10 :         m_locked_coins.erase(locked_coin_it);
    2585         [ +  + ]:          10 :         if (persisted) {
    2586                 :           1 :             WalletBatch batch(GetDatabase());
    2587         [ +  - ]:           1 :             return batch.EraseLockedUTXO(output);
    2588                 :           1 :         }
    2589                 :             :     }
    2590                 :             :     return true;
    2591                 :             : }
    2592                 :             : 
    2593                 :           4 : bool CWallet::UnlockAllCoins()
    2594                 :             : {
    2595                 :           4 :     AssertLockHeld(cs_wallet);
    2596                 :           4 :     bool success = true;
    2597                 :           4 :     WalletBatch batch(GetDatabase());
    2598   [ -  +  +  + ]:          56 :     for (const auto& [coin, persistent] : m_locked_coins) {
    2599   [ -  +  -  -  :          52 :         if (persistent) success = success && batch.EraseLockedUTXO(coin);
             -  -  -  - ]
    2600                 :             :     }
    2601                 :           4 :     m_locked_coins.clear();
    2602                 :           4 :     return success;
    2603                 :           4 : }
    2604                 :             : 
    2605                 :      449308 : bool CWallet::IsLockedCoin(const COutPoint& output) const
    2606                 :             : {
    2607                 :      449308 :     AssertLockHeld(cs_wallet);
    2608                 :      449308 :     return m_locked_coins.contains(output);
    2609                 :             : }
    2610                 :             : 
    2611                 :          11 : void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
    2612                 :             : {
    2613                 :          11 :     AssertLockHeld(cs_wallet);
    2614         [ +  + ]:          18 :     for (const auto& [coin, _] : m_locked_coins) {
    2615                 :           7 :         vOutpts.push_back(coin);
    2616                 :             :     }
    2617                 :          11 : }
    2618                 :             : 
    2619                 :             : /**
    2620                 :             :  * Compute smart timestamp for a transaction being added to the wallet.
    2621                 :             :  *
    2622                 :             :  * Logic:
    2623                 :             :  * - If sending a transaction, assign its timestamp to the current time.
    2624                 :             :  * - If receiving a transaction outside a block, assign its timestamp to the
    2625                 :             :  *   current time.
    2626                 :             :  * - If receiving a transaction during a rescanning process, assign all its
    2627                 :             :  *   (not already known) transactions' timestamps to the block time.
    2628                 :             :  * - If receiving a block with a future timestamp, assign all its (not already
    2629                 :             :  *   known) transactions' timestamps to the current time.
    2630                 :             :  * - If receiving a block with a past timestamp, before the most recent known
    2631                 :             :  *   transaction (that we care about), assign all its (not already known)
    2632                 :             :  *   transactions' timestamps to the same timestamp as that most-recent-known
    2633                 :             :  *   transaction.
    2634                 :             :  * - If receiving a block with a past timestamp, but after the most recent known
    2635                 :             :  *   transaction, assign all its (not already known) transactions' timestamps to
    2636                 :             :  *   the block time.
    2637                 :             :  *
    2638                 :             :  * For more information see CWalletTx::nTimeSmart,
    2639                 :             :  * https://bitcointalk.org/?topic=54527, or
    2640                 :             :  * https://github.com/bitcoin/bitcoin/pull/1393.
    2641                 :             :  */
    2642                 :       19506 : unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
    2643                 :             : {
    2644                 :       19506 :     std::optional<uint256> block_hash;
    2645         [ +  + ]:       19506 :     if (auto* conf = wtx.state<TxStateConfirmed>()) {
    2646                 :       15696 :         block_hash = conf->confirmed_block_hash;
    2647         [ -  + ]:        3810 :     } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
    2648                 :           0 :         block_hash = conf->conflicting_block_hash;
    2649                 :             :     }
    2650                 :             : 
    2651                 :       19506 :     unsigned int nTimeSmart = wtx.nTimeReceived;
    2652         [ +  + ]:       19506 :     if (block_hash) {
    2653                 :       15696 :         int64_t blocktime;
    2654                 :       15696 :         int64_t block_max_time;
    2655         [ +  - ]:       15696 :         if (chain().findBlock(*block_hash, FoundBlock().time(blocktime).maxTime(block_max_time))) {
    2656         [ +  + ]:       15696 :             if (rescanning_old_block) {
    2657                 :        5837 :                 nTimeSmart = block_max_time;
    2658                 :             :             } else {
    2659                 :        9859 :                 int64_t latestNow = wtx.nTimeReceived;
    2660                 :        9859 :                 int64_t latestEntry = 0;
    2661                 :             : 
    2662                 :             :                 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
    2663                 :        9859 :                 int64_t latestTolerated = latestNow + 300;
    2664                 :        9859 :                 const TxItems& txOrdered = wtxOrdered;
    2665         [ +  + ]:       19720 :                 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
    2666                 :       19599 :                     CWalletTx* const pwtx = it->second;
    2667         [ +  + ]:       19599 :                     if (pwtx == &wtx) {
    2668                 :        9859 :                         continue;
    2669                 :             :                     }
    2670                 :        9740 :                     int64_t nSmartTime;
    2671                 :        9740 :                     nSmartTime = pwtx->nTimeSmart;
    2672         [ -  + ]:        9740 :                     if (!nSmartTime) {
    2673                 :           0 :                         nSmartTime = pwtx->nTimeReceived;
    2674                 :             :                     }
    2675         [ +  + ]:        9740 :                     if (nSmartTime <= latestTolerated) {
    2676                 :        9738 :                         latestEntry = nSmartTime;
    2677         [ +  + ]:        9738 :                         if (nSmartTime > latestNow) {
    2678                 :           5 :                             latestNow = nSmartTime;
    2679                 :             :                         }
    2680                 :             :                         break;
    2681                 :             :                     }
    2682                 :             :                 }
    2683                 :             : 
    2684   [ +  +  +  + ]:       10724 :                 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
    2685                 :             :             }
    2686                 :             :         } else {
    2687   [ #  #  #  #  :           0 :             WalletLogPrintf("%s: found %s in block %s not in index", __func__, wtx.GetHash().ToString(), block_hash->ToString());
                   #  # ]
    2688                 :             :         }
    2689                 :             :     }
    2690                 :       19506 :     return nTimeSmart;
    2691                 :             : }
    2692                 :             : 
    2693                 :          46 : bool CWallet::SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used)
    2694                 :             : {
    2695         [ +  - ]:          46 :     if (std::get_if<CNoDestination>(&dest))
    2696                 :             :         return false;
    2697                 :             : 
    2698         [ -  + ]:          46 :     if (!used) {
    2699         [ #  # ]:           0 :         if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false;
    2700                 :           0 :         return batch.WriteAddressPreviouslySpent(dest, false);
    2701                 :             :     }
    2702                 :             : 
    2703                 :          46 :     LoadAddressPreviouslySpent(dest);
    2704                 :          46 :     return batch.WriteAddressPreviouslySpent(dest, true);
    2705                 :             : }
    2706                 :             : 
    2707                 :          54 : void CWallet::LoadAddressPreviouslySpent(const CTxDestination& dest)
    2708                 :             : {
    2709                 :          54 :     m_address_book[dest].previously_spent = true;
    2710                 :          54 : }
    2711                 :             : 
    2712                 :           3 : void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request)
    2713                 :             : {
    2714                 :           3 :     m_address_book[dest].receive_requests[id] = request;
    2715                 :           3 : }
    2716                 :             : 
    2717                 :        1711 : bool CWallet::IsAddressPreviouslySpent(const CTxDestination& dest) const
    2718                 :             : {
    2719         [ +  + ]:        1711 :     if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent;
    2720                 :             :     return false;
    2721                 :             : }
    2722                 :             : 
    2723                 :           2 : std::vector<std::string> CWallet::GetAddressReceiveRequests() const
    2724                 :             : {
    2725                 :           2 :     std::vector<std::string> values;
    2726         [ +  + ]:           5 :     for (const auto& [dest, entry] : m_address_book) {
    2727   [ +  -  +  + ]:           6 :         for (const auto& [id, request] : entry.receive_requests) {
    2728         [ +  - ]:           3 :             values.emplace_back(request);
    2729                 :             :         }
    2730                 :             :     }
    2731                 :           2 :     return values;
    2732                 :           0 : }
    2733                 :             : 
    2734                 :           4 : bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
    2735                 :             : {
    2736         [ +  - ]:           4 :     if (!batch.WriteAddressReceiveRequest(dest, id, value)) return false;
    2737                 :           4 :     m_address_book[dest].receive_requests[id] = value;
    2738                 :           4 :     return true;
    2739                 :             : }
    2740                 :             : 
    2741                 :           1 : bool CWallet::EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id)
    2742                 :             : {
    2743         [ +  - ]:           1 :     if (!batch.EraseAddressReceiveRequest(dest, id)) return false;
    2744                 :           1 :     m_address_book[dest].receive_requests.erase(id);
    2745                 :           1 :     return true;
    2746                 :             : }
    2747                 :             : 
    2748                 :        1679 : util::Result<fs::path> GetWalletPath(const std::string& name)
    2749                 :             : {
    2750                 :        1679 :     const fs::path name_path = fs::PathFromString(name);
    2751                 :             : 
    2752                 :             :     // 'name' must be a normalized path, i.e. no . or .. except at the root
    2753   [ +  -  +  + ]:        5037 :     if (name_path != name_path.lexically_normal()) {
    2754   [ +  -  +  - ]:          48 :         return util::Error{Untranslated("Wallet name given as a path must be normalized")};
    2755                 :             :     }
    2756                 :             : 
    2757                 :             :     // 'name' cannot begin with ./ or ../
    2758   [ +  +  +  -  :        7075 :     if (!name_path.empty() && (*name_path.begin() == fs::PathFromString(".") || *name_path.begin() == fs::PathFromString(".."))) {
          +  -  +  +  +  
          +  +  -  +  -  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  -  -  -  
                -  -  - ]
    2759   [ +  -  +  - ]:          18 :         return util::Error{Untranslated("Wallet name given as a relative path cannot begin with ./ or ../, for wallets not in the walletdir, please use an absolute path.")};
    2760                 :             :     }
    2761                 :             : 
    2762                 :             :     // Disallow path at root
    2763   [ +  +  +  -  :        1689 :     if (name_path.has_root_path() && name_path.root_path() == name_path) {
             +  +  +  + ]
    2764   [ +  -  +  - ]:           6 :         return util::Error{Untranslated("Wallet name cannot be the root path")};
    2765                 :             :     }
    2766                 :             : 
    2767                 :             :     // Do some checking on wallet path. It should be either a:
    2768                 :             :     //
    2769                 :             :     // 1. Path where a directory can be created.
    2770                 :             :     // 2. Path to an existing directory.
    2771                 :             :     // 3. Path to a symlink to a directory.
    2772                 :             :     // 4. For backwards compatibility, the name of a data file in -walletdir.
    2773   [ +  -  +  - ]:        1655 :     const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), name_path);
    2774         [ +  - ]:        1655 :     fs::file_type path_type = fs::symlink_status(wallet_path).type();
    2775   [ +  +  +  +  :        1673 :     if (!(path_type == fs::file_type::not_found || path_type == fs::file_type::directory ||
             +  +  +  + ]
    2776   [ +  -  +  + ]:          16 :           (path_type == fs::file_type::symlink && fs::is_directory(wallet_path)) ||
    2777   [ +  -  -  + ]:           4 :           (path_type == fs::file_type::regular && name_path.filename() == name_path))) {
    2778   [ +  -  +  - ]:           8 :         return util::Error{Untranslated(strprintf(
    2779                 :             :               "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
    2780                 :             :               "database/log.?????????? files can be stored, a location where such a directory could be created, "
    2781                 :             :               "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
    2782   [ +  -  +  - ]:          20 :               name, fs::quoted(fs::PathToString(GetWalletDir()))))};
    2783                 :             :     }
    2784         [ +  - ]:        3302 :     return wallet_path;
    2785                 :        3334 : }
    2786                 :             : 
    2787                 :        1597 : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
    2788                 :             : {
    2789                 :        1597 :     const auto& wallet_path = GetWalletPath(name);
    2790         [ +  + ]:        1597 :     if (!wallet_path) {
    2791         [ +  - ]:          28 :         error_string = util::ErrorString(wallet_path);
    2792                 :          28 :         status = DatabaseStatus::FAILED_BAD_PATH;
    2793                 :          28 :         return nullptr;
    2794                 :             :     }
    2795         [ +  - ]:        1569 :     return MakeDatabase(*wallet_path, options, status, error_string);
    2796                 :        1597 : }
    2797                 :             : 
    2798                 :        1140 : bool CWallet::LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings)
    2799                 :             : {
    2800                 :        1140 :     interfaces::Chain* chain = context.chain;
    2801                 :        1140 :     const ArgsManager& args = *Assert(context.args);
    2802                 :             : 
    2803   [ +  -  +  -  :        1140 :     if (!args.GetArg("-addresstype", "").empty()) {
                   +  + ]
    2804   [ +  -  +  -  :         291 :         std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-addresstype", ""));
                   +  - ]
    2805         [ -  + ]:          97 :         if (!parsed) {
    2806   [ #  #  #  #  :           0 :             error = strprintf(_("Unknown address type '%s'"), args.GetArg("-addresstype", ""));
                   #  # ]
    2807                 :           0 :             return false;
    2808                 :             :         }
    2809                 :          97 :         wallet->m_default_address_type = parsed.value();
    2810                 :             :     }
    2811                 :             : 
    2812   [ +  -  +  -  :        1140 :     if (!args.GetArg("-changetype", "").empty()) {
                   +  + ]
    2813   [ +  -  +  -  :          18 :         std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-changetype", ""));
                   +  - ]
    2814         [ -  + ]:           6 :         if (!parsed) {
    2815   [ #  #  #  #  :           0 :             error = strprintf(_("Unknown change type '%s'"), args.GetArg("-changetype", ""));
                   #  # ]
    2816                 :           0 :             return false;
    2817                 :             :         }
    2818                 :           6 :         wallet->m_default_change_type = parsed.value();
    2819                 :             :     }
    2820                 :             : 
    2821   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-mintxfee")}) {
    2822         [ +  - ]:          18 :         std::optional<CAmount> min_tx_fee = ParseMoney(*arg);
    2823         [ -  + ]:          18 :         if (!min_tx_fee) {
    2824   [ #  #  #  # ]:           0 :             error = AmountErrMsg("mintxfee", *arg);
    2825                 :           0 :             return false;
    2826         [ -  + ]:          18 :         } else if (min_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
    2827   [ #  #  #  #  :           0 :             warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
                   #  # ]
    2828   [ #  #  #  # ]:           0 :                                _("This is the minimum transaction fee you pay on every transaction."));
    2829                 :             :         }
    2830                 :             : 
    2831                 :          18 :         wallet->m_min_fee = CFeeRate{min_tx_fee.value()};
    2832                 :           0 :     }
    2833                 :             : 
    2834   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-maxapsfee")}) {
    2835         [ -  + ]:           2 :         const std::string& max_aps_fee_str{*arg};
    2836         [ -  + ]:           2 :         if (max_aps_fee_str == "-1") {
    2837                 :           0 :             wallet->m_max_aps_fee = -1;
    2838   [ +  -  +  - ]:           2 :         } else if (std::optional<CAmount> max_aps_fee = ParseMoney(max_aps_fee_str)) {
    2839         [ -  + ]:           2 :             if (max_aps_fee.value() > HIGH_APS_FEE) {
    2840   [ #  #  #  #  :           0 :                 warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
                   #  # ]
    2841   [ #  #  #  # ]:           0 :                                   _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
    2842                 :             :             }
    2843                 :           2 :             wallet->m_max_aps_fee = max_aps_fee.value();
    2844                 :             :         } else {
    2845   [ #  #  #  # ]:           0 :             error = AmountErrMsg("maxapsfee", max_aps_fee_str);
    2846                 :           0 :             return false;
    2847                 :             :         }
    2848                 :           0 :     }
    2849                 :             : 
    2850   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-fallbackfee")}) {
    2851         [ +  - ]:        1116 :         std::optional<CAmount> fallback_fee = ParseMoney(*arg);
    2852         [ -  + ]:        1116 :         if (!fallback_fee) {
    2853         [ #  # ]:           0 :             error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-fallbackfee", *arg);
    2854                 :           0 :             return false;
    2855         [ +  + ]:        1116 :         } else if (fallback_fee.value() > HIGH_TX_FEE_PER_KB) {
    2856   [ +  -  +  -  :           6 :             warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
                   +  - ]
    2857   [ +  -  +  - ]:           2 :                                _("This is the transaction fee you may pay when fee estimates are not available."));
    2858                 :             :         }
    2859                 :        1116 :         wallet->m_fallback_fee = CFeeRate{fallback_fee.value()};
    2860                 :           0 :     }
    2861                 :             : 
    2862                 :             :     // Disable fallback fee in case value was set to 0, enable if non-null value
    2863                 :        1140 :     wallet->m_allow_fallback_fee = wallet->m_fallback_fee.GetFeePerK() != 0;
    2864                 :             : 
    2865   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-discardfee")}) {
    2866         [ +  - ]:           6 :         std::optional<CAmount> discard_fee = ParseMoney(*arg);
    2867         [ -  + ]:           6 :         if (!discard_fee) {
    2868         [ #  # ]:           0 :             error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-discardfee", *arg);
    2869                 :           0 :             return false;
    2870         [ +  + ]:           6 :         } else if (discard_fee.value() > HIGH_TX_FEE_PER_KB) {
    2871   [ +  -  +  -  :          24 :             warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
                   +  - ]
    2872   [ +  -  +  - ]:           8 :                                _("This is the transaction fee you may discard if change is smaller than dust at this level"));
    2873                 :             :         }
    2874                 :           6 :         wallet->m_discard_rate = CFeeRate{discard_fee.value()};
    2875                 :           0 :     }
    2876                 :             : 
    2877   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-maxtxfee")}) {
    2878         [ +  - ]:           8 :         std::optional<CAmount> max_tx_fee = ParseMoney(*arg);
    2879         [ -  + ]:           8 :         if (!max_tx_fee) {
    2880   [ #  #  #  # ]:           0 :             error = AmountErrMsg("maxtxfee", *arg);
    2881                 :           0 :             return false;
    2882         [ +  + ]:           8 :         } else if (max_tx_fee.value() > HIGH_MAX_TX_FEE) {
    2883         [ +  - ]:           6 :             warnings.push_back(strprintf(_("%s is set very high! Fees this large could be paid on a single transaction."), "-maxtxfee"));
    2884                 :             :         }
    2885   [ +  -  +  - ]:           8 :         const CFeeRate max_txfee{max_tx_fee.value(), 1000};
    2886   [ +  -  +  -  :           8 :         if (chain && max_txfee < chain->relayMinFee()) {
                   +  + ]
    2887                 :             :             // Wallet prevents creating transactions with fee rates lower than minrelaytxfee.
    2888                 :             :             // Also the wallet prevents creating transactions with base fee above maxtxfee.
    2889                 :             :             // Warn when a 1kvb transaction, with a base fee set to maxtxfee, has a fee rate less than minrelaytxfee.
    2890                 :             :             // It is likely that some transactions with fee rates greater than or equal to the minrelaytxfee will exceed maxtxfee.
    2891                 :             :             // In such cases, the wallet won't be able to create transactions. Therefore, warn the user.
    2892         [ +  - ]:          12 :             warnings.push_back(strprintf(_("Invalid amount for %s=<amount>: '%s' conflicts with the minimum relay transaction feerate %s. Please set a higher %s or lower %s"),
    2893   [ +  -  +  -  :           8 :                                          "-maxtxfee", max_txfee.ToString(), chain->relayMinFee().ToString(), "-maxtxfee", "-minrelaytxfee"));
                   +  - ]
    2894                 :             :         }
    2895                 :             : 
    2896         [ +  - ]:           8 :         wallet->m_max_tx_fee = max_tx_fee.value();
    2897                 :           0 :     }
    2898                 :             : 
    2899   [ +  -  +  + ]:        2280 :     if (const auto arg{args.GetArg("-maxfeerate")}) {
    2900         [ +  - ]:          19 :         std::optional<CAmount> max_tx_fee_rate = ParseMoney(*arg);
    2901         [ -  + ]:          19 :         if (!max_tx_fee_rate) {
    2902   [ #  #  #  # ]:           0 :             error = AmountErrMsg("maxfeerate", *arg);
    2903                 :           0 :             return false;
    2904                 :             :         }
    2905   [ +  -  +  -  :          19 :         if (chain && CFeeRate(*max_tx_fee_rate) < chain->relayMinFee()) {
                   +  + ]
    2906         [ +  - ]:           2 :             error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
    2907   [ +  -  +  - ]:           2 :                               "-maxfeerate", *arg, chain->relayMinFee().ToString());
    2908                 :           1 :             return false;
    2909                 :             :         }
    2910         [ -  + ]:          18 :         if (CFeeRate(*max_tx_fee_rate) > HIGH_MAX_TX_FEERATE) {
    2911         [ #  # ]:           0 :             warnings.push_back(strprintf(_("%s is set very high! Fee rate this large could be paid on a single transaction."), "-maxfeerate"));
    2912                 :             :         }
    2913                 :             : 
    2914                 :          18 :         wallet->m_max_tx_fee_rate = CFeeRate(*max_tx_fee_rate);
    2915                 :           1 :     }
    2916                 :             : 
    2917   [ +  -  -  + ]:        2278 :     if (const auto arg{args.GetArg("-consolidatefeerate")}) {
    2918   [ #  #  #  # ]:           0 :         if (std::optional<CAmount> consolidate_feerate = ParseMoney(*arg)) {
    2919                 :           0 :             wallet->m_consolidate_feerate = CFeeRate(*consolidate_feerate);
    2920                 :             :         } else {
    2921   [ #  #  #  # ]:           0 :             error = AmountErrMsg("consolidatefeerate", *arg);
    2922                 :           0 :             return false;
    2923                 :             :         }
    2924                 :           0 :     }
    2925                 :             : 
    2926   [ +  +  +  + ]:        1139 :     if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
    2927   [ +  -  +  -  :          24 :         warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
                   +  - ]
    2928         [ +  - ]:           8 :                            _("The wallet will avoid paying less than the minimum relay fee."));
    2929                 :             :     }
    2930                 :             : 
    2931                 :        2278 :     wallet->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
    2932         [ +  - ]:        1139 :     wallet->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
    2933                 :        1139 :     wallet->m_signal_rbf = DEFAULT_WALLET_RBF;
    2934   [ +  -  +  + ]:        2278 :     if (auto value{args.GetBoolArg("-walletrbf")}) {
    2935         [ +  - ]:           2 :         warnings.push_back(_("-walletrbf is deprecated and will be fully removed in the next release."));
    2936                 :           2 :         wallet->m_signal_rbf = *value;
    2937                 :             :     }
    2938                 :             : 
    2939         [ +  - ]:        3417 :     wallet->m_keypool_size = std::max(args.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{1});
    2940   [ +  -  +  - ]:        1139 :     wallet->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
    2941         [ +  - ]:        1139 :     wallet->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
    2942                 :             : 
    2943                 :        1139 :     return true;
    2944                 :             : }
    2945                 :             : 
    2946                 :         696 : std::shared_ptr<CWallet> CWallet::CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bool born_encrypted, bilingual_str& error, std::vector<bilingual_str>& warnings)
    2947                 :             : {
    2948                 :         696 :     interfaces::Chain* chain = context.chain;
    2949                 :         696 :     const std::string& walletFile = database->Filename();
    2950                 :             : 
    2951                 :         696 :     const auto start{SteadyClock::now()};
    2952                 :             :     // TODO: Can't use std::make_shared because we need a custom deleter but
    2953                 :             :     // should be possible to use std::allocate_shared.
    2954   [ +  -  +  -  :        1392 :     std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
             +  -  -  - ]
    2955                 :             : 
    2956   [ +  -  +  -  :        2088 :     if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
             +  -  +  + ]
    2957                 :           1 :         return nullptr;
    2958                 :             :     }
    2959                 :             : 
    2960                 :             :     // Initialize version key.
    2961                 :         695 :     {
    2962         [ +  - ]:         695 :         WalletBatch batch(walletInstance->GetDatabase());
    2963   [ +  -  -  + ]:         695 :         if(!batch.WriteLastOpenedVersion()) {
    2964         [ #  # ]:           0 :             error = strprintf(_("Error creating %s: Could not write version metadata."), walletFile);
    2965                 :           0 :             return nullptr;
    2966                 :             :         }
    2967   [ +  -  -  + ]:         695 :         if(!batch.WriteLastOpenedFeatures()) {
    2968         [ #  # ]:           0 :             error = strprintf(_("Error creating %s: Could not write features metadata."), walletFile);
    2969                 :           0 :             return nullptr;
    2970                 :             :         }
    2971                 :           0 :     }
    2972                 :         695 :     {
    2973         [ +  - ]:         695 :         LOCK(walletInstance->cs_wallet);
    2974                 :             : 
    2975                 :             :         // Init with passed flags.
    2976                 :             :         // Always set the cache upgrade flag as this feature is supported from the beginning.
    2977         [ +  - ]:         695 :         walletInstance->InitWalletFlags(wallet_creation_flags | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
    2978                 :             : 
    2979                 :             :         // Only descriptor wallets can be created
    2980   [ +  -  -  + ]:         695 :         assert(walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    2981                 :             : 
    2982                 :             :         // Born encrypted wallets will have their keys generated later
    2983         [ +  + ]:         695 :         if (!born_encrypted) {
    2984         [ +  + ]:         678 :             walletInstance->SetupWalletGeneration();
    2985                 :             :         }
    2986                 :             : 
    2987         [ +  + ]:         692 :         if (chain) {
    2988         [ +  - ]:         661 :             std::optional<int> tip_height = chain->getHeight();
    2989         [ +  - ]:         661 :             if (tip_height) {
    2990   [ +  -  +  - ]:         661 :                 walletInstance->SetLastBlockProcessed(*tip_height, chain->getBlockHash(*tip_height));
    2991                 :             :             }
    2992                 :             :         }
    2993                 :           3 :     }
    2994                 :             : 
    2995         [ +  - ]:         692 :     walletInstance->WalletLogPrintf("Wallet completed creation in %15dms", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
    2996                 :             : 
    2997                 :             :     // Try to top up keypool. No-op if the wallet is locked.
    2998         [ +  - ]:         692 :     walletInstance->TopUpKeyPool();
    2999                 :             : 
    3000   [ +  +  +  -  :         692 :     if (chain && !AttachChain(walletInstance, *chain, /*rescan_required=*/false, error, warnings)) {
                   -  + ]
    3001         [ #  # ]:           0 :         walletInstance->DisconnectChainNotifications();
    3002                 :           0 :         return nullptr;
    3003                 :             :     }
    3004                 :             : 
    3005                 :         692 :     return walletInstance;
    3006                 :         696 : }
    3007                 :             : 
    3008                 :         444 : std::shared_ptr<CWallet> CWallet::LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings)
    3009                 :             : {
    3010                 :         444 :     interfaces::Chain* chain = context.chain;
    3011                 :         444 :     const std::string& walletFile = database->Filename();
    3012                 :             : 
    3013                 :         444 :     const auto start{SteadyClock::now()};
    3014   [ +  -  +  -  :         888 :     std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
             +  -  -  - ]
    3015                 :             : 
    3016   [ +  -  +  -  :        1332 :     if (!LoadWalletArgs(walletInstance, context, error, warnings)) {
             +  -  -  + ]
    3017                 :           0 :         return nullptr;
    3018                 :             :     }
    3019                 :             : 
    3020                 :             :     // Load wallet
    3021         [ +  - ]:         444 :     auto nLoadWalletRet = walletInstance->PopulateWalletFromDB(error, warnings);
    3022                 :         444 :     bool rescan_required = nLoadWalletRet == DBErrors::NEED_RESCAN;
    3023   [ +  +  +  - ]:         444 :     if (nLoadWalletRet != DBErrors::LOAD_OK && nLoadWalletRet != DBErrors::NONCRITICAL_ERROR && !rescan_required) {
    3024                 :           2 :         return nullptr;
    3025                 :             :     }
    3026                 :             : 
    3027   [ +  -  +  + ]:         442 :     if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
    3028   [ +  -  +  + ]:         180 :         for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
    3029   [ +  -  -  + ]:          72 :             if (spk_man->HavePrivateKeys()) {
    3030         [ #  # ]:           0 :                 warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
    3031                 :           0 :                 break;
    3032                 :             :             }
    3033                 :             :         }
    3034                 :             :     }
    3035                 :             : 
    3036         [ +  - ]:         442 :     walletInstance->WalletLogPrintf("Wallet completed loading in %15dms", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
    3037                 :             : 
    3038                 :             :     // Try to top up keypool. No-op if the wallet is locked.
    3039         [ +  - ]:         442 :     walletInstance->TopUpKeyPool();
    3040                 :             : 
    3041   [ +  +  +  -  :         442 :     if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
                   +  + ]
    3042         [ +  - ]:          10 :         walletInstance->DisconnectChainNotifications();
    3043                 :          10 :         return nullptr;
    3044                 :             :     }
    3045                 :             : 
    3046   [ +  -  +  - ]:        1296 :     WITH_LOCK(walletInstance->cs_wallet, walletInstance->LogStats());
    3047                 :             : 
    3048                 :         432 :     return walletInstance;
    3049                 :         444 : }
    3050                 :             : 
    3051                 :             : 
    3052                 :        1051 : bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings)
    3053                 :             : {
    3054                 :        1051 :     LOCK(walletInstance->cs_wallet);
    3055                 :             :     // allow setting the chain if it hasn't been set already but prevent changing it
    3056   [ +  -  -  + ]:        1051 :     assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
    3057         [ +  - ]:        1051 :     walletInstance->m_chain = &chain;
    3058                 :             : 
    3059                 :             :     // Unless allowed, ensure wallet files are not reused across chains:
    3060   [ +  -  +  -  :        1051 :     if (!gArgs.GetBoolArg("-walletcrosschain", DEFAULT_WALLETCROSSCHAIN)) {
                   +  - ]
    3061         [ +  - ]:        1051 :         WalletBatch batch(walletInstance->GetDatabase());
    3062                 :        1051 :         CBlockLocator locator;
    3063   [ +  -  +  +  :        2100 :         if (batch.ReadBestBlock(locator) && locator.vHave.size() > 0 && chain.getHeight()) {
          +  -  +  -  +  
                      + ]
    3064                 :             :             // Wallet is assumed to be from another chain, if genesis block in the active
    3065                 :             :             // chain differs from the genesis block known to the wallet.
    3066         [ +  - ]:        2094 :             if (chain.getBlockHash(0) != locator.vHave.back()) {
    3067   [ +  -  +  - ]:           2 :                 error = Untranslated("Wallet files should not be reused across chains. Restart bitcoind with -walletcrosschain to override.");
    3068                 :           1 :                 return false;
    3069                 :             :             }
    3070                 :             :         }
    3071                 :        2102 :     }
    3072                 :             : 
    3073                 :             :     // Register wallet with validationinterface. It's done before rescan to avoid
    3074                 :             :     // missing block connections during the rescan.
    3075                 :             :     // Because of the wallet lock being held, block connection notifications are going to
    3076                 :             :     // be pending on the validation-side until lock release. Blocks that are connected while the
    3077                 :             :     // rescan is ongoing will not be processed in the rescan but with the block connected notifications,
    3078                 :             :     // so the wallet will only be completeley synced after the notifications delivery.
    3079   [ +  -  -  + ]:        1050 :     walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    3080                 :             : 
    3081                 :             :     // If rescan_required = true, rescan_height remains equal to 0
    3082                 :        1050 :     int rescan_height = 0;
    3083         [ +  - ]:        1050 :     if (!rescan_required)
    3084                 :             :     {
    3085         [ +  - ]:        1050 :         WalletBatch batch(walletInstance->GetDatabase());
    3086                 :        1050 :         CBlockLocator locator;
    3087   [ +  -  +  + ]:        1050 :         if (batch.ReadBestBlock(locator)) {
    3088   [ +  -  +  + ]:        1048 :             if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
    3089                 :        1043 :                 rescan_height = *fork_height;
    3090                 :             :             }
    3091                 :             :         }
    3092                 :        2100 :     }
    3093                 :             : 
    3094         [ +  - ]:        1050 :     const std::optional<int> tip_height = chain.getHeight();
    3095         [ +  + ]:        1050 :     if (tip_height) {
    3096   [ +  -  +  - ]:        1045 :         walletInstance->SetLastBlockProcessedInMem(*tip_height, chain.getBlockHash(*tip_height));
    3097                 :             :     } else {
    3098         [ +  - ]:           5 :         walletInstance->SetLastBlockProcessedInMem(-1, uint256());
    3099                 :             :     }
    3100                 :             : 
    3101   [ +  +  +  + ]:        1050 :     if (tip_height && *tip_height != rescan_height)
    3102                 :             :     {
    3103                 :             :         // No need to read and scan block if block was created before
    3104                 :             :         // our wallet birthday (as adjusted for block time variability)
    3105         [ +  - ]:          75 :         std::optional<int64_t> time_first_key = walletInstance->m_birth_time.load();
    3106         [ +  - ]:          75 :         if (time_first_key) {
    3107         [ +  - ]:          75 :             FoundBlock found = FoundBlock().height(rescan_height);
    3108         [ +  - ]:          75 :             chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
    3109         [ -  + ]:          75 :             if (!found.found) {
    3110                 :             :                 // We were unable to find a block that had a time more recent than our earliest timestamp
    3111                 :             :                 // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
    3112                 :             :                 // current chain tip. Skip rescanning in this case.
    3113                 :           0 :                 rescan_height = *tip_height;
    3114                 :             :             }
    3115                 :             :         }
    3116                 :             : 
    3117                 :             :         // Technically we could execute the code below in any case, but performing the
    3118                 :             :         // `while` loop below can make startup very slow, so only check blocks on disk
    3119                 :             :         // if necessary.
    3120   [ +  -  +  +  :          75 :         if (chain.havePruned() || chain.hasAssumedValidChain()) {
             +  -  +  + ]
    3121                 :          14 :             int block_height = *tip_height;
    3122   [ +  -  +  -  :        2658 :             while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
             +  +  +  + ]
    3123                 :        2644 :                 --block_height;
    3124                 :             :             }
    3125                 :             : 
    3126         [ +  + ]:          14 :             if (rescan_height != block_height) {
    3127                 :             :                 // We can't rescan beyond blocks we don't have data for, stop and throw an error.
    3128                 :             :                 // This might happen if a user uses an old wallet within a pruned node
    3129                 :             :                 // or if they ran -disablewallet for a longer time, then decided to re-enable
    3130                 :             :                 // Exit early and print an error.
    3131                 :             :                 // It also may happen if an assumed-valid chain is in use and therefore not
    3132                 :             :                 // all block data is available.
    3133                 :             :                 // If a block is pruned after this check, we will load the wallet,
    3134                 :             :                 // but fail the rescan with a generic error.
    3135                 :             : 
    3136   [ +  -  +  +  :           9 :                 error = chain.havePruned() ?
                   +  - ]
    3137         [ +  - ]:           4 :                      _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of a pruned node)") :
    3138                 :             :                      strprintf(_(
    3139                 :             :                         "Error loading wallet. Wallet requires blocks to be downloaded, "
    3140                 :             :                         "and software does not currently support loading wallets while "
    3141                 :             :                         "blocks are being downloaded out of order when using assumeutxo "
    3142                 :             :                         "snapshots. Wallet should be able to load successfully after "
    3143                 :           9 :                         "node sync reaches height %s"), block_height);
    3144                 :           9 :                 return false;
    3145                 :             :             }
    3146                 :             :         }
    3147                 :             : 
    3148   [ +  -  +  - ]:          66 :         chain.initMessage(_("Rescanning…"));
    3149         [ +  - ]:          66 :         walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...", *tip_height - rescan_height, rescan_height);
    3150                 :             : 
    3151                 :          66 :         {
    3152         [ +  - ]:          66 :             WalletRescanReserver reserver(*walletInstance);
    3153   [ +  -  -  + ]:          66 :             if (!reserver.reserve()) {
    3154         [ #  # ]:           0 :                 error = _("Failed to acquire rescan reserver during wallet initialization");
    3155                 :           0 :                 return false;
    3156                 :             :             }
    3157   [ +  -  +  -  :          66 :             ScanResult scan_res = walletInstance->Scanner().Scan(chain.getBlockHash(rescan_height), rescan_height, /*max_height=*/{}, reserver, /*save_progress=*/true);
                   +  - ]
    3158         [ -  + ]:          66 :             if (ScanResult::SUCCESS != scan_res.status) {
    3159         [ #  # ]:           0 :                 error = _("Failed to rescan the wallet during initialization");
    3160                 :           0 :                 return false;
    3161                 :             :             }
    3162                 :             :             // Set and update the best block record
    3163                 :             :             // Set last block scanned as the last block processed as it may be different in case of a reorg.
    3164                 :             :             // Also save the best block locator because rescanning only updates it intermittently.
    3165         [ +  - ]:          66 :             walletInstance->SetLastBlockProcessed(*scan_res.last_scanned_height, scan_res.last_scanned_block);
    3166                 :          66 :         }
    3167                 :             :     }
    3168                 :             : 
    3169                 :             :     return true;
    3170                 :        1051 : }
    3171                 :             : 
    3172                 :       24922 : const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
    3173                 :             : {
    3174                 :       24922 :     const auto& address_book_it = m_address_book.find(dest);
    3175         [ +  + ]:       24922 :     if (address_book_it == m_address_book.end()) return nullptr;
    3176   [ +  -  +  + ]:       11919 :     if ((!allow_change) && address_book_it->second.IsChange()) {
    3177                 :             :         return nullptr;
    3178                 :             :     }
    3179                 :       11916 :     return &address_book_it->second;
    3180                 :             : }
    3181                 :             : 
    3182                 :        1041 : void CWallet::postInitProcess()
    3183                 :             : {
    3184                 :             :     // Add wallet transactions that aren't already in a block to mempool
    3185                 :             :     // Do this here as mempool requires genesis block to be loaded
    3186                 :        1041 :     ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_NO_BROADCAST, /*force=*/true);
    3187                 :             : 
    3188                 :             :     // Update wallet transactions with current mempool transactions.
    3189         [ +  - ]:        3123 :     WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
    3190                 :        1041 : }
    3191                 :             : 
    3192                 :         130 : bool CWallet::BackupWallet(const std::string& strDest) const
    3193                 :             : {
    3194         [ +  - ]:         390 :     WITH_LOCK(cs_wallet, WriteBestBlock());
    3195                 :         130 :     return GetDatabase().Backup(strDest);
    3196                 :             : }
    3197                 :             : 
    3198                 :     1252849 : int CWallet::GetTxDepthInMainChain(const CWalletTx& wtx) const
    3199                 :             : {
    3200                 :     1252849 :     AssertLockHeld(cs_wallet);
    3201         [ +  + ]:     1252849 :     if (auto* conf = wtx.state<TxStateConfirmed>()) {
    3202         [ -  + ]:     1167795 :         assert(conf->confirmed_block_height >= 0);
    3203                 :     1167795 :         return GetLastBlockHeight() - conf->confirmed_block_height + 1;
    3204         [ +  + ]:       85054 :     } else if (auto* conf = wtx.state<TxStateBlockConflicted>()) {
    3205         [ -  + ]:        5175 :         assert(conf->conflicting_block_height >= 0);
    3206                 :        5175 :         return -1 * (GetLastBlockHeight() - conf->conflicting_block_height + 1);
    3207                 :             :     } else {
    3208                 :             :         return 0;
    3209                 :             :     }
    3210                 :             : }
    3211                 :             : 
    3212                 :      718725 : int CWallet::GetTxBlocksToMaturity(const CWalletTx& wtx) const
    3213                 :             : {
    3214                 :      718725 :     AssertLockHeld(cs_wallet);
    3215                 :             : 
    3216         [ +  + ]:      718725 :     if (!wtx.IsCoinBase()) {
    3217                 :             :         return 0;
    3218                 :             :     }
    3219                 :      440327 :     int chain_depth = GetTxDepthInMainChain(wtx);
    3220         [ -  + ]:      440327 :     assert(chain_depth >= 0); // coinbase tx should not be conflicted
    3221         [ +  + ]:      440327 :     return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
    3222                 :             : }
    3223                 :             : 
    3224                 :      718725 : bool CWallet::IsTxImmatureCoinBase(const CWalletTx& wtx) const
    3225                 :             : {
    3226                 :      718725 :     AssertLockHeld(cs_wallet);
    3227                 :             : 
    3228                 :             :     // note GetBlocksToMaturity is 0 for non-coinbase tx
    3229                 :      718725 :     return GetTxBlocksToMaturity(wtx) > 0;
    3230                 :             : }
    3231                 :             : 
    3232                 :       11579 : bool CWallet::IsLocked() const
    3233                 :             : {
    3234         [ +  + ]:       11579 :     if (!HasEncryptionKeys()) {
    3235                 :             :         return false;
    3236                 :             :     }
    3237                 :        2576 :     LOCK(cs_wallet);
    3238         [ +  - ]:        2576 :     return vMasterKey.empty();
    3239                 :        2576 : }
    3240                 :             : 
    3241                 :         117 : bool CWallet::Lock()
    3242                 :             : {
    3243         [ +  - ]:         117 :     if (!HasEncryptionKeys())
    3244                 :             :         return false;
    3245                 :             : 
    3246                 :         117 :     {
    3247         [ +  - ]:         117 :         LOCK2(m_relock_mutex, cs_wallet);
    3248         [ +  + ]:         117 :         if (!vMasterKey.empty()) {
    3249   [ -  +  +  - ]:          73 :             memory_cleanse(vMasterKey.data(), vMasterKey.size() * sizeof(decltype(vMasterKey)::value_type));
    3250   [ +  -  +  - ]:         190 :             vMasterKey.clear();
    3251                 :             :         }
    3252         [ +  - ]:         117 :     }
    3253                 :             : 
    3254                 :         117 :     NotifyStatusChanged(this);
    3255                 :         117 :     return true;
    3256                 :             : }
    3257                 :             : 
    3258                 :          87 : bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
    3259                 :             : {
    3260                 :          87 :     {
    3261                 :          87 :         LOCK(cs_wallet);
    3262         [ +  + ]:         706 :         for (const auto& spk_man_pair : m_spk_managers) {
    3263   [ +  -  -  + ]:         619 :             if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn)) {
    3264         [ #  # ]:           0 :                 return false;
    3265                 :             :             }
    3266                 :             :         }
    3267         [ +  - ]:          87 :         vMasterKey = vMasterKeyIn;
    3268                 :           0 :     }
    3269                 :          87 :     NotifyStatusChanged(this);
    3270                 :          87 :     return true;
    3271                 :             : }
    3272                 :             : 
    3273                 :       31140 : std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
    3274                 :             : {
    3275                 :       31140 :     std::set<ScriptPubKeyMan*> spk_mans;
    3276         [ +  + ]:       93420 :     for (bool internal : {false, true}) {
    3277         [ +  + ]:      311400 :         for (OutputType t : OUTPUT_TYPES) {
    3278         [ +  - ]:      249120 :             auto spk_man = GetScriptPubKeyMan(t, internal);
    3279         [ +  + ]:      249120 :             if (spk_man) {
    3280         [ +  - ]:      145174 :                 spk_mans.insert(spk_man);
    3281                 :             :             }
    3282                 :             :         }
    3283                 :             :     }
    3284                 :       31140 :     return spk_mans;
    3285                 :           0 : }
    3286                 :             : 
    3287                 :        2447 : bool CWallet::IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const
    3288                 :             : {
    3289   [ +  +  +  + ]:        9229 :     for (const auto& [_, ext_spkm] : m_external_spk_managers) {
    3290         [ +  + ]:        7909 :         if (ext_spkm == &spkm) return true;
    3291                 :             :     }
    3292   [ +  +  +  + ]:        3656 :     for (const auto& [_, int_spkm] : m_internal_spk_managers) {
    3293         [ +  + ]:        3450 :         if (int_spkm == &spkm) return true;
    3294                 :             :     }
    3295                 :             :     return false;
    3296                 :             : }
    3297                 :             : 
    3298                 :        4912 : std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
    3299                 :             : {
    3300                 :        4912 :     std::set<ScriptPubKeyMan*> spk_mans;
    3301         [ +  + ]:       45142 :     for (const auto& spk_man_pair : m_spk_managers) {
    3302         [ +  - ]:       40230 :         spk_mans.insert(spk_man_pair.second.get());
    3303                 :             :     }
    3304                 :        4912 :     return spk_mans;
    3305                 :           0 : }
    3306                 :             : 
    3307                 :      307147 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
    3308                 :             : {
    3309         [ +  + ]:      307147 :     const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
    3310                 :      307147 :     std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
    3311         [ +  + ]:      307147 :     if (it == spk_managers.end()) {
    3312                 :             :         return nullptr;
    3313                 :             :     }
    3314                 :      197525 :     return it->second;
    3315                 :             : }
    3316                 :             : 
    3317                 :      154747 : std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script) const
    3318                 :             : {
    3319         [ +  - ]:      154747 :     std::set<ScriptPubKeyMan*> spk_mans;
    3320                 :             : 
    3321                 :             :     // Search the cache for relevant SPKMs instead of iterating m_spk_managers
    3322         [ +  - ]:      154747 :     const auto& it = m_cached_spks.find(script);
    3323         [ +  + ]:      154747 :     if (it != m_cached_spks.end()) {
    3324         [ +  - ]:       92418 :         spk_mans.insert(it->second.begin(), it->second.end());
    3325                 :             :     }
    3326                 :      154747 :     SignatureData sigdata;
    3327         [ +  - ]:      247174 :     Assume(std::all_of(spk_mans.begin(), spk_mans.end(), [&script, &sigdata](ScriptPubKeyMan* spkm) { return spkm->CanProvide(script, sigdata); }));
    3328                 :             : 
    3329                 :      154747 :     return spk_mans;
    3330                 :      154747 : }
    3331                 :             : 
    3332                 :        4944 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
    3333                 :             : {
    3334         [ +  - ]:        4944 :     if (m_spk_managers.contains(id)) {
    3335                 :        4944 :         return m_spk_managers.at(id).get();
    3336                 :             :     }
    3337                 :             :     return nullptr;
    3338                 :             : }
    3339                 :             : 
    3340                 :      291424 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
    3341                 :             : {
    3342                 :      291424 :     SignatureData sigdata;
    3343         [ +  - ]:      582848 :     return GetSolvingProvider(script, sigdata);
    3344                 :      291424 : }
    3345                 :             : 
    3346                 :      291424 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
    3347                 :             : {
    3348                 :             :     // Search the cache for relevant SPKMs instead of iterating m_spk_managers
    3349                 :      291424 :     const auto& it = m_cached_spks.find(script);
    3350         [ +  + ]:      291424 :     if (it != m_cached_spks.end()) {
    3351                 :             :         // All spkms for a given script must already be able to make a SigningProvider for the script, so just return the first one.
    3352                 :      181212 :         Assume(it->second.at(0)->CanProvide(script, sigdata));
    3353                 :      181212 :         return it->second.at(0)->GetSolvingProvider(script);
    3354                 :             :     }
    3355                 :             : 
    3356                 :      110212 :     return nullptr;
    3357                 :             : }
    3358                 :             : 
    3359                 :       10466 : std::vector<WalletDescriptor> CWallet::GetWalletDescriptors(const CScript& script) const
    3360                 :             : {
    3361                 :       10466 :     std::vector<WalletDescriptor> descs;
    3362   [ +  -  +  + ]:       20933 :     for (const auto spk_man: GetScriptPubKeyMans(script)) {
    3363   [ +  -  +  - ]:       10467 :         if (const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man)) {
    3364         [ +  - ]:       10467 :             LOCK(desc_spk_man->cs_desc_man);
    3365   [ +  -  +  - ]:       20934 :             descs.push_back(desc_spk_man->GetWalletDescriptor());
    3366                 :       10467 :         }
    3367                 :             :     }
    3368                 :       10466 :     return descs;
    3369                 :           0 : }
    3370                 :             : 
    3371                 :        1001 : LegacyDataSPKM* CWallet::GetLegacyDataSPKM() const
    3372                 :             : {
    3373         [ +  - ]:        1001 :     if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    3374                 :             :         return nullptr;
    3375                 :             :     }
    3376                 :        1001 :     auto it = m_internal_spk_managers.find(OutputType::LEGACY);
    3377         [ +  - ]:        1001 :     if (it == m_internal_spk_managers.end()) return nullptr;
    3378         [ +  - ]:        1001 :     return dynamic_cast<LegacyDataSPKM*>(it->second);
    3379                 :             : }
    3380                 :             : 
    3381                 :        8560 : void CWallet::AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man)
    3382                 :             : {
    3383                 :             :     // Add spkm_man to m_spk_managers before calling any method
    3384                 :             :     // that might access it.
    3385                 :        8560 :     const auto& spkm = m_spk_managers[id] = std::move(spkm_man);
    3386                 :             : 
    3387                 :             :     // Update birth time if needed
    3388                 :        8560 :     MaybeUpdateBirthTime(spkm->GetTimeFirstKey());
    3389                 :        8560 : }
    3390                 :             : 
    3391                 :         875 : LegacyDataSPKM* CWallet::GetOrCreateLegacyDataSPKM()
    3392                 :             : {
    3393                 :         875 :     SetupLegacyDataSPKM();
    3394                 :         875 :     return GetLegacyDataSPKM();
    3395                 :             : }
    3396                 :             : 
    3397                 :         875 : void CWallet::SetupLegacyDataSPKM()
    3398                 :             : {
    3399   [ +  +  +  -  :         875 :     if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
             +  -  -  + ]
    3400                 :         826 :         return;
    3401                 :             :     }
    3402                 :             : 
    3403   [ +  -  -  +  :          49 :     Assert(m_database->Format() == "bdb_ro" || m_database->Format() == "sqlite-mock");
          -  -  -  -  +  
          -  -  +  -  -  
                   -  - ]
    3404                 :          49 :     std::unique_ptr<ScriptPubKeyMan> spk_manager = std::make_unique<LegacyDataSPKM>(*this);
    3405                 :             : 
    3406   [ +  +  +  - ]:         196 :     for (const auto& type : LEGACY_OUTPUT_TYPES) {
    3407         [ +  - ]:         147 :         m_internal_spk_managers[type] = spk_manager.get();
    3408         [ +  - ]:         147 :         m_external_spk_managers[type] = spk_manager.get();
    3409                 :             :     }
    3410         [ +  - ]:          49 :     uint256 id = spk_manager->GetID();
    3411         [ +  - ]:          49 :     AddScriptPubKeyMan(id, std::move(spk_manager));
    3412                 :          49 : }
    3413                 :             : 
    3414                 :        1337 : bool CWallet::WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const
    3415                 :             : {
    3416                 :        1337 :     LOCK(cs_wallet);
    3417   [ +  -  +  - ]:        1337 :     return cb(vMasterKey);
    3418                 :        1337 : }
    3419                 :             : 
    3420                 :      125812 : bool CWallet::HasEncryptionKeys() const
    3421                 :             : {
    3422                 :      125812 :     return !mapMasterKeys.empty();
    3423                 :             : }
    3424                 :             : 
    3425                 :          10 : bool CWallet::HaveCryptedKeys() const
    3426                 :             : {
    3427         [ +  + ]:          46 :     for (const auto& spkm : GetAllScriptPubKeyMans()) {
    3428   [ +  -  +  + ]:          41 :         if (spkm->HaveCryptedKeys()) return true;
    3429                 :             :     }
    3430                 :           5 :     return false;
    3431                 :             : }
    3432                 :             : 
    3433                 :        1709 : void CWallet::ConnectScriptPubKeyManNotifiers()
    3434                 :             : {
    3435         [ +  + ]:       10460 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
    3436         [ +  - ]:        8751 :         spk_man->NotifyCanGetAddressesChanged.connect([this] {
    3437                 :           1 :             NotifyCanGetAddressesChanged();
    3438                 :             :         });
    3439         [ +  - ]:       17502 :         spk_man->NotifyFirstKeyTimeChanged.connect([this](const ScriptPubKeyMan*, int64_t time) {
    3440                 :          35 :             MaybeUpdateBirthTime(time);
    3441                 :             :         });
    3442                 :             :     }
    3443                 :        1709 : }
    3444                 :             : 
    3445                 :        3182 : void CWallet::LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc, const KeyMap& keys, const CryptedKeyMap& ckeys)
    3446                 :             : {
    3447                 :        3182 :     std::unique_ptr<DescriptorScriptPubKeyMan> spk_manager;
    3448   [ +  -  +  + ]:        3182 :     if (IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
    3449         [ +  - ]:           8 :         spk_manager = ExternalSignerScriptPubKeyMan::LoadFromStorage(*this, id, desc, m_keypool_size, keys, ckeys);
    3450                 :             :     } else {
    3451         [ +  + ]:        6347 :         spk_manager = DescriptorScriptPubKeyMan::LoadFromStorage(*this, id, desc, m_keypool_size, keys, ckeys);
    3452                 :             :     }
    3453         [ +  - ]:        3181 :     AddScriptPubKeyMan(id, std::move(spk_manager));
    3454                 :        3182 : }
    3455                 :             : 
    3456                 :        4172 : DescriptorScriptPubKeyMan& CWallet::SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal)
    3457                 :             : {
    3458                 :        4172 :     AssertLockHeld(cs_wallet);
    3459         [ -  + ]:        4172 :     if (IsLocked()) {
    3460   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
    3461                 :             :     }
    3462                 :        4172 :     auto spk_manager = DescriptorScriptPubKeyMan::GenerateNewSingleSig(*this, batch, m_keypool_size, master_key, output_type, internal);
    3463         [ +  - ]:        4172 :     DescriptorScriptPubKeyMan* out = spk_manager.get();
    3464         [ +  - ]:        4172 :     uint256 id = spk_manager->GetID();
    3465         [ +  - ]:        4172 :     AddScriptPubKeyMan(id, std::move(spk_manager));
    3466         [ +  - ]:        4172 :     AddActiveScriptPubKeyManWithDb(batch, id, output_type, internal);
    3467                 :        4172 :     return *out;
    3468                 :        4172 : }
    3469                 :             : 
    3470                 :         520 : void CWallet::SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key)
    3471                 :             : {
    3472                 :         520 :     AssertLockHeld(cs_wallet);
    3473         [ +  + ]:        1560 :     for (bool internal : {false, true}) {
    3474         [ +  + ]:        5200 :         for (OutputType t : OUTPUT_TYPES) {
    3475                 :        4160 :             SetupDescriptorScriptPubKeyMan(batch, master_key, t, internal);
    3476                 :             :         }
    3477                 :             :     }
    3478                 :         520 : }
    3479                 :             : 
    3480                 :         486 : void CWallet::SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch)
    3481                 :             : {
    3482                 :         486 :     AssertLockHeld(cs_wallet);
    3483         [ -  + ]:         486 :     assert(!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER));
    3484                 :             :     // Make a seed
    3485                 :         486 :     CKey seed_key = GenerateRandomKey();
    3486         [ +  - ]:         486 :     CPubKey seed = seed_key.GetPubKey();
    3487   [ +  -  -  + ]:         486 :     assert(seed_key.VerifyPubKey(seed));
    3488                 :             : 
    3489                 :             :     // Get the extended key
    3490         [ +  - ]:         486 :     CExtKey master_key;
    3491   [ +  -  +  - ]:         972 :     master_key.SetSeed(seed_key);
    3492                 :             : 
    3493         [ +  - ]:         486 :     SetupDescriptorScriptPubKeyMans(batch, master_key);
    3494                 :         486 : }
    3495                 :             : 
    3496                 :         488 : void CWallet::SetupDescriptorScriptPubKeyMans()
    3497                 :             : {
    3498                 :         488 :     AssertLockHeld(cs_wallet);
    3499                 :             : 
    3500         [ +  + ]:         488 :     if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
    3501   [ +  -  -  + ]:         483 :         if (!RunWithinTxn(GetDatabase(), /*process_desc=*/"setup descriptors", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet){
    3502                 :         483 :             SetupOwnDescriptorScriptPubKeyMans(batch);
    3503                 :         483 :             return true;
    3504         [ #  # ]:           0 :         })) throw std::runtime_error("Error: cannot process db transaction for descriptors setup");
    3505                 :             :     } else {
    3506                 :           5 :         auto signer = ExternalSignerScriptPubKeyMan::GetExternalSigner();
    3507   [ +  +  +  -  :           5 :         if (!signer) throw std::runtime_error(util::ErrorString(signer).original);
                   +  - ]
    3508                 :             : 
    3509                 :             :         // TODO: add account parameter
    3510                 :           3 :         int account = 0;
    3511         [ +  - ]:           3 :         UniValue signer_res = signer->GetDescriptors(account);
    3512                 :             : 
    3513   [ -  +  -  -  :           3 :         if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
                   -  - ]
    3514                 :             : 
    3515         [ +  - ]:           3 :         WalletBatch batch(GetDatabase());
    3516   [ +  -  -  +  :           3 :         if (!batch.TxnBegin()) throw std::runtime_error("Error: cannot create db transaction for descriptors import");
                   -  - ]
    3517                 :             : 
    3518         [ +  + ]:           7 :         for (bool internal : {false, true}) {
    3519   [ +  +  +  - ]:           8 :             const UniValue& descriptor_vals = signer_res.find_value(internal ? "internal" : "receive");
    3520   [ -  +  -  -  :           5 :             if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
                   -  - ]
    3521   [ +  -  +  -  :          21 :             for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
                   +  + ]
    3522                 :          17 :                 const std::string& desc_str = desc_val.getValStr();
    3523                 :          17 :                 FlatSigningProvider keys;
    3524         [ -  + ]:          17 :                 std::string desc_error;
    3525   [ -  +  +  - ]:          17 :                 auto descs = Parse(desc_str, keys, desc_error, false);
    3526         [ +  + ]:          17 :                 if (descs.empty()) {
    3527   [ +  -  +  -  :           5 :                     throw std::runtime_error(std::string(__func__) + ": Invalid descriptor \"" + desc_str + "\" (" + desc_error + ")");
             +  -  +  - ]
    3528                 :             :                 }
    3529         [ +  - ]:          16 :                 auto& desc = descs.at(0);
    3530   [ +  -  -  + ]:          16 :                 if (!desc->GetOutputType()) {
    3531                 :           0 :                     continue;
    3532                 :             :                 }
    3533         [ +  - ]:          16 :                 OutputType t =  *desc->GetOutputType();
    3534         [ +  - ]:          16 :                 auto spk_manager = ExternalSignerScriptPubKeyMan::CreateNew(*this, batch, m_keypool_size, std::move(desc));
    3535         [ +  - ]:          16 :                 uint256 id = spk_manager->GetID();
    3536         [ +  - ]:          16 :                 AddScriptPubKeyMan(id, std::move(spk_manager));
    3537         [ +  - ]:          16 :                 AddActiveScriptPubKeyManWithDb(batch, id, t, internal);
    3538                 :          18 :             }
    3539                 :             :         }
    3540                 :             : 
    3541                 :             :         // Ensure imported descriptors are committed to disk
    3542   [ +  -  -  +  :           2 :         if (!batch.TxnCommit()) throw std::runtime_error("Error: cannot commit db transaction for descriptors import");
                   -  - ]
    3543                 :           3 :     }
    3544                 :         485 : }
    3545                 :             : 
    3546                 :         713 : void CWallet::SetupWalletGeneration()
    3547                 :             : {
    3548                 :         713 :     AssertLockHeld(cs_wallet);
    3549                 :             :     // Skip setup for non-external-signer wallets that are either blank
    3550                 :             :     // or have private keys disabled (not having private keys implies blank).
    3551   [ +  +  +  + ]:        1421 :     if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER) &&
    3552         [ +  + ]:        1207 :         (IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET) || IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS))) {
    3553                 :         254 :         return;
    3554                 :             :     }
    3555                 :         459 :     SetupDescriptorScriptPubKeyMans();
    3556                 :             : }
    3557                 :             : 
    3558                 :         443 : void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
    3559                 :             : {
    3560                 :         443 :     WalletBatch batch(GetDatabase());
    3561         [ +  - ]:         443 :     return AddActiveScriptPubKeyManWithDb(batch, id, type, internal);
    3562                 :         443 : }
    3563                 :             : 
    3564                 :        4631 : void CWallet::AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal)
    3565                 :             : {
    3566         [ -  + ]:        4631 :     if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
    3567   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
    3568                 :             :     }
    3569                 :        4631 :     LoadActiveScriptPubKeyMan(id, type, internal);
    3570                 :        4631 : }
    3571                 :             : 
    3572                 :        7378 : void CWallet::LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
    3573                 :             : {
    3574                 :             :     // Activating ScriptPubKeyManager for a given output and change type is incompatible with legacy wallets.
    3575                 :             :     // Legacy wallets have only one ScriptPubKeyManager and it's active for all output and change types.
    3576                 :        7378 :     Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    3577                 :             : 
    3578   [ +  +  +  - ]:       11111 :     WalletLogPrintf("Setting spkMan to active: id = %s, type = %s, internal = %s", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
    3579         [ +  + ]:        7378 :     auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
    3580                 :        7378 :     auto& spk_mans_other = internal ? m_external_spk_managers : m_internal_spk_managers;
    3581                 :        7378 :     auto spk_man = m_spk_managers.at(id).get();
    3582                 :        7377 :     spk_mans[type] = spk_man;
    3583                 :             : 
    3584                 :        7377 :     const auto it = spk_mans_other.find(type);
    3585   [ +  +  +  + ]:        7377 :     if (it != spk_mans_other.end() && it->second == spk_man) {
    3586                 :           2 :         spk_mans_other.erase(type);
    3587                 :             :     }
    3588                 :             : 
    3589                 :        7377 :     NotifyCanGetAddressesChanged();
    3590                 :        7377 : }
    3591                 :             : 
    3592                 :         240 : void CWallet::DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
    3593                 :             : {
    3594                 :         240 :     auto spk_man = GetScriptPubKeyMan(type, internal);
    3595   [ +  +  +  + ]:         240 :     if (spk_man != nullptr && spk_man->GetID() == id) {
    3596   [ +  +  +  - ]:           3 :         WalletLogPrintf("Deactivate spkMan: id = %s, type = %s, internal = %s", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
    3597                 :           2 :         WalletBatch batch(GetDatabase());
    3598   [ +  -  -  + ]:           2 :         if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type), internal)) {
    3599   [ #  #  #  # ]:           0 :             throw std::runtime_error(std::string(__func__) + ": erasing active ScriptPubKeyMan id failed");
    3600                 :             :         }
    3601                 :             : 
    3602         [ +  + ]:           2 :         auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
    3603                 :           2 :         spk_mans.erase(type);
    3604                 :           2 :     }
    3605                 :             : 
    3606                 :         240 :     NotifyCanGetAddressesChanged();
    3607                 :         240 : }
    3608                 :             : 
    3609                 :        1014 : DescriptorScriptPubKeyMan* CWallet::GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const
    3610                 :             : {
    3611                 :        1014 :     auto spk_man_pair = std::find_if(m_spk_managers.begin(), m_spk_managers.end(), [&desc](const auto& item) {
    3612         [ +  - ]:        4734 :         DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(item.second.get());
    3613   [ +  -  +  + ]:        4734 :         return spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc);
    3614                 :             :     });
    3615                 :             : 
    3616         [ +  + ]:        1014 :     if (spk_man_pair != m_spk_managers.end()) {
    3617         [ +  - ]:          34 :         return dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair->second.get());
    3618                 :             :     }
    3619                 :             : 
    3620                 :             :     return nullptr;
    3621                 :             : }
    3622                 :             : 
    3623                 :       26602 : std::optional<bool> CWallet::IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const
    3624                 :             : {
    3625                 :             :     // only active ScriptPubKeyMan can be internal
    3626         [ +  + ]:       26602 :     if (!GetActiveScriptPubKeyMans().contains(spk_man)) {
    3627                 :        8389 :         return std::nullopt;
    3628                 :             :     }
    3629                 :             : 
    3630         [ +  - ]:       18213 :     const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
    3631         [ -  + ]:       18213 :     if (!desc_spk_man) {
    3632   [ #  #  #  # ]:           0 :         throw std::runtime_error(std::string(__func__) + ": unexpected ScriptPubKeyMan type.");
    3633                 :             :     }
    3634                 :             : 
    3635                 :       18213 :     LOCK(desc_spk_man->cs_desc_man);
    3636   [ +  -  +  - ]:       18213 :     const auto& type = desc_spk_man->GetWalletDescriptor().descriptor->GetOutputType();
    3637         [ -  + ]:       18213 :     assert(type.has_value());
    3638                 :             : 
    3639   [ +  -  +  - ]:       18213 :     return GetScriptPubKeyMan(*type, /* internal= */ true) == desc_spk_man;
    3640                 :       18213 : }
    3641                 :             : 
    3642                 :         989 : util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
    3643                 :             : {
    3644                 :         989 :     AssertLockHeld(cs_wallet);
    3645                 :             : 
    3646                 :         989 :     Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    3647                 :             : 
    3648                 :         989 :     auto spk_man = GetDescriptorScriptPubKeyMan(desc);
    3649         [ +  + ]:         989 :     if (spk_man) {
    3650         [ +  - ]:          31 :         WalletLogPrintf("Update existing descriptor: %s", desc.descriptor->ToString());
    3651         [ +  + ]:          31 :         if (auto spkm_res = spk_man->UpdateWalletDescriptor(desc, signing_provider); !spkm_res) {
    3652         [ +  - ]:           9 :             return util::Error{util::ErrorString(spkm_res)};
    3653                 :          27 :         }
    3654                 :             :     } else {
    3655                 :         958 :         auto new_spk_man = DescriptorScriptPubKeyMan::CreateFromImport(*this, desc, m_keypool_size, signing_provider);
    3656         [ +  - ]:         957 :         spk_man = new_spk_man.get();
    3657                 :             : 
    3658                 :             :         // Save the descriptor to memory
    3659         [ +  - ]:         957 :         uint256 id = new_spk_man->GetID();
    3660         [ +  - ]:         957 :         AddScriptPubKeyMan(id, std::move(new_spk_man));
    3661                 :             : 
    3662                 :             :         // Write the existing cache to disk
    3663         [ +  - ]:         957 :         WalletBatch batch(GetDatabase());
    3664   [ +  -  -  + ]:         957 :         if (!batch.WriteDescriptorCacheItems(id, desc.cache)) {
    3665         [ #  # ]:           0 :             return util::Error{_("Unable to write descriptor cache")};
    3666                 :             :         }
    3667                 :         957 :     }
    3668                 :             : 
    3669                 :             :     // Apply the label if necessary
    3670                 :             :     // Note: we disable labels for descriptors that are ranged or that don't produce output scripts (i.e. unused())
    3671   [ +  +  +  + ]:         981 :     if (!desc.descriptor->IsRange() && desc.descriptor->HasScripts()) {
    3672                 :         372 :         auto script_pub_keys = spk_man->GetScriptPubKeys();
    3673         [ -  + ]:         372 :         if (script_pub_keys.empty()) {
    3674         [ #  # ]:           0 :             return util::Error{_("Could not generate scriptPubKeys (cache is empty)")};
    3675                 :             :         }
    3676                 :             : 
    3677         [ +  + ]:         372 :         if (!internal) {
    3678   [ +  +  +  - ]:        1369 :             for (const auto& script : script_pub_keys) {
    3679                 :         997 :                 CTxDestination dest;
    3680   [ +  +  +  - ]:         997 :                 if (ExtractDestination(script, dest)) {
    3681         [ +  - ]:         778 :                     SetAddressBook(dest, label, AddressPurpose::RECEIVE);
    3682                 :             :                 }
    3683                 :         997 :             }
    3684                 :             :         }
    3685                 :         372 :     }
    3686                 :             : 
    3687                 :             :     // Save the descriptor to DB
    3688                 :         981 :     spk_man->WriteDescriptor();
    3689                 :             : 
    3690                 :             :     // Break balance caches so that outputs that are now IsMine in already known txs will be included in the balance
    3691                 :         981 :     MarkDirty();
    3692                 :             : 
    3693                 :         981 :     return std::reference_wrapper(*spk_man);
    3694                 :             : }
    3695                 :             : 
    3696                 :          13 : util::Expected<CExtPubKey, WalletError> CWallet::AddHDKey(const std::optional<CExtKey>& key)
    3697                 :             : {
    3698                 :          13 :     LOCK(cs_wallet);
    3699                 :             : 
    3700   [ +  +  -  + ]:          13 :     if (key && !key->key.IsValid()) {
    3701                 :           0 :         return util::Unexpected{WalletError{
    3702                 :             :             WalletErrorCode::GenericError,
    3703         [ #  # ]:           0 :             _("Invalid HD key"),
    3704                 :           0 :         }};
    3705                 :             :     }
    3706                 :             : 
    3707   [ +  -  -  + ]:          13 :     if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
    3708                 :           0 :         return util::Unexpected{WalletError{
    3709                 :             :             WalletErrorCode::GenericError,
    3710         [ #  # ]:           0 :             _("addhdkey is not available for wallets without private keys")
    3711                 :           0 :         }};
    3712                 :             :     }
    3713                 :             : 
    3714   [ +  -  +  + ]:          13 :     if (IsLocked()) {
    3715                 :           2 :         return util::Unexpected{WalletError{
    3716                 :             :             WalletErrorCode::UnlockNeeded,
    3717         [ +  - ]:           1 :             _("Wallet needs to be unlocked to perform this operation.")
    3718                 :           1 :         }};
    3719                 :             :     }
    3720                 :             : 
    3721         [ +  + ]:          12 :     CExtKey hdkey;
    3722         [ +  + ]:          12 :     if (key) {
    3723         [ +  - ]:           4 :         hdkey = *key;
    3724                 :             :     } else {
    3725                 :           8 :         CKey seed_key = GenerateRandomKey();
    3726   [ +  -  +  - ]:          16 :         hdkey.SetSeed(seed_key);
    3727                 :           8 :     }
    3728                 :             : 
    3729   [ +  -  +  - ]:          24 :     std::string desc_str = "unused(" + EncodeExtKey(hdkey) + ")";
    3730                 :          12 :     FlatSigningProvider keys;
    3731         [ -  + ]:          12 :     std::string parse_error;
    3732   [ -  +  +  - ]:          12 :     std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_error, /*require_checksum=*/false);
    3733         [ +  + ]:          12 :     if (descs.empty()) {
    3734                 :           2 :         return util::Unexpected{WalletError{
    3735                 :             :             WalletErrorCode::GenericError,
    3736         [ +  - ]:           1 :             _("Invalid HD key")
    3737                 :           1 :         }};
    3738                 :             :     }
    3739   [ +  -  +  -  :          11 :     WalletDescriptor w_desc(std::move(descs.at(0)), GetTime(), /*range_start=*/0, /*range_end=*/0, /*next_index=*/0);
             +  -  +  - ]
    3740                 :             : 
    3741   [ +  -  +  + ]:          11 :     if (GetDescriptorScriptPubKeyMan(w_desc) != nullptr) {
    3742                 :           2 :         return util::Unexpected{WalletError{
    3743                 :             :             WalletErrorCode::GenericError,
    3744         [ +  - ]:           1 :             _("HD key already exists")
    3745                 :           1 :         }};
    3746                 :             :     }
    3747                 :             : 
    3748   [ +  -  +  - ]:          10 :     auto spkm = AddWalletDescriptor(w_desc, keys, /*label=*/"", /*internal=*/false);
    3749         [ -  + ]:          10 :     if(!spkm) {
    3750         [ #  # ]:           0 :         return util::Unexpected{WalletError{
    3751                 :             :             WalletErrorCode::GenericError,
    3752                 :             :             util::ErrorString(spkm),
    3753                 :           0 :         }};
    3754                 :             :     }
    3755                 :             : 
    3756         [ +  - ]:          10 :     const DescriptorScriptPubKeyMan& desc_spkm = spkm->get();
    3757         [ +  - ]:          10 :     LOCK(desc_spkm.cs_desc_man);
    3758         [ +  - ]:          10 :     std::set<CPubKey> pubkeys;
    3759                 :          10 :     std::set<CExtPubKey> extpubs;
    3760   [ +  -  +  - ]:          10 :     desc_spkm.GetWalletDescriptor().descriptor->GetPubKeys(pubkeys, extpubs);
    3761                 :          10 :     Assume(pubkeys.empty());
    3762                 :          10 :     Assume(extpubs.size() == 1);
    3763                 :             : 
    3764                 :          10 :     return *extpubs.begin();
    3765         [ +  - ]:          45 : }
    3766                 :             : 
    3767                 :          49 : bool CWallet::MigrateToSQLite(bilingual_str& error)
    3768                 :             : {
    3769                 :          49 :     AssertLockHeld(cs_wallet);
    3770                 :             : 
    3771                 :          49 :     WalletLogPrintf("Migrating wallet storage database from BerkeleyDB to SQLite.");
    3772                 :             : 
    3773         [ -  + ]:          49 :     if (m_database->Format() == "sqlite") {
    3774                 :           0 :         error = _("Error: This wallet already uses SQLite");
    3775                 :           0 :         return false;
    3776                 :             :     }
    3777                 :             : 
    3778                 :             :     // Get all of the records for DB type migration
    3779                 :          49 :     std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();
    3780         [ +  - ]:          49 :     std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
    3781                 :          49 :     std::vector<std::pair<SerializeData, SerializeData>> records;
    3782         [ -  + ]:          49 :     if (!cursor) {
    3783         [ #  # ]:           0 :         error = _("Error: Unable to begin reading all records in the database");
    3784                 :           0 :         return false;
    3785                 :             :     }
    3786                 :        1993 :     DatabaseCursor::Status status = DatabaseCursor::Status::FAIL;
    3787                 :        3937 :     while (true) {
    3788                 :        1993 :         DataStream ss_key{};
    3789                 :        1993 :         DataStream ss_value{};
    3790         [ +  - ]:        1993 :         status = cursor->Next(ss_key, ss_value);
    3791         [ +  + ]:        1993 :         if (status != DatabaseCursor::Status::MORE) {
    3792                 :             :             break;
    3793                 :             :         }
    3794         [ +  - ]:        1944 :         SerializeData key(ss_key.begin(), ss_key.end());
    3795         [ +  - ]:        1944 :         SerializeData value(ss_value.begin(), ss_value.end());
    3796         [ +  - ]:        1944 :         records.emplace_back(key, value);
    3797                 :        1993 :     }
    3798         [ +  - ]:          49 :     cursor.reset();
    3799         [ +  - ]:          49 :     batch.reset();
    3800         [ -  + ]:          49 :     if (status != DatabaseCursor::Status::DONE) {
    3801         [ #  # ]:           0 :         error = _("Error: Unable to read all records in the database");
    3802                 :           0 :         return false;
    3803                 :             :     }
    3804                 :             : 
    3805                 :             :     // Close this database and delete the file
    3806   [ +  -  +  - ]:          49 :     fs::path db_path = fs::PathFromString(m_database->Filename());
    3807         [ +  - ]:          49 :     m_database->Close();
    3808         [ +  - ]:          49 :     fs::remove(db_path);
    3809                 :             : 
    3810                 :             :     // Generate the path for the location of the migrated wallet
    3811                 :             :     // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
    3812   [ +  -  +  -  :          98 :     const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));
                   +  - ]
    3813                 :             : 
    3814                 :             :     // Make new DB
    3815         [ +  - ]:          49 :     DatabaseOptions opts;
    3816                 :          49 :     opts.require_create = true;
    3817                 :          49 :     opts.require_format = DatabaseFormat::SQLITE;
    3818                 :          49 :     DatabaseStatus db_status;
    3819         [ +  - ]:          49 :     std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
    3820         [ -  + ]:          49 :     assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
    3821         [ +  - ]:          49 :     m_database.reset();
    3822                 :          49 :     m_database = std::move(new_db);
    3823                 :             : 
    3824                 :             :     // Write existing records into the new DB
    3825         [ +  - ]:          98 :     batch = m_database->MakeBatch();
    3826         [ +  - ]:          49 :     bool began = batch->TxnBegin();
    3827         [ -  + ]:          49 :     assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3828   [ -  +  +  + ]:        1993 :     for (const auto& [key, value] : records) {
    3829   [ -  +  -  +  :        1944 :         if (!batch->Write(std::span{key}, std::span{value})) {
             +  -  -  + ]
    3830         [ #  # ]:           0 :             batch->TxnAbort();
    3831         [ #  # ]:           0 :             m_database->Close();
    3832   [ #  #  #  #  :           0 :             fs::remove(m_database->Filename());
                   #  # ]
    3833                 :           0 :             AssertUnreachable(); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3834                 :             :         }
    3835                 :             :     }
    3836         [ +  - ]:          49 :     bool committed = batch->TxnCommit();
    3837         [ -  + ]:          49 :     assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
    3838                 :          49 :     return true;
    3839                 :         147 : }
    3840                 :             : 
    3841                 :          46 : std::optional<MigrationData> CWallet::GetDescriptorsForLegacy(bilingual_str& error) const
    3842                 :             : {
    3843                 :          46 :     AssertLockHeld(cs_wallet);
    3844                 :             : 
    3845                 :          46 :     LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
    3846         [ -  + ]:          46 :     if (!Assume(legacy_spkm)) {
    3847                 :             :         // This shouldn't happen
    3848         [ #  # ]:           0 :         error = Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"));
    3849                 :           0 :         return std::nullopt;
    3850                 :             :     }
    3851                 :             : 
    3852                 :          46 :     std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();
    3853         [ -  + ]:          46 :     if (res == std::nullopt) {
    3854         [ #  # ]:           0 :         error = _("Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.");
    3855                 :           0 :         return std::nullopt;
    3856                 :             :     }
    3857                 :          46 :     return res;
    3858                 :          46 : }
    3859                 :             : 
    3860                 :          42 : util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data)
    3861                 :             : {
    3862                 :          42 :     AssertLockHeld(cs_wallet);
    3863                 :             : 
    3864                 :          42 :     LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();
    3865         [ -  + ]:          42 :     if (!Assume(legacy_spkm)) {
    3866                 :             :         // This shouldn't happen
    3867         [ #  # ]:           0 :         return util::Error{Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"))};
    3868                 :             :     }
    3869                 :             : 
    3870                 :             :     // Note: when the legacy wallet has no spendable scripts, it must be empty at the end of the process.
    3871   [ +  +  -  + ]:          42 :     bool has_spendable_material = !data.desc_spkms.empty() || data.master_key.key.IsValid();
    3872                 :             : 
    3873                 :             :     // Get all invalid or non-watched scripts that will not be migrated
    3874         [ +  - ]:          42 :     std::set<CTxDestination> not_migrated_dests;
    3875   [ +  -  +  +  :          46 :     for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {
                   +  - ]
    3876                 :           4 :         CTxDestination dest;
    3877   [ +  -  +  -  :           4 :         if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);
                   +  - ]
    3878                 :           4 :     }
    3879                 :             : 
    3880                 :             :     // When the legacy wallet has no spendable scripts, the main wallet will be empty, leaving its script cache empty as well.
    3881                 :             :     // The watch-only and/or solvable wallet(s) will contain the scripts in their respective caches.
    3882         [ +  + ]:          42 :     if (!data.desc_spkms.empty()) Assume(!m_cached_spks.empty());
    3883         [ +  + ]:          42 :     if (!data.watch_descs.empty()) Assume(!data.watchonly_wallet->m_cached_spks.empty());
    3884         [ +  + ]:          42 :     if (!data.solvable_descs.empty()) Assume(!data.solvable_wallet->m_cached_spks.empty());
    3885                 :             : 
    3886         [ +  + ]:         227 :     for (auto& desc_spkm : data.desc_spkms) {
    3887   [ +  -  -  + ]:         185 :         if (m_spk_managers.contains(desc_spkm->GetID())) {
    3888         [ #  # ]:           0 :             return util::Error{_("Error: Duplicate descriptors created during migration. Your wallet may be corrupted.")};
    3889                 :             :         }
    3890         [ +  - ]:         185 :         uint256 id = desc_spkm->GetID();
    3891         [ +  - ]:         185 :         AddScriptPubKeyMan(id, std::move(desc_spkm));
    3892                 :             :     }
    3893                 :             : 
    3894                 :             :     // Remove the LegacyDataSPKM's records from disk
    3895   [ +  -  -  + ]:          42 :     if (!legacy_spkm->DeleteRecordsWithDB(local_wallet_batch)) {
    3896         [ #  # ]:           0 :         return util::Error{_("Error: cannot remove legacy wallet records")};
    3897                 :             :     }
    3898                 :             : 
    3899                 :             :     // Remove the LegacyDataSPKM from memory
    3900         [ +  - ]:          42 :     m_spk_managers.erase(legacy_spkm->GetID());
    3901                 :          42 :     m_external_spk_managers.clear();
    3902                 :          42 :     m_internal_spk_managers.clear();
    3903                 :             : 
    3904                 :             :     // Setup new descriptors (only if we are migrating any key material)
    3905         [ +  - ]:          42 :     SetWalletFlagWithDB(local_wallet_batch, WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);
    3906   [ +  +  +  -  :          42 :     if (has_spendable_material && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
                   +  + ]
    3907                 :             :         // Use the existing master key if we have it
    3908         [ +  + ]:          37 :         if (data.master_key.key.IsValid()) {
    3909         [ +  - ]:          34 :             SetupDescriptorScriptPubKeyMans(local_wallet_batch, data.master_key);
    3910                 :             :         } else {
    3911                 :             :             // Setup with a new seed if we don't.
    3912         [ +  - ]:           3 :             SetupOwnDescriptorScriptPubKeyMans(local_wallet_batch);
    3913                 :             :         }
    3914                 :             :     }
    3915                 :             : 
    3916                 :             :     // Set the last opened version and features
    3917   [ +  -  -  + ]:          42 :     if (!local_wallet_batch.WriteLastOpenedVersion()) {
    3918         [ #  # ]:           0 :         return util::Error{_("Error: Unable to write last opened version")};
    3919                 :             :     }
    3920   [ +  -  -  + ]:          42 :     if (!local_wallet_batch.WriteLastOpenedFeatures()) {
    3921         [ #  # ]:           0 :         return util::Error{_("Error: Unable to write last opened features")};
    3922                 :             :     }
    3923   [ +  -  +  + ]:          42 :     if (HasEncryptionKeys()) {
    3924   [ +  -  -  + ]:           3 :         if (!local_wallet_batch.WriteLastDecryptedFeatures()) {
    3925         [ #  # ]:           0 :             return util::Error{_("Error: Unable to write last decrypted features")};
    3926                 :             :         }
    3927                 :             :     }
    3928                 :             : 
    3929                 :             :     // Get best block locator so that we can copy it to the watchonly and solvables
    3930                 :             :     // Note: The best block locator was introduced in #152 so ancient wallets do not have it
    3931                 :          42 :     CBlockLocator best_block_locator;
    3932         [ +  - ]:          42 :     (void)local_wallet_batch.ReadBestBlock(best_block_locator);
    3933                 :             : 
    3934                 :             :     // Update m_txos to match the descriptors remaining in this wallet
    3935                 :          42 :     m_txos.clear();
    3936         [ +  - ]:          42 :     RefreshAllTXOs();
    3937                 :             : 
    3938                 :             :     // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.
    3939                 :             :     // We need to go through these in the tx insertion order so that lookups to spends works.
    3940                 :          42 :     std::vector<Txid> txids_to_delete;
    3941                 :          42 :     std::unique_ptr<WalletBatch> watchonly_batch;
    3942         [ +  + ]:          42 :     if (data.watchonly_wallet) {
    3943         [ +  - ]:          24 :         watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());
    3944   [ +  -  -  +  :          12 :         if (!watchonly_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.watchonly_wallet->GetName())};
                   -  - ]
    3945                 :             :         // Copy the next tx order pos to the watchonly wallet
    3946         [ +  - ]:          12 :         LOCK(data.watchonly_wallet->cs_wallet);
    3947         [ +  - ]:          12 :         data.watchonly_wallet->nOrderPosNext = nOrderPosNext;
    3948         [ +  - ]:          12 :         watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);
    3949                 :             :         // Write the locator record. An empty locator is valid and triggers rescan on load.
    3950   [ +  -  -  + ]:          12 :         if (!watchonly_batch->WriteBestBlock(best_block_locator)) {
    3951   [ #  #  #  # ]:           0 :             return util::Error{_("Error: Unable to write watchonly wallet best block locator record")};
    3952                 :             :         }
    3953                 :          12 :     }
    3954                 :          42 :     std::unique_ptr<WalletBatch> solvables_batch;
    3955         [ +  + ]:          42 :     if (data.solvable_wallet) {
    3956         [ +  - ]:          12 :         solvables_batch = std::make_unique<WalletBatch>(data.solvable_wallet->GetDatabase());
    3957   [ +  -  -  +  :           6 :         if (!solvables_batch->TxnBegin()) return util::Error{strprintf(_("Error: database transaction cannot be executed for wallet %s"), data.solvable_wallet->GetName())};
                   -  - ]
    3958                 :             :         // Write the locator record. An empty locator is valid and triggers rescan on load.
    3959   [ +  -  -  + ]:           6 :         if (!solvables_batch->WriteBestBlock(best_block_locator)) {
    3960         [ #  # ]:           0 :             return util::Error{_("Error: Unable to write solvable wallet best block locator record")};
    3961                 :             :         }
    3962                 :             :     }
    3963   [ +  -  +  + ]:         519 :     for (const auto& [_pos, wtx] : wtxOrdered) {
    3964                 :             :         // Check it is the watchonly wallet's
    3965                 :             :         // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for
    3966   [ +  -  +  -  :         489 :         bool is_mine = IsMine(*wtx->GetTx()) || IsFromMe(*wtx->GetTx());
          +  +  +  -  +  
          -  +  +  -  -  
                   -  - ]
    3967         [ +  + ]:         477 :         if (data.watchonly_wallet) {
    3968         [ +  - ]:          22 :             LOCK(data.watchonly_wallet->cs_wallet);
    3969   [ +  -  +  -  :          54 :             if (data.watchonly_wallet->IsMine(*wtx->GetTx()) || data.watchonly_wallet->IsFromMe(*wtx->GetTx())) {
          +  +  +  -  +  
          -  +  +  +  +  
             -  -  -  - ]
    3970                 :             :                 // Add to watchonly wallet
    3971         [ +  - ]:          14 :                 const Txid& hash = wtx->GetHash();
    3972                 :          14 :                 DataStream wtx_ser;
    3973         [ +  - ]:          14 :                 wtx_ser << *wtx;
    3974         [ +  - ]:          14 :                 CWalletTx copy_wtx(deserialize, wtx_ser, wtx->GetTxs());
    3975   [ +  -  -  + ]:          14 :                 if (!data.watchonly_wallet->LoadToWallet(std::move(copy_wtx))) {
    3976   [ #  #  #  #  :           0 :                     return util::Error{strprintf(_("Error: Could not add watchonly tx %s to watchonly wallet"), wtx->GetHash().GetHex())};
                   #  # ]
    3977                 :             :                 }
    3978   [ +  -  +  - ]:          14 :                 watchonly_batch->WriteFullTx(data.watchonly_wallet->mapWallet.at(hash));
    3979                 :             :                 // Mark as to remove from the migrated wallet only if it does not also belong to it
    3980         [ +  + ]:          14 :                 if (!is_mine) {
    3981         [ +  - ]:          11 :                     txids_to_delete.push_back(hash);
    3982                 :          11 :                     continue;
    3983                 :             :                 }
    3984   [ -  -  +  - ]:          14 :             }
    3985                 :          22 :         }
    3986         [ -  + ]:         466 :         if (!is_mine) {
    3987                 :             :             // Both not ours and not in the watchonly wallet
    3988   [ #  #  #  #  :           0 :             return util::Error{strprintf(_("Error: Transaction %s in wallet cannot be identified to belong to migrated wallets"), wtx->GetHash().GetHex())};
                   #  # ]
    3989                 :             :         }
    3990                 :             :         // Rewrite the transaction so that anything that may have changed about it in memory also persists to disk
    3991         [ +  - ]:         466 :         local_wallet_batch.WriteTxMetadata(*wtx);
    3992                 :             :     }
    3993                 :             : 
    3994                 :             :     // Do the removes
    3995   [ -  +  +  + ]:          42 :     if (txids_to_delete.size() > 0) {
    3996   [ +  -  -  + ]:           6 :         if (auto res = RemoveTxs(local_wallet_batch, txids_to_delete); !res) {
    3997   [ #  #  #  # ]:           0 :             return util::Error{_("Error: Could not delete watchonly transactions. ") + util::ErrorString(res)};
    3998                 :           6 :         }
    3999                 :             :     }
    4000                 :             : 
    4001                 :             :     // Pair external wallets with their corresponding db handler
    4002                 :          42 :     std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;
    4003   [ +  +  +  - ]:          42 :     if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet, std::move(watchonly_batch));
    4004   [ +  +  +  - ]:          42 :     if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet, std::move(solvables_batch));
    4005                 :             : 
    4006                 :             :     // Write address book entry to disk
    4007                 :         103 :     auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {
    4008                 :          61 :         auto address{EncodeDestination(dest)};
    4009   [ +  -  +  -  :         122 :         if (entry.purpose) batch.WritePurpose(address, PurposeToString(*entry.purpose));
                   +  - ]
    4010   [ +  -  +  - ]:          61 :         if (entry.label) batch.WriteName(address, *entry.label);
    4011   [ -  -  -  + ]:          61 :         for (const auto& [id, request] : entry.receive_requests) {
    4012         [ #  # ]:           0 :             batch.WriteAddressReceiveRequest(dest, id, request);
    4013                 :             :         }
    4014   [ +  +  +  - ]:          61 :         if (entry.previously_spent) batch.WriteAddressPreviouslySpent(dest, true);
    4015                 :          61 :     };
    4016                 :             : 
    4017                 :             :     // Check the address book data in the same way we did for transactions
    4018                 :          42 :     std::vector<CTxDestination> dests_to_delete;
    4019   [ +  -  +  + ]:         155 :     for (const auto& [dest, record] : m_address_book) {
    4020                 :             :         // Ensure "receive" entries that are no longer part of the original wallet are transferred to another wallet
    4021                 :             :         // Entries for everything else ("send") will be cloned to all wallets.
    4022   [ +  -  +  -  :         218 :         bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);
                   +  + ]
    4023                 :         113 :         bool copied = false;
    4024   [ +  -  +  + ]:         151 :         for (auto& [wallet, batch] : wallets_vec) {
    4025         [ +  - ]:          62 :             LOCK(wallet->cs_wallet);
    4026   [ +  +  +  -  :          62 :             if (require_transfer && !wallet->IsMine(dest)) continue;
             +  +  +  - ]
    4027                 :             : 
    4028                 :             :             // Copy the entire address book entry
    4029   [ +  -  +  - ]:          61 :             wallet->m_address_book[dest] = record;
    4030         [ +  - ]:          61 :             func_store_addr(*batch, dest, record);
    4031                 :             : 
    4032                 :          61 :             copied = true;
    4033                 :             :             // Only delete 'receive' records that are no longer part of the original wallet
    4034         [ +  + ]:          61 :             if (require_transfer) {
    4035         [ +  - ]:          24 :                 dests_to_delete.push_back(dest);
    4036         [ +  - ]:          24 :                 break;
    4037                 :             :             }
    4038                 :          62 :         }
    4039                 :             : 
    4040                 :             :         // Fail immediately if we ever found an entry that was ours and cannot be transferred
    4041                 :             :         // to any of the created wallets (watch-only, solvable).
    4042                 :             :         // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.
    4043         [ +  + ]:         113 :         if (require_transfer && !copied) {
    4044                 :             : 
    4045                 :             :             // Skip invalid/non-watched scripts that will not be migrated
    4046         [ +  - ]:           4 :             if (not_migrated_dests.contains(dest)) {
    4047         [ +  - ]:           4 :                 dests_to_delete.push_back(dest);
    4048                 :           4 :                 continue;
    4049                 :             :             }
    4050                 :             : 
    4051         [ #  # ]:           0 :             return util::Error{_("Error: Address book data in wallet cannot be identified to belong to migrated wallets")};
    4052                 :             :         }
    4053                 :             :     }
    4054                 :             : 
    4055                 :             :     // Persist external wallets address book entries
    4056   [ +  -  +  + ]:          60 :     for (auto& [wallet, batch] : wallets_vec) {
    4057   [ +  -  -  + ]:          18 :         if (!batch->TxnCommit()) {
    4058         [ #  # ]:           0 :             return util::Error{strprintf(_("Error: Unable to write data to disk for wallet %s"), wallet->GetName())};
    4059                 :             :         }
    4060                 :             :     }
    4061                 :             : 
    4062                 :             :     // Remove the things to delete in this wallet
    4063   [ -  +  +  + ]:          42 :     if (dests_to_delete.size() > 0) {
    4064         [ +  + ]:          40 :         for (const auto& dest : dests_to_delete) {
    4065   [ +  -  -  + ]:          28 :             if (!DelAddressBookWithDB(local_wallet_batch, dest)) {
    4066         [ #  # ]:           0 :                 return util::Error{_("Error: Unable to remove watchonly address book data")};
    4067                 :             :             }
    4068                 :             :         }
    4069                 :             :     }
    4070                 :             : 
    4071                 :             :     // If there was no key material in the main wallet, there should be no records on it anymore.
    4072                 :             :     // This wallet will be discarded at the end of the process. Only wallets that contain the
    4073                 :             :     // migrated records will be presented to the user.
    4074         [ +  + ]:          42 :     if (!has_spendable_material) {
    4075   [ -  +  -  - ]:           3 :         if (!m_address_book.empty()) return util::Error{_("Error: Not all address book records were migrated")};
    4076   [ -  +  -  - ]:           3 :         if (!mapWallet.empty()) return util::Error{_("Error: Not all transaction records were migrated")};
    4077                 :             :     }
    4078                 :             : 
    4079                 :          42 :     return {}; // all good
    4080                 :          84 : }
    4081                 :             : 
    4082                 :      147427 : bool CWallet::CanGrindR() const
    4083                 :             : {
    4084                 :      147427 :     return !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
    4085                 :             : }
    4086                 :             : 
    4087                 :             : // Returns wallet prefix for migration.
    4088                 :             : // Used to name the backup file and newly created wallets.
    4089                 :             : // E.g. a watch-only wallet is named "<prefix>_watchonly".
    4090                 :          29 : static std::string MigrationPrefixName(CWallet& wallet)
    4091                 :             : {
    4092         [ +  + ]:          29 :     const std::string& name{wallet.GetName()};
    4093         [ +  + ]:          29 :     return name.empty() ? "default_wallet" : name;
    4094                 :             : }
    4095                 :             : 
    4096                 :          46 : bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res, const bool load_on_startup = true) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
    4097                 :             : {
    4098                 :          46 :     AssertLockHeld(wallet.cs_wallet);
    4099                 :             : 
    4100                 :             :     // Get all of the descriptors from the legacy wallet
    4101                 :          46 :     std::optional<MigrationData> data = wallet.GetDescriptorsForLegacy(error);
    4102         [ +  - ]:          46 :     if (data == std::nullopt) return false;
    4103                 :             : 
    4104                 :             :     // Create the watchonly and solvable wallets if necessary
    4105   [ -  +  +  +  :          46 :     if (data->watch_descs.size() > 0 || data->solvable_descs.size() > 0) {
             -  +  +  + ]
    4106         [ +  - ]:          17 :         DatabaseOptions options;
    4107                 :          17 :         options.require_existing = false;
    4108                 :          17 :         options.require_create = true;
    4109                 :          17 :         options.require_format = DatabaseFormat::SQLITE;
    4110                 :             : 
    4111         [ +  - ]:          17 :         WalletContext empty_context;
    4112                 :          17 :         empty_context.args = context.args;
    4113                 :             : 
    4114                 :             :         // Make the wallets
    4115                 :          17 :         options.create_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET | WALLET_FLAG_DESCRIPTORS;
    4116   [ +  -  +  + ]:          17 :         if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
    4117                 :           1 :             options.create_flags |= WALLET_FLAG_AVOID_REUSE;
    4118                 :             :         }
    4119   [ +  -  +  + ]:          17 :         if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
    4120                 :          13 :             options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;
    4121                 :             :         }
    4122   [ -  +  +  + ]:          17 :         if (data->watch_descs.size() > 0) {
    4123         [ +  - ]:          16 :             wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts");
    4124                 :             : 
    4125                 :          16 :             DatabaseStatus status;
    4126                 :          16 :             std::vector<bilingual_str> warnings;
    4127         [ +  - ]:          32 :             std::string wallet_name = MigrationPrefixName(wallet) + "_watchonly";
    4128         [ +  - ]:          16 :             std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
    4129         [ +  + ]:          16 :             if (!database) {
    4130         [ +  - ]:           3 :                 error = strprintf(_("Wallet file creation failed: %s"), error);
    4131                 :           3 :                 return false;
    4132                 :             :             }
    4133                 :             : 
    4134   [ +  -  -  + ]:          13 :             data->watchonly_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
    4135         [ -  + ]:          13 :             if (!data->watchonly_wallet) {
    4136         [ #  # ]:           0 :                 error = _("Error: Failed to create new watchonly wallet");
    4137                 :           0 :                 return false;
    4138                 :             :             }
    4139                 :          13 :             res.watchonly_wallet = data->watchonly_wallet;
    4140         [ +  - ]:          13 :             LOCK(data->watchonly_wallet->cs_wallet);
    4141                 :             : 
    4142                 :             :             // Parse the descriptors and add them to the new wallet
    4143         [ +  + ]:          50 :             for (const auto& [desc_str, creation_time] : data->watch_descs) {
    4144                 :             :                 // Parse the descriptor
    4145                 :          37 :                 FlatSigningProvider keys;
    4146         [ -  + ]:          37 :                 std::string parse_err;
    4147   [ -  +  +  - ]:          37 :                 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
    4148                 :             :                 // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
    4149   [ -  +  -  + ]:          37 :                 assert(descs.size() == 1);
    4150   [ +  -  +  -  :          37 :                 assert(!descs.at(0)->IsRange());
                   -  + ]
    4151                 :             : 
    4152                 :             :                 // Add to the wallet
    4153   [ +  -  +  -  :          37 :                 WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
                   +  - ]
    4154   [ +  -  +  -  :          74 :                 if (auto spkm_res = data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
                   -  + ]
    4155   [ #  #  #  # ]:           0 :                     throw std::runtime_error(util::ErrorString(spkm_res).original);
    4156                 :           0 :                 }
    4157                 :          37 :             }
    4158                 :             : 
    4159                 :             :             // Add the wallet to settings
    4160         [ +  - ]:          13 :             UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
    4161                 :          16 :         }
    4162   [ -  +  +  + ]:          14 :         if (data->solvable_descs.size() > 0) {
    4163         [ +  - ]:           7 :             wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts");
    4164                 :             : 
    4165                 :           7 :             DatabaseStatus status;
    4166                 :           7 :             std::vector<bilingual_str> warnings;
    4167         [ +  - ]:          14 :             std::string wallet_name = MigrationPrefixName(wallet) + "_solvables";
    4168         [ +  - ]:           7 :             std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
    4169         [ +  + ]:           7 :             if (!database) {
    4170         [ +  - ]:           1 :                 error = strprintf(_("Wallet file creation failed: %s"), error);
    4171                 :           1 :                 return false;
    4172                 :             :             }
    4173                 :             : 
    4174   [ +  -  -  + ]:           6 :             data->solvable_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);
    4175         [ -  + ]:           6 :             if (!data->solvable_wallet) {
    4176         [ #  # ]:           0 :                 error = _("Error: Failed to create new watchonly wallet");
    4177                 :           0 :                 return false;
    4178                 :             :             }
    4179                 :           6 :             res.solvables_wallet = data->solvable_wallet;
    4180         [ +  - ]:           6 :             LOCK(data->solvable_wallet->cs_wallet);
    4181                 :             : 
    4182                 :             :             // Parse the descriptors and add them to the new wallet
    4183         [ +  + ]:          21 :             for (const auto& [desc_str, creation_time] : data->solvable_descs) {
    4184                 :             :                 // Parse the descriptor
    4185                 :          15 :                 FlatSigningProvider keys;
    4186         [ -  + ]:          15 :                 std::string parse_err;
    4187   [ -  +  +  - ]:          15 :                 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);
    4188                 :             :                 // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.
    4189   [ -  +  -  + ]:          15 :                 assert(descs.size() == 1);
    4190   [ +  -  +  -  :          15 :                 assert(!descs.at(0)->IsRange());
                   -  + ]
    4191                 :             : 
    4192                 :             :                 // Add to the wallet
    4193   [ +  -  +  -  :          15 :                 WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
                   +  - ]
    4194   [ +  -  +  -  :          30 :                 if (auto spkm_res = data->solvable_wallet->AddWalletDescriptor(w_desc, keys, "", false); !spkm_res) {
                   -  + ]
    4195   [ #  #  #  # ]:           0 :                     throw std::runtime_error(util::ErrorString(spkm_res).original);
    4196                 :           0 :                 }
    4197                 :          15 :             }
    4198                 :             : 
    4199                 :             :             // Add the wallet to settings
    4200         [ +  - ]:           6 :             UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);
    4201                 :           7 :         }
    4202                 :          17 :     }
    4203                 :             : 
    4204                 :             :     // Add the descriptors to the wallet, remove the LegacyDataSPKM, and clean up transactions and address book data
    4205   [ +  -  +  - ]:          42 :     return RunWithinTxn(wallet.GetDatabase(), /*process_desc=*/"apply migration process", [&](WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet){
    4206         [ -  + ]:          42 :         if (auto res_migration = wallet.ApplyMigrationData(batch, *data); !res_migration) {
    4207         [ #  # ]:           0 :             error = util::ErrorString(res_migration);
    4208                 :           0 :             return false;
    4209                 :           0 :         }
    4210                 :          42 :         wallet.WalletLogPrintf("Wallet migration complete.");
    4211                 :          42 :         return true;
    4212                 :             :     });
    4213                 :          46 : }
    4214                 :             : 
    4215                 :          55 : util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context, bool load_wallet)
    4216                 :             : {
    4217                 :          55 :     std::vector<bilingual_str> warnings;
    4218         [ +  - ]:          55 :     bilingual_str error;
    4219                 :             : 
    4220                 :             :     // The only kind of wallets that could be loaded are descriptor ones, which don't need to be migrated.
    4221   [ +  -  +  + ]:          55 :     if (auto wallet = GetWallet(context, wallet_name)) {
    4222   [ +  -  -  + ]:           1 :         assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    4223         [ +  - ]:           3 :         return util::Error{_("Error: This wallet is already a descriptor wallet")};
    4224                 :             :     } else {
    4225                 :             :         // Check if the wallet is BDB
    4226   [ +  -  -  + ]:         106 :         const auto& wallet_path = GetWalletPath(wallet_name);
    4227         [ -  + ]:          54 :         if (!wallet_path) {
    4228         [ #  # ]:           0 :             return util::Error{util::ErrorString(wallet_path)};
    4229                 :             :         }
    4230   [ +  -  +  + ]:          54 :         if (!fs::exists(*wallet_path)) {
    4231         [ +  - ]:           3 :             return util::Error{_("Error: Wallet does not exist")};
    4232                 :             :         }
    4233   [ +  -  +  -  :         106 :         if (!IsBDBFile(BDBDataFile(*wallet_path))) {
                   +  + ]
    4234         [ +  - ]:           3 :             return util::Error{_("Error: This wallet is already a descriptor wallet")};
    4235                 :             :         }
    4236                 :           3 :     }
    4237                 :             : 
    4238                 :             :     // Load the wallet but only in the context of this function.
    4239                 :             :     // No signals should be connected nor should anything else be aware of this wallet
    4240         [ +  - ]:          52 :     WalletContext empty_context;
    4241                 :          52 :     empty_context.args = context.args;
    4242         [ +  - ]:          52 :     DatabaseOptions options;
    4243                 :          52 :     options.require_existing = true;
    4244                 :          52 :     options.require_format = DatabaseFormat::BERKELEY_RO;
    4245                 :          52 :     DatabaseStatus status;
    4246         [ +  - ]:          52 :     std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
    4247         [ -  + ]:          52 :     if (!database) {
    4248   [ #  #  #  #  :           0 :         return util::Error{Untranslated("Wallet file verification failed.") + Untranslated(" ") + error};
          #  #  #  #  #  
                      # ]
    4249                 :             :     }
    4250                 :             : 
    4251                 :             :     // Make the local wallet
    4252         [ +  - ]:          52 :     std::shared_ptr<CWallet> local_wallet = CWallet::LoadExisting(empty_context, wallet_name, std::move(database), error, warnings);
    4253         [ -  + ]:          52 :     if (!local_wallet) {
    4254   [ #  #  #  #  :           0 :         return util::Error{Untranslated("Wallet loading failed.") + Untranslated(" ") + error};
          #  #  #  #  #  
                      # ]
    4255                 :             :     }
    4256                 :             : 
    4257         [ +  - ]:         104 :     return MigrateLegacyToDescriptor(std::move(local_wallet), passphrase, context, load_wallet);
    4258                 :         107 : }
    4259                 :             : 
    4260                 :          52 : util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context, bool load_wallet)
    4261                 :             : {
    4262                 :          52 :     MigrationResult res;
    4263         [ -  + ]:          52 :     bilingual_str error;
    4264                 :          52 :     std::vector<bilingual_str> warnings;
    4265                 :             : 
    4266         [ -  + ]:          52 :     DatabaseOptions options;
    4267                 :          52 :     options.require_existing = true;
    4268                 :          52 :     DatabaseStatus status;
    4269                 :             : 
    4270         [ -  + ]:          52 :     const std::string wallet_name = local_wallet->GetName();
    4271                 :             : 
    4272                 :             :     // Before anything else, check if there is something to migrate.
    4273   [ +  -  -  + ]:          52 :     if (local_wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    4274         [ #  # ]:           0 :         return util::Error{_("Error: This wallet is already a descriptor wallet")};
    4275                 :             :     }
    4276                 :             : 
    4277                 :             :     // Make a backup of the DB in the wallet's directory with a unique filename
    4278                 :             :     // using the wallet name and current timestamp. The backup filename is based
    4279                 :             :     // on the name of the parent directory containing the wallet data in most
    4280                 :             :     // cases, but in the case where the wallet name is a path to a data file,
    4281                 :             :     // the name of the data file is used, and in the case where the wallet name
    4282                 :             :     // is blank, "default_wallet" is used.
    4283         [ +  + ]:          52 :     const std::string backup_prefix = wallet_name.empty() ? MigrationPrefixName(*local_wallet) : [&] {
    4284                 :             :         // fs::weakly_canonical resolves relative specifiers and remove trailing slashes.
    4285   [ +  -  +  - ]:         184 :         const auto legacy_wallet_path = fs::weakly_canonical(GetWalletDir() / fs::PathFromString(wallet_name));
    4286   [ +  -  -  + ]:         230 :         return fs::PathToString(legacy_wallet_path.filename());
    4287   [ +  -  +  - ]:          98 :     }();
    4288                 :             : 
    4289   [ +  -  +  -  :          52 :     fs::path backup_filename = fs::PathFromString(strprintf("%s_%d.legacy.bak", backup_prefix, GetTime()));
                   +  - ]
    4290   [ +  -  +  - ]:          52 :     fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
    4291   [ -  +  +  -  :         104 :     if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
                   -  + ]
    4292         [ #  # ]:           0 :         return util::Error{_("Error: Unable to make a backup of your wallet")};
    4293                 :             :     }
    4294         [ +  - ]:          52 :     res.backup_path = backup_path;
    4295                 :             : 
    4296                 :          52 :     bool success = false;
    4297                 :             : 
    4298                 :             :     // Unlock the wallet if needed
    4299   [ +  -  +  + ]:          52 :     if (local_wallet->IsLocked()) {
    4300   [ +  -  +  +  :          15 :         if (auto unlocked{local_wallet->Unlock(passphrase)}; !unlocked) return util::Error{unlocked.error().message};
                   +  - ]
    4301                 :             :     }
    4302                 :             : 
    4303                 :             :     // Indicates whether the current wallet is empty after migration.
    4304                 :             :     // Notes:
    4305                 :             :     // When non-empty: the local wallet becomes the main spendable wallet.
    4306                 :             :     // When empty: The local wallet is excluded from the result, as the
    4307                 :             :     //             user does not expect an empty spendable wallet after
    4308                 :             :     //             migrating only watch-only scripts.
    4309                 :          49 :     bool empty_local_wallet = false;
    4310                 :             : 
    4311                 :          49 :     {
    4312         [ +  - ]:          49 :         LOCK(local_wallet->cs_wallet);
    4313                 :             :         // First change to using SQLite
    4314   [ +  -  -  +  :          49 :         if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
             -  -  -  - ]
    4315                 :             : 
    4316                 :             :         // Do the migration of keys and scripts for non-empty wallets, and cleanup if it fails
    4317   [ +  -  +  + ]:          49 :         if (HasLegacyRecords(*local_wallet)) {
    4318         [ +  - ]:          46 :             success = DoMigration(*local_wallet, context, error, res, load_wallet);
    4319                 :             :             // No scripts mean empty wallet after migration
    4320         [ +  - ]:          46 :             empty_local_wallet = local_wallet->GetAllScriptPubKeyMans().empty();
    4321                 :             :         } else {
    4322                 :             :             // Make sure that descriptors flag is actually set
    4323         [ +  - ]:           3 :             local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
    4324                 :             :             success = true;
    4325                 :             :         }
    4326                 :           0 :     }
    4327                 :             : 
    4328                 :             :     // In case of loading failure, we need to remember the wallet files we have created to remove.
    4329                 :             :     // A `set` is used as it may be populated with the same wallet directory paths multiple times,
    4330                 :             :     // both before and after loading. This ensures the set is complete even if one of the wallets
    4331                 :             :     // fails to load.
    4332         [ +  + ]:          49 :     std::set<fs::path> wallet_files_to_remove;
    4333                 :          49 :     std::set<fs::path> wallet_empty_dirs_to_remove;
    4334                 :             : 
    4335                 :             :     // Helper to track wallet files and directories for cleanup on failure.
    4336                 :             :     // Only directories of wallets created during migration (not the main wallet) are tracked.
    4337                 :         114 :     auto track_for_cleanup = [&](const CWallet& wallet) {
    4338                 :          65 :         const auto files = wallet.GetDatabase().Files();
    4339         [ +  - ]:          65 :         wallet_files_to_remove.insert(files.begin(), files.end());
    4340         [ +  + ]:          65 :         if (wallet.GetName() != wallet_name) {
    4341                 :             :             // If this isn’t the main wallet, mark its directory for removal.
    4342                 :             :             // This applies to the watch-only and solvable wallets.
    4343                 :             :             // Wallets stored directly as files in the top-level directory
    4344                 :             :             // (e.g. default unnamed wallets) don’t have a removable parent directory.
    4345   [ +  -  +  -  :          95 :             wallet_empty_dirs_to_remove.insert(fs::PathFromString(wallet.GetDatabase().Filename()).parent_path());
             +  -  +  - ]
    4346                 :             :         }
    4347                 :          65 :     };
    4348                 :             : 
    4349                 :             : 
    4350         [ +  + ]:          49 :     if (success) {
    4351         [ +  + ]:          45 :         Assume(!res.wallet); // We will set it here.
    4352                 :             :         // Check if the local wallet is empty after migration
    4353         [ +  + ]:          45 :         if (empty_local_wallet) {
    4354                 :             :             // This wallet has no records. We can safely remove it.
    4355         [ +  - ]:           3 :             std::vector<fs::path> paths_to_remove = local_wallet->GetDatabase().Files();
    4356                 :           3 :             local_wallet.reset();
    4357   [ +  -  +  + ]:           9 :             for (const auto& path_to_remove : paths_to_remove) fs::remove(path_to_remove);
    4358                 :           3 :         }
    4359                 :             : 
    4360         [ +  + ]:          45 :         if (load_wallet) {
    4361         [ +  - ]:          41 :             LogInfo("Loading new wallets after migration...\n");
    4362                 :             :             /** We only override the load_on_startup setting in case the user explicitly said
    4363                 :             :              * that he does not want to load the wallet, otherwise keep the old wallet configuration */
    4364                 :             :         } else {
    4365         [ +  - ]:           4 :             UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/false, warnings);
    4366                 :             :         }
    4367                 :             :         // Migration successful, if load_wallet is set load all the migrated wallets.
    4368                 :          45 :         bool main_wallet_set{false};
    4369         [ +  + ]:         174 :         for (std::shared_ptr<CWallet>* wallet_ptr : {&local_wallet, &res.watchonly_wallet, &res.solvables_wallet}) {
    4370         [ +  + ]:         131 :             if (success && *wallet_ptr) {
    4371                 :          60 :                 std::shared_ptr<CWallet>& wallet = *wallet_ptr;
    4372                 :             :                 // Track db path
    4373         [ +  - ]:          60 :                 track_for_cleanup(*wallet);
    4374         [ -  + ]:          60 :                 assert(wallet.use_count() == 1);
    4375         [ -  + ]:          60 :                 std::string wallet_name = wallet->GetName();
    4376                 :          60 :                 wallet.reset();
    4377         [ +  + ]:          60 :                 if (load_wallet) {
    4378   [ +  -  -  + ]:         108 :                     wallet = LoadWallet(context, wallet_name, /*load_on_start=*/std::nullopt, options, status, error, warnings);
    4379         [ +  + ]:          54 :                     if (!wallet) {
    4380         [ +  - ]:           2 :                         LogError("Failed to load wallet '%s' after migration. Rolling back migration to preserve consistency. "
    4381                 :             :                                  "Error cause: %s\n", wallet_name, error.original);
    4382                 :           2 :                         success = false;
    4383                 :           2 :                         break;
    4384                 :             :                     }
    4385                 :             :                 }
    4386                 :             :                 // Set the first wallet as the main one.
    4387                 :             :                 // The loop order is intentional and must always start with the local wallet.
    4388         [ +  + ]:          58 :                 if (!main_wallet_set) {
    4389         [ +  - ]:          43 :                     res.wallet_name = wallet_name;
    4390         [ +  + ]:          43 :                     if (load_wallet) res.wallet = std::move(wallet);
    4391                 :             :                     main_wallet_set = true;
    4392                 :             :                 }
    4393         [ +  + ]:          58 :                 if (wallet_ptr == &res.watchonly_wallet) {
    4394         [ +  - ]:          12 :                     res.watchonly_wallet_name = wallet_name;
    4395         [ +  + ]:          46 :                 } else if (wallet_ptr == &res.solvables_wallet) {
    4396         [ +  - ]:           6 :                     res.solvables_wallet_name = wallet_name;
    4397                 :             :                 }
    4398                 :          58 :             }
    4399                 :             :         }
    4400                 :             :     }
    4401                 :           2 :     if (!success) {
    4402                 :             :         // Make list of wallets to cleanup
    4403                 :           6 :         std::vector<std::shared_ptr<CWallet>> created_wallets;
    4404   [ +  +  +  - ]:           6 :         if (local_wallet) created_wallets.push_back(std::move(local_wallet));
    4405   [ +  +  +  - ]:           6 :         if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));
    4406   [ -  +  -  - ]:           6 :         if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));
    4407                 :             : 
    4408                 :             :         // Get the directories to remove after unloading
    4409         [ +  + ]:          11 :         for (std::shared_ptr<CWallet>& wallet : created_wallets) {
    4410         [ +  - ]:           5 :             track_for_cleanup(*wallet);
    4411                 :             :         }
    4412                 :             : 
    4413                 :             :         // Unload the wallets
    4414         [ +  + ]:          11 :         for (std::shared_ptr<CWallet>& w : created_wallets) {
    4415         [ -  + ]:           5 :             if (w->HaveChain()) {
    4416                 :             :                 // Unloading for wallets that were loaded for normal use
    4417   [ #  #  #  # ]:           0 :                 if (!RemoveWallet(context, w, /*load_on_start=*/false)) {
    4418   [ #  #  #  # ]:           0 :                     error += _("\nUnable to cleanup failed migration");
    4419         [ #  # ]:           0 :                     return util::Error{error};
    4420                 :             :                 }
    4421         [ #  # ]:           0 :                 WaitForDeleteWallet(std::move(w));
    4422                 :             :             } else {
    4423                 :             :                 // Unloading for wallets in local context
    4424         [ -  + ]:           5 :                 assert(w.use_count() == 1);
    4425                 :           5 :                 w.reset();
    4426                 :             :             }
    4427                 :             :         }
    4428                 :             : 
    4429                 :             :         // First, delete the db files we have created throughout this process and nothing else
    4430         [ +  + ]:          20 :         for (const fs::path& file : wallet_files_to_remove) {
    4431         [ +  - ]:          14 :             fs::remove(file);
    4432                 :             :         }
    4433                 :             : 
    4434                 :             :         // Second, delete the created wallet directories and nothing else. They must be empty at this point.
    4435         [ +  + ]:           7 :         for (const fs::path& dir : wallet_empty_dirs_to_remove) {
    4436   [ +  -  +  - ]:           1 :             Assume(fs::is_empty(dir));
    4437         [ +  - ]:           1 :             fs::remove(dir);
    4438                 :             :         }
    4439                 :             : 
    4440                 :             :         // Restore the backup
    4441                 :             :         // Convert the backup file to the wallet db file by renaming it and moving it into the wallet's directory.
    4442         [ +  - ]:           6 :         bilingual_str restore_error;
    4443         [ +  - ]:           6 :         const auto& ptr_wallet = RestoreWallet(context, backup_path, wallet_name, /*load_on_start=*/std::nullopt, status, restore_error, warnings, /*load_after_restore=*/false, /*allow_unnamed=*/true);
    4444         [ -  + ]:           6 :         if (!restore_error.empty()) {
    4445   [ #  #  #  # ]:           0 :             error += restore_error + _("\nUnable to restore backup of wallet.");
    4446         [ #  # ]:           0 :             return util::Error{error};
    4447                 :             :         }
    4448                 :             :         // Verify that the legacy wallet is not loaded after restoring from the backup.
    4449         [ -  + ]:           6 :         assert(!ptr_wallet);
    4450                 :             : 
    4451         [ +  - ]:          18 :         return util::Error{error};
    4452                 :          12 :     }
    4453                 :          43 :     return res;
    4454                 :         257 : }
    4455                 :             : 
    4456                 :       83271 : void CWallet::CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
    4457                 :             : {
    4458         [ +  + ]:      634991 :     for (const auto& script : spks) {
    4459                 :      551720 :         m_cached_spks[script].push_back(spkm);
    4460                 :             :     }
    4461                 :       83271 : }
    4462                 :             : 
    4463                 :       83271 : void CWallet::TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
    4464                 :             : {
    4465                 :             :     // Update scriptPubKey cache
    4466                 :       83271 :     CacheNewScriptPubKeys(spks, spkm);
    4467                 :       83271 : }
    4468                 :             : 
    4469                 :          82 : CWallet::HDPubKeyMap CWallet::GetHDPubKeys(HDKeyFilter filter) const
    4470                 :             : {
    4471                 :          82 :     AssertLockHeld(cs_wallet);
    4472                 :             : 
    4473                 :          82 :     Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    4474                 :             : 
    4475         [ +  + ]:          82 :     HDPubKeyMap xpubs;
    4476   [ +  +  +  -  :         515 :     for (const auto& spkm : filter == HDKeyFilter::Active ? GetActiveScriptPubKeyMans() : GetAllScriptPubKeyMans()) {
             +  -  +  + ]
    4477   [ +  -  +  - ]:         433 :         auto* desc_spkm = Assert(dynamic_cast<DescriptorScriptPubKeyMan*>(spkm));
    4478         [ +  - ]:         433 :         LOCK(desc_spkm->cs_desc_man);
    4479         [ +  - ]:         433 :         WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();
    4480   [ +  +  +  -  :         433 :         if (filter == HDKeyFilter::UnusedKey && w_desc.descriptor->HasScripts()) continue;
                   +  + ]
    4481                 :             : 
    4482         [ +  - ]:         375 :         std::set<CPubKey> desc_pubkeys;
    4483                 :         375 :         std::set<CExtPubKey> desc_xpubs;
    4484         [ +  - ]:         375 :         w_desc.descriptor->GetPubKeys(desc_pubkeys, desc_xpubs);
    4485         [ +  + ]:         743 :         for (const CExtPubKey& xpub : desc_xpubs) {
    4486   [ +  -  +  - ]:         368 :             xpubs[xpub].insert(desc_spkm);
    4487                 :             :         }
    4488   [ +  -  +  - ]:         866 :     }
    4489                 :          82 :     return xpubs;
    4490                 :           0 : }
    4491                 :             : 
    4492                 :          41 : std::optional<CKey> CWallet::GetKey(const CKeyID& keyid) const
    4493                 :             : {
    4494                 :          41 :     Assert(IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
    4495                 :             : 
    4496         [ +  + ]:          74 :     for (const auto& spkm : GetAllScriptPubKeyMans()) {
    4497         [ +  - ]:          64 :         const DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
    4498         [ -  + ]:          64 :         assert(desc_spkm);
    4499         [ +  - ]:          64 :         LOCK(desc_spkm->cs_desc_man);
    4500   [ +  -  +  + ]:          64 :         if (std::optional<CKey> key = desc_spkm->GetKey(keyid)) {
    4501         [ +  - ]:          31 :             return key;
    4502         [ +  - ]:          33 :         }
    4503                 :          64 :     }
    4504                 :          10 :     return std::nullopt;
    4505                 :             : }
    4506                 :             : 
    4507                 :          18 : std::optional<CExtKey> CWallet::GetExtKey(const CExtPubKey& xpub) const
    4508                 :             : {
    4509         [ +  - ]:          18 :     if (std::optional<CKey> key = GetKey(xpub.pubkey.GetID())) {
    4510         [ +  - ]:          18 :         return CExtKey{xpub, *key};
    4511                 :          18 :     }
    4512                 :           0 :     return std::nullopt;
    4513                 :             : }
    4514                 :             : 
    4515                 :       16858 : void CWallet::WriteBestBlock() const
    4516                 :             : {
    4517                 :       16858 :     AssertLockHeld(cs_wallet);
    4518                 :             : 
    4519         [ +  + ]:       33716 :     if (!m_last_block_processed.IsNull()) {
    4520                 :       16798 :         CBlockLocator loc;
    4521         [ +  - ]:       16798 :         chain().findBlock(m_last_block_processed, FoundBlock().locator(loc));
    4522                 :             : 
    4523         [ +  - ]:       16798 :         if (!loc.IsNull()) {
    4524         [ +  - ]:       16798 :             WalletBatch batch(GetDatabase());
    4525         [ +  - ]:       16798 :             batch.WriteBestBlock(loc);
    4526                 :       16798 :         }
    4527                 :       16798 :     }
    4528                 :       16858 : }
    4529                 :             : 
    4530                 :       44399 : void CWallet::RefreshTXOsFromTx(const CWalletTx& wtx)
    4531                 :             : {
    4532                 :       44399 :     AssertLockHeld(cs_wallet);
    4533   [ -  +  +  -  :      420326 :     for (uint32_t i = 0; i < wtx.GetTx()->vout.size(); ++i) {
                   +  + ]
    4534   [ +  -  +  - ]:      165764 :         const CTxOut& txout = wtx.GetTx()->vout.at(i);
    4535         [ +  + ]:      165764 :         if (!IsMine(txout)) continue;
    4536                 :       65969 :         COutPoint outpoint(wtx.GetHash(), i);
    4537         [ +  + ]:       65969 :         if (m_txos.contains(outpoint)) {
    4538                 :             :         } else {
    4539                 :       48403 :             m_txos.emplace(outpoint, WalletTXO{wtx, txout});
    4540                 :             :         }
    4541                 :             :     }
    4542                 :       44399 : }
    4543                 :             : 
    4544                 :         738 : void CWallet::RefreshAllTXOs()
    4545                 :             : {
    4546                 :         738 :     AssertLockHeld(cs_wallet);
    4547         [ +  + ]:        4435 :     for (const auto& [_, wtx] : mapWallet) {
    4548                 :        3697 :         RefreshTXOsFromTx(wtx);
    4549                 :             :     }
    4550                 :         738 : }
    4551                 :             : 
    4552                 :      205686 : std::optional<WalletTXO> CWallet::GetTXO(const COutPoint& outpoint) const
    4553                 :             : {
    4554                 :      205686 :     AssertLockHeld(cs_wallet);
    4555                 :      205686 :     const auto& it = m_txos.find(outpoint);
    4556         [ +  + ]:      205686 :     if (it == m_txos.end()) {
    4557                 :      194850 :         return std::nullopt;
    4558                 :             :     }
    4559                 :       10836 :     return it->second;
    4560                 :             : }
    4561                 :             : 
    4562                 :        1033 : void CWallet::DisconnectChainNotifications()
    4563                 :             : {
    4564         [ +  + ]:        1033 :     if (m_chain_notifications_handler) {
    4565                 :        1032 :         m_chain_notifications_handler->disconnect();
    4566                 :        1032 :         chain().waitForNotifications();
    4567         [ +  - ]:        1032 :         m_chain_notifications_handler.reset();
    4568                 :             :     }
    4569                 :        1033 : }
    4570                 :             : 
    4571                 :          52 : void CWallet::SetLastDecryptedFeatures(uint64_t features)
    4572                 :             : {
    4573                 :          52 :     AssertLockHeld(cs_wallet);
    4574                 :          52 :     m_last_decrypted_features = features;
    4575                 :          52 : }
    4576                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1