LCOV - code coverage report
Current view: top level - src/wallet - wallet.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 1809 2227 81.2 %
Date: 2021-06-29 14:35:33 Functions: 142 152 93.4 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 746 1022 73.0 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
#       2                 :            : // Copyright (c) 2009-2020 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 <wallet/wallet.h>
#       7                 :            : 
#       8                 :            : #include <chain.h>
#       9                 :            : #include <consensus/consensus.h>
#      10                 :            : #include <consensus/validation.h>
#      11                 :            : #include <fs.h>
#      12                 :            : #include <interfaces/chain.h>
#      13                 :            : #include <interfaces/wallet.h>
#      14                 :            : #include <key.h>
#      15                 :            : #include <key_io.h>
#      16                 :            : #include <outputtype.h>
#      17                 :            : #include <policy/fees.h>
#      18                 :            : #include <policy/policy.h>
#      19                 :            : #include <primitives/block.h>
#      20                 :            : #include <primitives/transaction.h>
#      21                 :            : #include <psbt.h>
#      22                 :            : #include <script/descriptor.h>
#      23                 :            : #include <script/script.h>
#      24                 :            : #include <script/signingprovider.h>
#      25                 :            : #include <txmempool.h>
#      26                 :            : #include <util/bip32.h>
#      27                 :            : #include <util/check.h>
#      28                 :            : #include <util/error.h>
#      29                 :            : #include <util/fees.h>
#      30                 :            : #include <util/moneystr.h>
#      31                 :            : #include <util/rbf.h>
#      32                 :            : #include <util/string.h>
#      33                 :            : #include <util/translation.h>
#      34                 :            : #include <wallet/coincontrol.h>
#      35                 :            : #include <wallet/fees.h>
#      36                 :            : #include <wallet/external_signer_scriptpubkeyman.h>
#      37                 :            : 
#      38                 :            : #include <univalue.h>
#      39                 :            : 
#      40                 :            : #include <algorithm>
#      41                 :            : #include <assert.h>
#      42                 :            : #include <optional>
#      43                 :            : 
#      44                 :            : #include <boost/algorithm/string/replace.hpp>
#      45                 :            : 
#      46                 :            : using interfaces::FoundBlock;
#      47                 :            : 
#      48                 :            : const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS{
#      49                 :            :     {WALLET_FLAG_AVOID_REUSE,
#      50                 :            :         "You need to rescan the blockchain in order to correctly mark used "
#      51                 :            :         "destinations in the past. Until this is done, some destinations may "
#      52                 :            :         "be considered unused, even if the opposite is the case."
#      53                 :            :     },
#      54                 :            : };
#      55                 :            : 
#      56                 :            : RecursiveMutex cs_wallets;
#      57                 :            : static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
#      58                 :            : static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
#      59                 :            : 
#      60                 :            : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
#      61                 :        240 : {
#      62                 :        240 :     util::SettingsValue setting_value = chain.getRwSetting("wallet");
#      63         [ +  + ]:        240 :     if (!setting_value.isArray()) setting_value.setArray();
#      64         [ +  + ]:        240 :     for (const util::SettingsValue& value : setting_value.getValues()) {
#      65 [ +  - ][ +  + ]:         10 :         if (value.isStr() && value.get_str() == wallet_name) return true;
#      66                 :         10 :     }
#      67                 :        240 :     setting_value.push_back(wallet_name);
#      68                 :        236 :     return chain.updateRwSetting("wallet", setting_value);
#      69                 :        240 : }
#      70                 :            : 
#      71                 :            : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
#      72                 :          8 : {
#      73                 :          8 :     util::SettingsValue setting_value = chain.getRwSetting("wallet");
#      74         [ +  + ]:          8 :     if (!setting_value.isArray()) return true;
#      75                 :          7 :     util::SettingsValue new_value(util::SettingsValue::VARR);
#      76         [ +  + ]:         18 :     for (const util::SettingsValue& value : setting_value.getValues()) {
#      77 [ -  + ][ +  + ]:         18 :         if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
#      78                 :         18 :     }
#      79         [ +  + ]:          7 :     if (new_value.size() == setting_value.size()) return true;
#      80                 :          3 :     return chain.updateRwSetting("wallet", new_value);
#      81                 :          3 : }
#      82                 :            : 
#      83                 :            : static void UpdateWalletSetting(interfaces::Chain& chain,
#      84                 :            :                                 const std::string& wallet_name,
#      85                 :            :                                 std::optional<bool> load_on_startup,
#      86                 :            :                                 std::vector<bilingual_str>& warnings)
#      87                 :       1336 : {
#      88         [ +  + ]:       1336 :     if (!load_on_startup) return;
#      89 [ +  + ][ -  + ]:        248 :     if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
#      90                 :          0 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
#      91 [ +  + ][ -  + ]:        248 :     } else if (!load_on_startup.value() && !RemoveWalletSetting(chain, wallet_name)) {
#      92                 :          0 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
#      93                 :          0 :     }
#      94                 :        248 : }
#      95                 :            : 
#      96                 :            : bool AddWallet(const std::shared_ptr<CWallet>& wallet)
#      97                 :        737 : {
#      98                 :        737 :     LOCK(cs_wallets);
#      99                 :        737 :     assert(wallet);
#     100                 :        737 :     std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
#     101         [ -  + ]:        737 :     if (i != vpwallets.end()) return false;
#     102                 :        737 :     vpwallets.push_back(wallet);
#     103                 :        737 :     wallet->ConnectScriptPubKeyManNotifiers();
#     104                 :        737 :     wallet->NotifyCanGetAddressesChanged();
#     105                 :        737 :     return true;
#     106                 :        737 : }
#     107                 :            : 
#     108                 :            : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
#     109                 :        737 : {
#     110                 :        737 :     assert(wallet);
#     111                 :            : 
#     112                 :        737 :     interfaces::Chain& chain = wallet->chain();
#     113                 :        737 :     std::string name = wallet->GetName();
#     114                 :            : 
#     115                 :            :     // Unregister with the validation interface which also drops shared ponters.
#     116                 :        737 :     wallet->m_chain_notifications_handler.reset();
#     117                 :        737 :     LOCK(cs_wallets);
#     118                 :        737 :     std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
#     119         [ -  + ]:        737 :     if (i == vpwallets.end()) return false;
#     120                 :        737 :     vpwallets.erase(i);
#     121                 :            : 
#     122                 :            :     // Write the wallet setting
#     123                 :        737 :     UpdateWalletSetting(chain, name, load_on_start, warnings);
#     124                 :            : 
#     125                 :        737 :     return true;
#     126                 :        737 : }
#     127                 :            : 
#     128                 :            : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
#     129                 :          3 : {
#     130                 :          3 :     std::vector<bilingual_str> warnings;
#     131                 :          3 :     return RemoveWallet(wallet, load_on_start, warnings);
#     132                 :          3 : }
#     133                 :            : 
#     134                 :            : std::vector<std::shared_ptr<CWallet>> GetWallets()
#     135                 :      60060 : {
#     136                 :      60060 :     LOCK(cs_wallets);
#     137                 :      60060 :     return vpwallets;
#     138                 :      60060 : }
#     139                 :            : 
#     140                 :            : std::shared_ptr<CWallet> GetWallet(const std::string& name)
#     141                 :       6467 : {
#     142                 :       6467 :     LOCK(cs_wallets);
#     143         [ +  + ]:      14431 :     for (const std::shared_ptr<CWallet>& wallet : vpwallets) {
#     144         [ +  + ]:      14431 :         if (wallet->GetName() == name) return wallet;
#     145                 :      14431 :     }
#     146                 :       6467 :     return nullptr;
#     147                 :       6467 : }
#     148                 :            : 
#     149                 :            : std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet)
#     150                 :          1 : {
#     151                 :          1 :     LOCK(cs_wallets);
#     152                 :          1 :     auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(), std::move(load_wallet));
#     153                 :          1 :     return interfaces::MakeHandler([it] { LOCK(cs_wallets); g_load_wallet_fns.erase(it); });
#     154                 :          1 : }
#     155                 :            : 
#     156                 :            : static Mutex g_loading_wallet_mutex;
#     157                 :            : static Mutex g_wallet_release_mutex;
#     158                 :            : static std::condition_variable g_wallet_release_cv;
#     159                 :            : static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
#     160                 :            : static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
#     161                 :            : 
#     162                 :            : // Custom deleter for shared_ptr<CWallet>.
#     163                 :            : static void ReleaseWallet(CWallet* wallet)
#     164                 :        745 : {
#     165                 :        745 :     const std::string name = wallet->GetName();
#     166                 :        745 :     wallet->WalletLogPrintf("Releasing wallet\n");
#     167                 :        745 :     wallet->Flush();
#     168                 :        745 :     delete wallet;
#     169                 :            :     // Wallet is now released, notify UnloadWallet, if any.
#     170                 :        745 :     {
#     171                 :        745 :         LOCK(g_wallet_release_mutex);
#     172         [ +  + ]:        745 :         if (g_unloading_wallet_set.erase(name) == 0) {
#     173                 :            :             // UnloadWallet was not called for this wallet, all done.
#     174                 :          6 :             return;
#     175                 :          6 :         }
#     176                 :        739 :     }
#     177                 :        739 :     g_wallet_release_cv.notify_all();
#     178                 :        739 : }
#     179                 :            : 
#     180                 :            : void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
#     181                 :        739 : {
#     182                 :            :     // Mark wallet for unloading.
#     183                 :        739 :     const std::string name = wallet->GetName();
#     184                 :        739 :     {
#     185                 :        739 :         LOCK(g_wallet_release_mutex);
#     186                 :        739 :         auto it = g_unloading_wallet_set.insert(name);
#     187                 :        739 :         assert(it.second);
#     188                 :        739 :     }
#     189                 :            :     // The wallet can be in use so it's not possible to explicitly unload here.
#     190                 :            :     // Notify the unload intent so that all remaining shared pointers are
#     191                 :            :     // released.
#     192                 :        739 :     wallet->NotifyUnload();
#     193                 :            : 
#     194                 :            :     // Time to ditch our shared_ptr and wait for ReleaseWallet call.
#     195                 :        739 :     wallet.reset();
#     196                 :        739 :     {
#     197                 :        739 :         WAIT_LOCK(g_wallet_release_mutex, lock);
#     198         [ -  + ]:        739 :         while (g_unloading_wallet_set.count(name) == 1) {
#     199                 :          0 :             g_wallet_release_cv.wait(lock);
#     200                 :          0 :         }
#     201                 :        739 :     }
#     202                 :        739 : }
#     203                 :            : 
#     204                 :            : namespace {
#     205                 :            : std::shared_ptr<CWallet> LoadWalletInternal(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
#     206                 :        211 : {
#     207                 :        211 :     try {
#     208                 :        211 :         std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
#     209         [ +  + ]:        211 :         if (!database) {
#     210                 :         19 :             error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
#     211                 :         19 :             return nullptr;
#     212                 :         19 :         }
#     213                 :            : 
#     214                 :        192 :         chain.initMessage(_("Loading wallet…").translated);
#     215                 :        192 :         std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), options.create_flags, error, warnings);
#     216         [ -  + ]:        192 :         if (!wallet) {
#     217                 :          0 :             error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
#     218                 :          0 :             status = DatabaseStatus::FAILED_LOAD;
#     219                 :          0 :             return nullptr;
#     220                 :          0 :         }
#     221                 :        192 :         AddWallet(wallet);
#     222                 :        192 :         wallet->postInitProcess();
#     223                 :            : 
#     224                 :            :         // Write the wallet setting
#     225                 :        192 :         UpdateWalletSetting(chain, name, load_on_start, warnings);
#     226                 :            : 
#     227                 :        192 :         return wallet;
#     228                 :        192 :     } catch (const std::runtime_error& e) {
#     229                 :          4 :         error = Untranslated(e.what());
#     230                 :          4 :         status = DatabaseStatus::FAILED_LOAD;
#     231                 :          4 :         return nullptr;
#     232                 :          4 :     }
#     233                 :        211 : }
#     234                 :            : } // namespace
#     235                 :            : 
#     236                 :            : std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
#     237                 :        217 : {
#     238                 :        217 :     auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
#     239         [ +  + ]:        217 :     if (!result.second) {
#     240                 :          6 :         error = Untranslated("Wallet already loading.");
#     241                 :          6 :         status = DatabaseStatus::FAILED_LOAD;
#     242                 :          6 :         return nullptr;
#     243                 :          6 :     }
#     244                 :        211 :     auto wallet = LoadWalletInternal(chain, name, load_on_start, options, status, error, warnings);
#     245                 :        211 :     WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
#     246                 :        211 :     return wallet;
#     247                 :        211 : }
#     248                 :            : 
#     249                 :            : std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
#     250                 :        420 : {
#     251                 :        420 :     uint64_t wallet_creation_flags = options.create_flags;
#     252                 :        420 :     const SecureString& passphrase = options.create_passphrase;
#     253                 :            : 
#     254         [ +  + ]:        420 :     if (wallet_creation_flags & WALLET_FLAG_DESCRIPTORS) options.require_format = DatabaseFormat::SQLITE;
#     255                 :            : 
#     256                 :            :     // Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
#     257                 :        420 :     bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
#     258                 :            : 
#     259                 :            :     // Born encrypted wallets need to be created blank first.
#     260         [ +  + ]:        420 :     if (!passphrase.empty()) {
#     261                 :         10 :         wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
#     262                 :         10 :     }
#     263                 :            : 
#     264                 :            :     // Private keys must be disabled for an external signer wallet
#     265 [ -  + ][ #  # ]:        420 :     if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#     266                 :          0 :         error = Untranslated("Private keys must be disabled when using an external signer");
#     267                 :          0 :         status = DatabaseStatus::FAILED_CREATE;
#     268                 :          0 :         return nullptr;
#     269                 :          0 :     }
#     270                 :            : 
#     271                 :            :     // Descriptor support must be enabled for an external signer wallet
#     272 [ -  + ][ #  # ]:        420 :     if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS)) {
#     273                 :          0 :         error = Untranslated("Descriptor support must be enabled when using an external signer");
#     274                 :          0 :         status = DatabaseStatus::FAILED_CREATE;
#     275                 :          0 :         return nullptr;
#     276                 :          0 :     }
#     277                 :            : 
#     278                 :            :     // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
#     279                 :        420 :     std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
#     280         [ +  + ]:        420 :     if (!database) {
#     281                 :          4 :         error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
#     282                 :          4 :         status = DatabaseStatus::FAILED_VERIFY;
#     283                 :          4 :         return nullptr;
#     284                 :          4 :     }
#     285                 :            : 
#     286                 :            :     // Do not allow a passphrase when private keys are disabled
#     287 [ +  + ][ +  + ]:        416 :     if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#     288                 :          3 :         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.");
#     289                 :          3 :         status = DatabaseStatus::FAILED_CREATE;
#     290                 :          3 :         return nullptr;
#     291                 :          3 :     }
#     292                 :            : 
#     293                 :            :     // Make the wallet
#     294                 :        413 :     chain.initMessage(_("Loading wallet…").translated);
#     295                 :        413 :     std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), wallet_creation_flags, error, warnings);
#     296         [ -  + ]:        413 :     if (!wallet) {
#     297                 :          0 :         error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
#     298                 :          0 :         status = DatabaseStatus::FAILED_CREATE;
#     299                 :          0 :         return nullptr;
#     300                 :          0 :     }
#     301                 :            : 
#     302                 :            :     // Encrypt the wallet
#     303 [ +  + ][ +  - ]:        413 :     if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#     304         [ -  + ]:          7 :         if (!wallet->EncryptWallet(passphrase)) {
#     305                 :          0 :             error = Untranslated("Error: Wallet created but failed to encrypt.");
#     306                 :          0 :             status = DatabaseStatus::FAILED_ENCRYPT;
#     307                 :          0 :             return nullptr;
#     308                 :          0 :         }
#     309         [ +  + ]:          7 :         if (!create_blank) {
#     310                 :            :             // Unlock the wallet
#     311         [ -  + ]:          4 :             if (!wallet->Unlock(passphrase)) {
#     312                 :          0 :                 error = Untranslated("Error: Wallet was encrypted but could not be unlocked");
#     313                 :          0 :                 status = DatabaseStatus::FAILED_ENCRYPT;
#     314                 :          0 :                 return nullptr;
#     315                 :          0 :             }
#     316                 :            : 
#     317                 :            :             // Set a seed for the wallet
#     318                 :          4 :             {
#     319                 :          4 :                 LOCK(wallet->cs_wallet);
#     320         [ +  + ]:          4 :                 if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#     321                 :          2 :                     wallet->SetupDescriptorScriptPubKeyMans();
#     322                 :          2 :                 } else {
#     323         [ +  + ]:          2 :                     for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
#     324         [ -  + ]:          2 :                         if (!spk_man->SetupGeneration()) {
#     325                 :          0 :                             error = Untranslated("Unable to generate initial keys");
#     326                 :          0 :                             status = DatabaseStatus::FAILED_CREATE;
#     327                 :          0 :                             return nullptr;
#     328                 :          0 :                         }
#     329                 :          2 :                     }
#     330                 :          2 :                 }
#     331                 :          4 :             }
#     332                 :            : 
#     333                 :            :             // Relock the wallet
#     334                 :          4 :             wallet->Lock();
#     335                 :          4 :         }
#     336                 :          7 :     }
#     337                 :        413 :     AddWallet(wallet);
#     338                 :        413 :     wallet->postInitProcess();
#     339                 :            : 
#     340                 :            :     // Write the wallet settings
#     341                 :        413 :     UpdateWalletSetting(chain, name, load_on_start, warnings);
#     342                 :            : 
#     343                 :        413 :     status = DatabaseStatus::SUCCESS;
#     344                 :        413 :     return wallet;
#     345                 :        413 : }
#     346                 :            : 
#     347                 :            : /** @defgroup mapWallet
#     348                 :            :  *
#     349                 :            :  * @{
#     350                 :            :  */
#     351                 :            : 
#     352                 :            : const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
#     353                 :     188292 : {
#     354                 :     188292 :     AssertLockHeld(cs_wallet);
#     355                 :     188292 :     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
#     356         [ +  + ]:     188292 :     if (it == mapWallet.end())
#     357                 :        390 :         return nullptr;
#     358                 :     187902 :     return &(it->second);
#     359                 :     187902 : }
#     360                 :            : 
#     361                 :            : void CWallet::UpgradeKeyMetadata()
#     362                 :        868 : {
#     363 [ +  + ][ +  + ]:        868 :     if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
#     364                 :        166 :         return;
#     365                 :        166 :     }
#     366                 :            : 
#     367                 :        702 :     auto spk_man = GetLegacyScriptPubKeyMan();
#     368         [ +  + ]:        702 :     if (!spk_man) {
#     369                 :        589 :         return;
#     370                 :        589 :     }
#     371                 :            : 
#     372                 :        113 :     spk_man->UpgradeKeyMetadata();
#     373                 :        113 :     SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
#     374                 :        113 : }
#     375                 :            : 
#     376                 :            : bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
#     377                 :         92 : {
#     378                 :         92 :     CCrypter crypter;
#     379                 :         92 :     CKeyingMaterial _vMasterKey;
#     380                 :            : 
#     381                 :         92 :     {
#     382                 :         92 :         LOCK(cs_wallet);
#     383         [ +  + ]:         92 :         for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
#     384                 :         92 :         {
#     385         [ -  + ]:         92 :             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
#     386                 :          0 :                 return false;
#     387         [ +  + ]:         92 :             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
#     388                 :          4 :                 continue; // try another master key
#     389         [ +  - ]:         88 :             if (Unlock(_vMasterKey, accept_no_keys)) {
#     390                 :            :                 // Now that we've unlocked, upgrade the key metadata
#     391                 :         88 :                 UpgradeKeyMetadata();
#     392                 :         88 :                 return true;
#     393                 :         88 :             }
#     394                 :         88 :         }
#     395                 :         92 :     }
#     396                 :         92 :     return false;
#     397                 :         92 : }
#     398                 :            : 
#     399                 :            : bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
#     400                 :          2 : {
#     401                 :          2 :     bool fWasLocked = IsLocked();
#     402                 :            : 
#     403                 :          2 :     {
#     404                 :          2 :         LOCK(cs_wallet);
#     405                 :          2 :         Lock();
#     406                 :            : 
#     407                 :          2 :         CCrypter crypter;
#     408                 :          2 :         CKeyingMaterial _vMasterKey;
#     409         [ +  - ]:          2 :         for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
#     410                 :          2 :         {
#     411         [ -  + ]:          2 :             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
#     412                 :          0 :                 return false;
#     413         [ -  + ]:          2 :             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
#     414                 :          0 :                 return false;
#     415         [ +  - ]:          2 :             if (Unlock(_vMasterKey))
#     416                 :          2 :             {
#     417                 :          2 :                 int64_t nStartTime = GetTimeMillis();
#     418                 :          2 :                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
#     419                 :          2 :                 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
#     420                 :            : 
#     421                 :          2 :                 nStartTime = GetTimeMillis();
#     422                 :          2 :                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
#     423                 :          2 :                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
#     424                 :            : 
#     425         [ -  + ]:          2 :                 if (pMasterKey.second.nDeriveIterations < 25000)
#     426                 :          0 :                     pMasterKey.second.nDeriveIterations = 25000;
#     427                 :            : 
#     428                 :          2 :                 WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
#     429                 :            : 
#     430         [ -  + ]:          2 :                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
#     431                 :          0 :                     return false;
#     432         [ -  + ]:          2 :                 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
#     433                 :          0 :                     return false;
#     434                 :          2 :                 WalletBatch(GetDatabase()).WriteMasterKey(pMasterKey.first, pMasterKey.second);
#     435         [ +  - ]:          2 :                 if (fWasLocked)
#     436                 :          2 :                     Lock();
#     437                 :          2 :                 return true;
#     438                 :          2 :             }
#     439                 :          2 :         }
#     440                 :          2 :     }
#     441                 :            : 
#     442                 :          2 :     return false;
#     443                 :          2 : }
#     444                 :            : 
#     445                 :            : void CWallet::chainStateFlushed(const CBlockLocator& loc)
#     446                 :       1347 : {
#     447                 :       1347 :     WalletBatch batch(GetDatabase());
#     448                 :       1347 :     batch.WriteBestBlock(loc);
#     449                 :       1347 : }
#     450                 :            : 
#     451                 :            : void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in)
#     452                 :      23711 : {
#     453                 :      23711 :     LOCK(cs_wallet);
#     454         [ +  + ]:      23711 :     if (nWalletVersion >= nVersion)
#     455                 :      23294 :         return;
#     456                 :        417 :     nWalletVersion = nVersion;
#     457                 :            : 
#     458                 :        417 :     {
#     459         [ -  + ]:        417 :         WalletBatch* batch = batch_in ? batch_in : new WalletBatch(GetDatabase());
#     460         [ +  - ]:        417 :         if (nWalletVersion > 40000)
#     461                 :        417 :             batch->WriteMinVersion(nWalletVersion);
#     462         [ +  - ]:        417 :         if (!batch_in)
#     463                 :        417 :             delete batch;
#     464                 :        417 :     }
#     465                 :        417 : }
#     466                 :            : 
#     467                 :            : std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
#     468                 :       3181 : {
#     469                 :       3181 :     std::set<uint256> result;
#     470                 :       3181 :     AssertLockHeld(cs_wallet);
#     471                 :            : 
#     472                 :       3181 :     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
#     473         [ -  + ]:       3181 :     if (it == mapWallet.end())
#     474                 :          0 :         return result;
#     475                 :       3181 :     const CWalletTx& wtx = it->second;
#     476                 :            : 
#     477                 :       3181 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
#     478                 :            : 
#     479         [ +  + ]:       3181 :     for (const CTxIn& txin : wtx.tx->vin)
#     480                 :       3796 :     {
#     481         [ +  + ]:       3796 :         if (mapTxSpends.count(txin.prevout) <= 1)
#     482                 :       3736 :             continue;  // No conflict if zero or one spends
#     483                 :         60 :         range = mapTxSpends.equal_range(txin.prevout);
#     484         [ +  + ]:        290 :         for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
#     485                 :        230 :             result.insert(_it->second);
#     486                 :         60 :     }
#     487                 :       3181 :     return result;
#     488                 :       3181 : }
#     489                 :            : 
#     490                 :            : bool CWallet::HasWalletSpend(const uint256& txid) const
#     491                 :        318 : {
#     492                 :        318 :     AssertLockHeld(cs_wallet);
#     493                 :        318 :     auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
#     494 [ +  + ][ +  + ]:        318 :     return (iter != mapTxSpends.end() && iter->first.hash == txid);
#     495                 :        318 : }
#     496                 :            : 
#     497                 :            : void CWallet::Flush()
#     498                 :       1322 : {
#     499                 :       1322 :     GetDatabase().Flush();
#     500                 :       1322 : }
#     501                 :            : 
#     502                 :            : void CWallet::Close()
#     503                 :        621 : {
#     504                 :        621 :     GetDatabase().Close();
#     505                 :        621 : }
#     506                 :            : 
#     507                 :            : void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
#     508                 :      21662 : {
#     509                 :            :     // We want all the wallet transactions in range to have the same metadata as
#     510                 :            :     // the oldest (smallest nOrderPos).
#     511                 :            :     // So: find smallest nOrderPos:
#     512                 :            : 
#     513                 :      21662 :     int nMinOrderPos = std::numeric_limits<int>::max();
#     514                 :      21662 :     const CWalletTx* copyFrom = nullptr;
#     515         [ +  + ]:      46739 :     for (TxSpends::iterator it = range.first; it != range.second; ++it) {
#     516                 :      25077 :         const CWalletTx* wtx = &mapWallet.at(it->second);
#     517         [ +  + ]:      25077 :         if (wtx->nOrderPos < nMinOrderPos) {
#     518                 :      21714 :             nMinOrderPos = wtx->nOrderPos;
#     519                 :      21714 :             copyFrom = wtx;
#     520                 :      21714 :         }
#     521                 :      25077 :     }
#     522                 :            : 
#     523         [ -  + ]:      21662 :     if (!copyFrom) {
#     524                 :          0 :         return;
#     525                 :          0 :     }
#     526                 :            : 
#     527                 :            :     // Now copy data from copyFrom to rest:
#     528         [ +  + ]:      46739 :     for (TxSpends::iterator it = range.first; it != range.second; ++it)
#     529                 :      25077 :     {
#     530                 :      25077 :         const uint256& hash = it->second;
#     531                 :      25077 :         CWalletTx* copyTo = &mapWallet.at(hash);
#     532         [ +  + ]:      25077 :         if (copyFrom == copyTo) continue;
#     533                 :       3415 :         assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
#     534         [ +  + ]:       3415 :         if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
#     535                 :          3 :         copyTo->mapValue = copyFrom->mapValue;
#     536                 :          3 :         copyTo->vOrderForm = copyFrom->vOrderForm;
#     537                 :            :         // fTimeReceivedIsTxTime not copied on purpose
#     538                 :            :         // nTimeReceived not copied on purpose
#     539                 :          3 :         copyTo->nTimeSmart = copyFrom->nTimeSmart;
#     540                 :          3 :         copyTo->fFromMe = copyFrom->fFromMe;
#     541                 :            :         // nOrderPos not copied on purpose
#     542                 :            :         // cached members not copied on purpose
#     543                 :          3 :     }
#     544                 :      21662 : }
#     545                 :            : 
#     546                 :            : /**
#     547                 :            :  * Outpoint is spent if any non-conflicted transaction
#     548                 :            :  * spends it:
#     549                 :            :  */
#     550                 :            : bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
#     551                 :    1861166 : {
#     552                 :    1861166 :     const COutPoint outpoint(hash, n);
#     553                 :    1861166 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
#     554                 :    1861166 :     range = mapTxSpends.equal_range(outpoint);
#     555                 :            : 
#     556         [ +  + ]:    1864062 :     for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
#     557                 :    1022547 :     {
#     558                 :    1022547 :         const uint256& wtxid = it->second;
#     559                 :    1022547 :         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
#     560         [ +  - ]:    1022547 :         if (mit != mapWallet.end()) {
#     561                 :    1022547 :             int depth = mit->second.GetDepthInMainChain();
#     562 [ +  + ][ +  + ]:    1022547 :             if (depth > 0  || (depth == 0 && !mit->second.isAbandoned()))
#                 [ +  + ]
#     563                 :    1019651 :                 return true; // Spent
#     564                 :    1022547 :         }
#     565                 :    1022547 :     }
#     566                 :    1861166 :     return false;
#     567                 :    1861166 : }
#     568                 :            : 
#     569                 :            : void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
#     570                 :      21662 : {
#     571                 :      21662 :     mapTxSpends.insert(std::make_pair(outpoint, wtxid));
#     572                 :            : 
#     573                 :      21662 :     setLockedCoins.erase(outpoint);
#     574                 :            : 
#     575                 :      21662 :     std::pair<TxSpends::iterator, TxSpends::iterator> range;
#     576                 :      21662 :     range = mapTxSpends.equal_range(outpoint);
#     577                 :      21662 :     SyncMetaData(range);
#     578                 :      21662 : }
#     579                 :            : 
#     580                 :            : 
#     581                 :            : void CWallet::AddToSpends(const uint256& wtxid)
#     582                 :     147955 : {
#     583                 :     147955 :     auto it = mapWallet.find(wtxid);
#     584                 :     147955 :     assert(it != mapWallet.end());
#     585                 :     147955 :     const CWalletTx& thisTx = it->second;
#     586         [ +  + ]:     147955 :     if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
#     587                 :      30035 :         return;
#     588                 :            : 
#     589         [ +  + ]:     117920 :     for (const CTxIn& txin : thisTx.tx->vin)
#     590                 :      21662 :         AddToSpends(txin.prevout, wtxid);
#     591                 :     117920 : }
#     592                 :            : 
#     593                 :            : bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
#     594                 :         27 : {
#     595         [ -  + ]:         27 :     if (IsCrypted())
#     596                 :          0 :         return false;
#     597                 :            : 
#     598                 :         27 :     CKeyingMaterial _vMasterKey;
#     599                 :            : 
#     600                 :         27 :     _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
#     601                 :         27 :     GetStrongRandBytes(_vMasterKey.data(), WALLET_CRYPTO_KEY_SIZE);
#     602                 :            : 
#     603                 :         27 :     CMasterKey kMasterKey;
#     604                 :            : 
#     605                 :         27 :     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
#     606                 :         27 :     GetStrongRandBytes(kMasterKey.vchSalt.data(), WALLET_CRYPTO_SALT_SIZE);
#     607                 :            : 
#     608                 :         27 :     CCrypter crypter;
#     609                 :         27 :     int64_t nStartTime = GetTimeMillis();
#     610                 :         27 :     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
#     611                 :         27 :     kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
#     612                 :            : 
#     613                 :         27 :     nStartTime = GetTimeMillis();
#     614                 :         27 :     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
#     615                 :         27 :     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
#     616                 :            : 
#     617         [ -  + ]:         27 :     if (kMasterKey.nDeriveIterations < 25000)
#     618                 :          0 :         kMasterKey.nDeriveIterations = 25000;
#     619                 :            : 
#     620                 :         27 :     WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
#     621                 :            : 
#     622         [ -  + ]:         27 :     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
#     623                 :          0 :         return false;
#     624         [ -  + ]:         27 :     if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
#     625                 :          0 :         return false;
#     626                 :            : 
#     627                 :         27 :     {
#     628                 :         27 :         LOCK(cs_wallet);
#     629                 :         27 :         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
#     630                 :         27 :         WalletBatch* encrypted_batch = new WalletBatch(GetDatabase());
#     631         [ -  + ]:         27 :         if (!encrypted_batch->TxnBegin()) {
#     632                 :          0 :             delete encrypted_batch;
#     633                 :          0 :             encrypted_batch = nullptr;
#     634                 :          0 :             return false;
#     635                 :          0 :         }
#     636                 :         27 :         encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
#     637                 :            : 
#     638         [ +  + ]:         63 :         for (const auto& spk_man_pair : m_spk_managers) {
#     639                 :         63 :             auto spk_man = spk_man_pair.second.get();
#     640         [ -  + ]:         63 :             if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
#     641                 :          0 :                 encrypted_batch->TxnAbort();
#     642                 :          0 :                 delete encrypted_batch;
#     643                 :          0 :                 encrypted_batch = nullptr;
#     644                 :            :                 // We now probably have half of our keys encrypted in memory, and half not...
#     645                 :            :                 // die and let the user reload the unencrypted wallet.
#     646                 :          0 :                 assert(false);
#     647                 :          0 :             }
#     648                 :         63 :         }
#     649                 :            : 
#     650                 :            :         // Encryption was introduced in version 0.4.0
#     651                 :         27 :         SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch);
#     652                 :            : 
#     653         [ -  + ]:         27 :         if (!encrypted_batch->TxnCommit()) {
#     654                 :          0 :             delete encrypted_batch;
#     655                 :          0 :             encrypted_batch = nullptr;
#     656                 :            :             // We now have keys encrypted in memory, but not on disk...
#     657                 :            :             // die to avoid confusion and let the user reload the unencrypted wallet.
#     658                 :          0 :             assert(false);
#     659                 :          0 :         }
#     660                 :            : 
#     661                 :         27 :         delete encrypted_batch;
#     662                 :         27 :         encrypted_batch = nullptr;
#     663                 :            : 
#     664                 :         27 :         Lock();
#     665                 :         27 :         Unlock(strWalletPassphrase);
#     666                 :            : 
#     667                 :            :         // If we are using descriptors, make new descriptors with a new seed
#     668 [ +  + ][ +  + ]:         27 :         if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)) {
#     669                 :          7 :             SetupDescriptorScriptPubKeyMans();
#     670         [ +  + ]:         20 :         } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
#     671                 :            :             // if we are using HD, replace the HD seed with a new one
#     672         [ +  + ]:         16 :             if (spk_man->IsHDEnabled()) {
#     673         [ -  + ]:         10 :                 if (!spk_man->SetupGeneration(true)) {
#     674                 :          0 :                     return false;
#     675                 :          0 :                 }
#     676                 :         27 :             }
#     677                 :         16 :         }
#     678                 :         27 :         Lock();
#     679                 :            : 
#     680                 :            :         // Need to completely rewrite the wallet file; if we don't, bdb might keep
#     681                 :            :         // bits of the unencrypted private key in slack space in the database file.
#     682                 :         27 :         GetDatabase().Rewrite();
#     683                 :            : 
#     684                 :            :         // BDB seems to have a bad habit of writing old data into
#     685                 :            :         // slack space in .dat files; that is bad if the old data is
#     686                 :            :         // unencrypted private keys. So:
#     687                 :         27 :         GetDatabase().ReloadDbEnv();
#     688                 :            : 
#     689                 :         27 :     }
#     690                 :         27 :     NotifyStatusChanged(this);
#     691                 :            : 
#     692                 :         27 :     return true;
#     693                 :         27 : }
#     694                 :            : 
#     695                 :            : DBErrors CWallet::ReorderTransactions()
#     696                 :          0 : {
#     697                 :          0 :     LOCK(cs_wallet);
#     698                 :          0 :     WalletBatch batch(GetDatabase());
#     699                 :            : 
#     700                 :            :     // Old wallets didn't have any defined order for transactions
#     701                 :            :     // Probably a bad idea to change the output of this
#     702                 :            : 
#     703                 :            :     // First: get all CWalletTx into a sorted-by-time multimap.
#     704                 :          0 :     typedef std::multimap<int64_t, CWalletTx*> TxItems;
#     705                 :          0 :     TxItems txByTime;
#     706                 :            : 
#     707         [ #  # ]:          0 :     for (auto& entry : mapWallet)
#     708                 :          0 :     {
#     709                 :          0 :         CWalletTx* wtx = &entry.second;
#     710                 :          0 :         txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
#     711                 :          0 :     }
#     712                 :            : 
#     713                 :          0 :     nOrderPosNext = 0;
#     714                 :          0 :     std::vector<int64_t> nOrderPosOffsets;
#     715         [ #  # ]:          0 :     for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
#     716                 :          0 :     {
#     717                 :          0 :         CWalletTx *const pwtx = (*it).second;
#     718                 :          0 :         int64_t& nOrderPos = pwtx->nOrderPos;
#     719                 :            : 
#     720         [ #  # ]:          0 :         if (nOrderPos == -1)
#     721                 :          0 :         {
#     722                 :          0 :             nOrderPos = nOrderPosNext++;
#     723                 :          0 :             nOrderPosOffsets.push_back(nOrderPos);
#     724                 :            : 
#     725         [ #  # ]:          0 :             if (!batch.WriteTx(*pwtx))
#     726                 :          0 :                 return DBErrors::LOAD_FAIL;
#     727                 :          0 :         }
#     728                 :          0 :         else
#     729                 :          0 :         {
#     730                 :          0 :             int64_t nOrderPosOff = 0;
#     731         [ #  # ]:          0 :             for (const int64_t& nOffsetStart : nOrderPosOffsets)
#     732                 :          0 :             {
#     733         [ #  # ]:          0 :                 if (nOrderPos >= nOffsetStart)
#     734                 :          0 :                     ++nOrderPosOff;
#     735                 :          0 :             }
#     736                 :          0 :             nOrderPos += nOrderPosOff;
#     737                 :          0 :             nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
#     738                 :            : 
#     739         [ #  # ]:          0 :             if (!nOrderPosOff)
#     740                 :          0 :                 continue;
#     741                 :            : 
#     742                 :            :             // Since we're changing the order, write it back
#     743         [ #  # ]:          0 :             if (!batch.WriteTx(*pwtx))
#     744                 :          0 :                 return DBErrors::LOAD_FAIL;
#     745                 :          0 :         }
#     746                 :          0 :     }
#     747                 :          0 :     batch.WriteOrderPosNext(nOrderPosNext);
#     748                 :            : 
#     749                 :          0 :     return DBErrors::LOAD_OK;
#     750                 :          0 : }
#     751                 :            : 
#     752                 :            : int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
#     753                 :     138063 : {
#     754                 :     138063 :     AssertLockHeld(cs_wallet);
#     755                 :     138063 :     int64_t nRet = nOrderPosNext++;
#     756         [ +  - ]:     138063 :     if (batch) {
#     757                 :     138063 :         batch->WriteOrderPosNext(nOrderPosNext);
#     758                 :     138063 :     } else {
#     759                 :          0 :         WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
#     760                 :          0 :     }
#     761                 :     138063 :     return nRet;
#     762                 :     138063 : }
#     763                 :            : 
#     764                 :            : void CWallet::MarkDirty()
#     765                 :        455 : {
#     766                 :        455 :     {
#     767                 :        455 :         LOCK(cs_wallet);
#     768         [ +  + ]:        455 :         for (std::pair<const uint256, CWalletTx>& item : mapWallet)
#     769                 :      21716 :             item.second.MarkDirty();
#     770                 :        455 :     }
#     771                 :        455 : }
#     772                 :            : 
#     773                 :            : bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
#     774                 :        140 : {
#     775                 :        140 :     LOCK(cs_wallet);
#     776                 :            : 
#     777                 :        140 :     auto mi = mapWallet.find(originalHash);
#     778                 :            : 
#     779                 :            :     // There is a bug if MarkReplaced is not called on an existing wallet transaction.
#     780                 :        140 :     assert(mi != mapWallet.end());
#     781                 :            : 
#     782                 :        140 :     CWalletTx& wtx = (*mi).second;
#     783                 :            : 
#     784                 :            :     // Ensure for now that we're not overwriting data
#     785                 :        140 :     assert(wtx.mapValue.count("replaced_by_txid") == 0);
#     786                 :            : 
#     787                 :        140 :     wtx.mapValue["replaced_by_txid"] = newHash.ToString();
#     788                 :            : 
#     789                 :            :     // Refresh mempool status without waiting for transactionRemovedFromMempool
#     790                 :            :     // notification so the wallet is in an internally consistent state and
#     791                 :            :     // immediately knows the old transaction should not be considered trusted
#     792                 :            :     // and is eligible to be abandoned
#     793                 :        140 :     wtx.fInMempool = chain().isInMempool(originalHash);
#     794                 :            : 
#     795                 :        140 :     WalletBatch batch(GetDatabase());
#     796                 :            : 
#     797                 :        140 :     bool success = true;
#     798         [ -  + ]:        140 :     if (!batch.WriteTx(wtx)) {
#     799                 :          0 :         WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
#     800                 :          0 :         success = false;
#     801                 :          0 :     }
#     802                 :            : 
#     803                 :        140 :     NotifyTransactionChanged(this, originalHash, CT_UPDATED);
#     804                 :            : 
#     805                 :        140 :     return success;
#     806                 :        140 : }
#     807                 :            : 
#     808                 :            : void CWallet::SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
#     809                 :       4020 : {
#     810                 :       4020 :     AssertLockHeld(cs_wallet);
#     811                 :       4020 :     const CWalletTx* srctx = GetWalletTx(hash);
#     812         [ +  + ]:       4020 :     if (!srctx) return;
#     813                 :            : 
#     814                 :       3730 :     CTxDestination dst;
#     815         [ +  - ]:       3730 :     if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
#     816         [ +  + ]:       3730 :         if (IsMine(dst)) {
#     817 [ +  - ][ +  + ]:       2434 :             if (used && !GetDestData(dst, "used", nullptr)) {
#                 [ +  + ]
#     818         [ +  - ]:         43 :                 if (AddDestData(batch, dst, "used", "p")) { // p for "present", opposite of absent (null)
#     819                 :         43 :                     tx_destinations.insert(dst);
#     820                 :         43 :                 }
#     821 [ -  + ][ -  + ]:       2391 :             } else if (!used && GetDestData(dst, "used", nullptr)) {
#                 [ #  # ]
#     822                 :          0 :                 EraseDestData(batch, dst, "used");
#     823                 :          0 :             }
#     824                 :       2434 :         }
#     825                 :       3730 :     }
#     826                 :       3730 : }
#     827                 :            : 
#     828                 :            : bool CWallet::IsSpentKey(const uint256& hash, unsigned int n) const
#     829                 :       2010 : {
#     830                 :       2010 :     AssertLockHeld(cs_wallet);
#     831                 :       2010 :     const CWalletTx* srctx = GetWalletTx(hash);
#     832         [ +  - ]:       2010 :     if (srctx) {
#     833                 :       2010 :         assert(srctx->tx->vout.size() > n);
#     834                 :       2010 :         CTxDestination dest;
#     835         [ +  + ]:       2010 :         if (!ExtractDestination(srctx->tx->vout[n].scriptPubKey, dest)) {
#     836                 :        400 :             return false;
#     837                 :        400 :         }
#     838         [ +  + ]:       1610 :         if (GetDestData(dest, "used", nullptr)) {
#     839                 :         18 :             return true;
#     840                 :         18 :         }
#     841         [ +  + ]:       1592 :         if (IsLegacy()) {
#     842                 :        833 :             LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
#     843                 :        833 :             assert(spk_man != nullptr);
#     844         [ +  + ]:        833 :             for (const auto& keyid : GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
#     845                 :        579 :                 WitnessV0KeyHash wpkh_dest(keyid);
#     846         [ -  + ]:        579 :                 if (GetDestData(wpkh_dest, "used", nullptr)) {
#     847                 :          0 :                     return true;
#     848                 :          0 :                 }
#     849                 :        579 :                 ScriptHash sh_wpkh_dest(GetScriptForDestination(wpkh_dest));
#     850         [ -  + ]:        579 :                 if (GetDestData(sh_wpkh_dest, "used", nullptr)) {
#     851                 :          0 :                     return true;
#     852                 :          0 :                 }
#     853                 :        579 :                 PKHash pkh_dest(keyid);
#     854         [ +  + ]:        579 :                 if (GetDestData(pkh_dest, "used", nullptr)) {
#     855                 :         12 :                     return true;
#     856                 :         12 :                 }
#     857                 :        579 :             }
#     858                 :        833 :         }
#     859                 :       1592 :     }
#     860                 :       2010 :     return false;
#     861                 :       2010 : }
#     862                 :            : 
#     863                 :            : CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose)
#     864                 :     164929 : {
#     865                 :     164929 :     LOCK(cs_wallet);
#     866                 :            : 
#     867                 :     164929 :     WalletBatch batch(GetDatabase(), fFlushOnClose);
#     868                 :            : 
#     869                 :     164929 :     uint256 hash = tx->GetHash();
#     870                 :            : 
#     871         [ +  + ]:     164929 :     if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
#     872                 :            :         // Mark used destinations
#     873                 :       1668 :         std::set<CTxDestination> tx_destinations;
#     874                 :            : 
#     875         [ +  + ]:       4020 :         for (const CTxIn& txin : tx->vin) {
#     876                 :       4020 :             const COutPoint& op = txin.prevout;
#     877                 :       4020 :             SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
#     878                 :       4020 :         }
#     879                 :            : 
#     880                 :       1668 :         MarkDestinationsDirty(tx_destinations);
#     881                 :       1668 :     }
#     882                 :            : 
#     883                 :            :     // Inserts only if not already there, returns tx inserted or tx found
#     884                 :     164929 :     auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, tx));
#     885                 :     164929 :     CWalletTx& wtx = (*ret.first).second;
#     886                 :     164929 :     bool fInsertedNew = ret.second;
#     887 [ +  + ][ +  - ]:     164929 :     bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
#     888         [ +  + ]:     164929 :     if (fInsertedNew) {
#     889                 :     138063 :         wtx.m_confirm = confirm;
#     890                 :     138063 :         wtx.nTimeReceived = chain().getAdjustedTime();
#     891                 :     138063 :         wtx.nOrderPos = IncOrderPosNext(&batch);
#     892                 :     138063 :         wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
#     893                 :     138063 :         wtx.nTimeSmart = ComputeTimeSmart(wtx);
#     894                 :     138063 :         AddToSpends(hash);
#     895                 :     138063 :     }
#     896                 :            : 
#     897         [ +  + ]:     164929 :     if (!fInsertedNew)
#     898                 :      26866 :     {
#     899         [ +  + ]:      26866 :         if (confirm.status != wtx.m_confirm.status) {
#     900                 :       4795 :             wtx.m_confirm.status = confirm.status;
#     901                 :       4795 :             wtx.m_confirm.nIndex = confirm.nIndex;
#     902                 :       4795 :             wtx.m_confirm.hashBlock = confirm.hashBlock;
#     903                 :       4795 :             wtx.m_confirm.block_height = confirm.block_height;
#     904                 :       4795 :             fUpdated = true;
#     905                 :      22071 :         } else {
#     906                 :      22071 :             assert(wtx.m_confirm.nIndex == confirm.nIndex);
#     907                 :      22071 :             assert(wtx.m_confirm.hashBlock == confirm.hashBlock);
#     908                 :      22071 :             assert(wtx.m_confirm.block_height == confirm.block_height);
#     909                 :      22071 :         }
#     910                 :            :         // If we have a witness-stripped version of this transaction, and we
#     911                 :            :         // see a new version with a witness, then we must be upgrading a pre-segwit
#     912                 :            :         // wallet.  Store the new version of the transaction with the witness,
#     913                 :            :         // as the stripped-version must be invalid.
#     914                 :            :         // TODO: Store all versions of the transaction, instead of just one.
#     915 [ +  + ][ -  + ]:      26866 :         if (tx->HasWitness() && !wtx.tx->HasWitness()) {
#     916                 :          0 :             wtx.SetTx(tx);
#     917                 :          0 :             fUpdated = true;
#     918                 :          0 :         }
#     919                 :      26866 :     }
#     920                 :            : 
#     921                 :            :     //// debug print
#     922 [ +  + ][ +  + ]:     164929 :     WalletLogPrintf("AddToWallet %s  %s%s\n", hash.ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
#     923                 :            : 
#     924                 :            :     // Write to disk
#     925 [ +  + ][ +  + ]:     164929 :     if (fInsertedNew || fUpdated)
#     926         [ -  + ]:     142858 :         if (!batch.WriteTx(wtx))
#     927                 :          0 :             return nullptr;
#     928                 :            : 
#     929                 :            :     // Break debit/credit balance caches:
#     930                 :     164929 :     wtx.MarkDirty();
#     931                 :            : 
#     932                 :            :     // Notify UI of new or updated transaction
#     933         [ +  + ]:     164929 :     NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
#     934                 :            : 
#     935                 :     164929 : #if HAVE_SYSTEM
#     936                 :            :     // notify an external script when a wallet transaction comes in or is updated
#     937                 :     164929 :     std::string strCmd = gArgs.GetArg("-walletnotify", "");
#     938                 :            : 
#     939         [ +  + ]:     164929 :     if (!strCmd.empty())
#     940                 :         26 :     {
#     941                 :         26 :         boost::replace_all(strCmd, "%s", hash.GetHex());
#     942         [ +  + ]:         26 :         if (confirm.status == CWalletTx::Status::CONFIRMED)
#     943                 :         22 :         {
#     944                 :         22 :             boost::replace_all(strCmd, "%b", confirm.hashBlock.GetHex());
#     945                 :         22 :             boost::replace_all(strCmd, "%h", ToString(confirm.block_height));
#     946                 :         22 :         } else {
#     947                 :          4 :             boost::replace_all(strCmd, "%b", "unconfirmed");
#     948                 :          4 :             boost::replace_all(strCmd, "%h", "-1");
#     949                 :          4 :         }
#     950                 :         26 : #ifndef WIN32
#     951                 :            :         // Substituting the wallet name isn't currently supported on windows
#     952                 :            :         // because windows shell escaping has not been implemented yet:
#     953                 :            :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
#     954                 :            :         // A few ways it could be implemented in the future are described in:
#     955                 :            :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
#     956                 :         26 :         boost::replace_all(strCmd, "%w", ShellEscape(GetName()));
#     957                 :         26 : #endif
#     958                 :         26 :         std::thread t(runCommand, strCmd);
#     959                 :         26 :         t.detach(); // thread runs free
#     960                 :         26 :     }
#     961                 :     164929 : #endif
#     962                 :            : 
#     963                 :     164929 :     return &wtx;
#     964                 :     164929 : }
#     965                 :            : 
#     966                 :            : bool CWallet::LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx)
#     967                 :       9892 : {
#     968                 :       9892 :     const auto& ins = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, nullptr));
#     969                 :       9892 :     CWalletTx& wtx = ins.first->second;
#     970         [ -  + ]:       9892 :     if (!fill_wtx(wtx, ins.second)) {
#     971                 :          0 :         return false;
#     972                 :          0 :     }
#     973                 :            :     // If wallet doesn't have a chain (e.g wallet-tool), don't bother to update txn.
#     974         [ +  + ]:       9892 :     if (HaveChain()) {
#     975                 :       9890 :         bool active;
#     976                 :       9890 :         int height;
#     977 [ +  + ][ +  + ]:       9890 :         if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().inActiveChain(active).height(height)) && active) {
#                 [ +  - ]
#     978                 :            :             // Update cached block height variable since it not stored in the
#     979                 :            :             // serialized transaction.
#     980                 :       9252 :             wtx.m_confirm.block_height = height;
#     981 [ +  + ][ +  + ]:       9252 :         } else if (wtx.isConflicted() || wtx.isConfirmed()) {
#     982                 :            :             // If tx block (or conflicting block) was reorged out of chain
#     983                 :            :             // while the wallet was shutdown, change tx status to UNCONFIRMED
#     984                 :            :             // and reset block height, hash, and index. ABANDONED tx don't have
#     985                 :            :             // associated blocks and don't need to be updated. The case where a
#     986                 :            :             // transaction was reorged out while online and then reconfirmed
#     987                 :            :             // while offline is covered by the rescan logic.
#     988                 :        535 :             wtx.setUnconfirmed();
#     989                 :        535 :             wtx.m_confirm.hashBlock = uint256();
#     990                 :        535 :             wtx.m_confirm.block_height = 0;
#     991                 :        535 :             wtx.m_confirm.nIndex = 0;
#     992                 :        535 :         }
#     993                 :       9890 :     }
#     994         [ +  - ]:       9892 :     if (/* insertion took place */ ins.second) {
#     995                 :       9892 :         wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
#     996                 :       9892 :     }
#     997                 :       9892 :     AddToSpends(hash);
#     998         [ +  + ]:       9976 :     for (const CTxIn& txin : wtx.tx->vin) {
#     999                 :       9976 :         auto it = mapWallet.find(txin.prevout.hash);
#    1000         [ +  + ]:       9976 :         if (it != mapWallet.end()) {
#    1001                 :        752 :             CWalletTx& prevtx = it->second;
#    1002         [ -  + ]:        752 :             if (prevtx.isConflicted()) {
#    1003                 :          0 :                 MarkConflicted(prevtx.m_confirm.hashBlock, prevtx.m_confirm.block_height, wtx.GetHash());
#    1004                 :          0 :             }
#    1005                 :        752 :         }
#    1006                 :       9976 :     }
#    1007                 :       9892 :     return true;
#    1008                 :       9892 : }
#    1009                 :            : 
#    1010                 :            : bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool fUpdate)
#    1011                 :     189978 : {
#    1012                 :     189978 :     const CTransaction& tx = *ptx;
#    1013                 :     189978 :     {
#    1014                 :     189978 :         AssertLockHeld(cs_wallet);
#    1015                 :            : 
#    1016         [ +  + ]:     189978 :         if (!confirm.hashBlock.IsNull()) {
#    1017         [ +  + ]:     202318 :             for (const CTxIn& txin : tx.vin) {
#    1018                 :     202318 :                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
#    1019         [ +  + ]:     216293 :                 while (range.first != range.second) {
#    1020         [ +  + ]:      13975 :                     if (range.first->second != tx.GetHash()) {
#    1021                 :        201 :                         WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), confirm.hashBlock.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
#    1022                 :        201 :                         MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
#    1023                 :        201 :                     }
#    1024                 :      13975 :                     range.first++;
#    1025                 :      13975 :                 }
#    1026                 :     202318 :             }
#    1027                 :     166359 :         }
#    1028                 :            : 
#    1029                 :     189978 :         bool fExisted = mapWallet.count(tx.GetHash()) != 0;
#    1030 [ +  + ][ +  + ]:     189978 :         if (fExisted && !fUpdate) return false;
#    1031 [ +  + ][ +  + ]:     189972 :         if (fExisted || IsMine(tx) || IsFromMe(tx))
#                 [ +  + ]
#    1032                 :      52733 :         {
#    1033                 :            :             /* Check if any keys in the wallet keypool that were supposed to be unused
#    1034                 :            :              * have appeared in a new transaction. If so, remove those keys from the keypool.
#    1035                 :            :              * This can happen when restoring an old wallet backup that does not contain
#    1036                 :            :              * the mostly recently created transactions from newer versions of the wallet.
#    1037                 :            :              */
#    1038                 :            : 
#    1039                 :            :             // loop though all outputs
#    1040         [ +  + ]:     246153 :             for (const CTxOut& txout: tx.vout) {
#    1041         [ +  + ]:     623534 :                 for (const auto& spk_man_pair : m_spk_managers) {
#    1042                 :     623534 :                     spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
#    1043                 :     623534 :                 }
#    1044                 :     246153 :             }
#    1045                 :            : 
#    1046                 :            :             // Block disconnection override an abandoned tx as unconfirmed
#    1047                 :            :             // which means user may have to call abandontransaction again
#    1048                 :      52733 :             return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false);
#    1049                 :      52733 :         }
#    1050                 :     137239 :     }
#    1051                 :     137239 :     return false;
#    1052                 :     137239 : }
#    1053                 :            : 
#    1054                 :            : bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
#    1055                 :          0 : {
#    1056                 :          0 :     LOCK(cs_wallet);
#    1057                 :          0 :     const CWalletTx* wtx = GetWalletTx(hashTx);
#    1058 [ #  # ][ #  # ]:          0 :     return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
#         [ #  # ][ #  # ]
#    1059                 :          0 : }
#    1060                 :            : 
#    1061                 :            : void CWallet::MarkInputsDirty(const CTransactionRef& tx)
#    1062                 :      52940 : {
#    1063         [ +  + ]:      80095 :     for (const CTxIn& txin : tx->vin) {
#    1064                 :      80095 :         auto it = mapWallet.find(txin.prevout.hash);
#    1065         [ +  + ]:      80095 :         if (it != mapWallet.end()) {
#    1066                 :      36708 :             it->second.MarkDirty();
#    1067                 :      36708 :         }
#    1068                 :      80095 :     }
#    1069                 :      52940 : }
#    1070                 :            : 
#    1071                 :            : bool CWallet::AbandonTransaction(const uint256& hashTx)
#    1072                 :         10 : {
#    1073                 :         10 :     LOCK(cs_wallet);
#    1074                 :            : 
#    1075                 :         10 :     WalletBatch batch(GetDatabase());
#    1076                 :            : 
#    1077                 :         10 :     std::set<uint256> todo;
#    1078                 :         10 :     std::set<uint256> done;
#    1079                 :            : 
#    1080                 :            :     // Can't mark abandoned if confirmed or in mempool
#    1081                 :         10 :     auto it = mapWallet.find(hashTx);
#    1082                 :         10 :     assert(it != mapWallet.end());
#    1083                 :         10 :     const CWalletTx& origtx = it->second;
#    1084 [ +  + ][ -  + ]:         10 :     if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
#    1085                 :          4 :         return false;
#    1086                 :          4 :     }
#    1087                 :            : 
#    1088                 :          6 :     todo.insert(hashTx);
#    1089                 :            : 
#    1090         [ +  + ]:         16 :     while (!todo.empty()) {
#    1091                 :         10 :         uint256 now = *todo.begin();
#    1092                 :         10 :         todo.erase(now);
#    1093                 :         10 :         done.insert(now);
#    1094                 :         10 :         auto it = mapWallet.find(now);
#    1095                 :         10 :         assert(it != mapWallet.end());
#    1096                 :         10 :         CWalletTx& wtx = it->second;
#    1097                 :         10 :         int currentconfirm = wtx.GetDepthInMainChain();
#    1098                 :            :         // If the orig tx was not in block, none of its spends can be
#    1099                 :         10 :         assert(currentconfirm <= 0);
#    1100                 :            :         // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
#    1101 [ +  - ][ +  - ]:         10 :         if (currentconfirm == 0 && !wtx.isAbandoned()) {
#    1102                 :            :             // If the orig tx was not in block/mempool, none of its spends can be in mempool
#    1103                 :         10 :             assert(!wtx.InMempool());
#    1104                 :         10 :             wtx.setAbandoned();
#    1105                 :         10 :             wtx.MarkDirty();
#    1106                 :         10 :             batch.WriteTx(wtx);
#    1107                 :         10 :             NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
#    1108                 :            :             // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
#    1109                 :         10 :             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
#    1110 [ +  - ][ +  + ]:         14 :             while (iter != mapTxSpends.end() && iter->first.hash == now) {
#                 [ +  + ]
#    1111         [ +  - ]:          4 :                 if (!done.count(iter->second)) {
#    1112                 :          4 :                     todo.insert(iter->second);
#    1113                 :          4 :                 }
#    1114                 :          4 :                 iter++;
#    1115                 :          4 :             }
#    1116                 :            :             // If a transaction changes 'conflicted' state, that changes the balance
#    1117                 :            :             // available of the outputs it spends. So force those to be recomputed
#    1118                 :         10 :             MarkInputsDirty(wtx.tx);
#    1119                 :         10 :         }
#    1120                 :         10 :     }
#    1121                 :            : 
#    1122                 :          6 :     return true;
#    1123                 :          6 : }
#    1124                 :            : 
#    1125                 :            : void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
#    1126                 :        201 : {
#    1127                 :        201 :     LOCK(cs_wallet);
#    1128                 :            : 
#    1129                 :        201 :     int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
#    1130                 :            :     // If number of conflict confirms cannot be determined, this means
#    1131                 :            :     // that the block is still unknown or not yet part of the main chain,
#    1132                 :            :     // for example when loading the wallet during a reindex. Do nothing in that
#    1133                 :            :     // case.
#    1134         [ -  + ]:        201 :     if (conflictconfirms >= 0)
#    1135                 :          0 :         return;
#    1136                 :            : 
#    1137                 :            :     // Do not flush the wallet here for performance reasons
#    1138                 :        201 :     WalletBatch batch(GetDatabase(), false);
#    1139                 :            : 
#    1140                 :        201 :     std::set<uint256> todo;
#    1141                 :        201 :     std::set<uint256> done;
#    1142                 :            : 
#    1143                 :        201 :     todo.insert(hashTx);
#    1144                 :            : 
#    1145         [ +  + ]:        410 :     while (!todo.empty()) {
#    1146                 :        209 :         uint256 now = *todo.begin();
#    1147                 :        209 :         todo.erase(now);
#    1148                 :        209 :         done.insert(now);
#    1149                 :        209 :         auto it = mapWallet.find(now);
#    1150                 :        209 :         assert(it != mapWallet.end());
#    1151                 :        209 :         CWalletTx& wtx = it->second;
#    1152                 :        209 :         int currentconfirm = wtx.GetDepthInMainChain();
#    1153         [ +  + ]:        209 :         if (conflictconfirms < currentconfirm) {
#    1154                 :            :             // Block is 'more conflicted' than current confirm; update.
#    1155                 :            :             // Mark transaction as conflicted with this block.
#    1156                 :        197 :             wtx.m_confirm.nIndex = 0;
#    1157                 :        197 :             wtx.m_confirm.hashBlock = hashBlock;
#    1158                 :        197 :             wtx.m_confirm.block_height = conflicting_height;
#    1159                 :        197 :             wtx.setConflicted();
#    1160                 :        197 :             wtx.MarkDirty();
#    1161                 :        197 :             batch.WriteTx(wtx);
#    1162                 :            :             // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
#    1163                 :        197 :             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
#    1164 [ +  + ][ +  + ]:        205 :             while (iter != mapTxSpends.end() && iter->first.hash == now) {
#                 [ +  + ]
#    1165         [ +  - ]:          8 :                  if (!done.count(iter->second)) {
#    1166                 :          8 :                      todo.insert(iter->second);
#    1167                 :          8 :                  }
#    1168                 :          8 :                  iter++;
#    1169                 :          8 :             }
#    1170                 :            :             // If a transaction changes 'conflicted' state, that changes the balance
#    1171                 :            :             // available of the outputs it spends. So force those to be recomputed
#    1172                 :        197 :             MarkInputsDirty(wtx.tx);
#    1173                 :        197 :         }
#    1174                 :        209 :     }
#    1175                 :        201 : }
#    1176                 :            : 
#    1177                 :            : void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
#    1178                 :     189978 : {
#    1179         [ +  + ]:     189978 :     if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
#    1180                 :     137245 :         return; // Not one of ours
#    1181                 :            : 
#    1182                 :            :     // If a transaction changes 'conflicted' state, that changes the balance
#    1183                 :            :     // available of the outputs it spends. So force those to be
#    1184                 :            :     // recomputed, also:
#    1185                 :      52733 :     MarkInputsDirty(ptx);
#    1186                 :      52733 : }
#    1187                 :            : 
#    1188                 :      20058 : void CWallet::transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {
#    1189                 :      20058 :     LOCK(cs_wallet);
#    1190                 :      20058 :     SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
#    1191                 :            : 
#    1192                 :      20058 :     auto it = mapWallet.find(tx->GetHash());
#    1193         [ +  + ]:      20058 :     if (it != mapWallet.end()) {
#    1194                 :       4529 :         it->second.fInMempool = true;
#    1195                 :       4529 :     }
#    1196                 :      20058 : }
#    1197                 :            : 
#    1198                 :      78122 : void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {
#    1199                 :      78122 :     LOCK(cs_wallet);
#    1200                 :      78122 :     auto it = mapWallet.find(tx->GetHash());
#    1201         [ +  + ]:      78122 :     if (it != mapWallet.end()) {
#    1202                 :      23331 :         it->second.fInMempool = false;
#    1203                 :      23331 :     }
#    1204                 :            :     // Handle transactions that were removed from the mempool because they
#    1205                 :            :     // conflict with transactions in a newly connected block.
#    1206         [ +  + ]:      78122 :     if (reason == MemPoolRemovalReason::CONFLICT) {
#    1207                 :            :         // Trigger external -walletnotify notifications for these transactions.
#    1208                 :            :         // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
#    1209                 :            :         //
#    1210                 :            :         // 1. The transactionRemovedFromMempool callback does not currently
#    1211                 :            :         //    provide the conflicting block's hash and height, and for backwards
#    1212                 :            :         //    compatibility reasons it may not be not safe to store conflicted
#    1213                 :            :         //    wallet transactions with a null block hash. See
#    1214                 :            :         //    https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
#    1215                 :            :         // 2. For most of these transactions, the wallet's internal conflict
#    1216                 :            :         //    detection in the blockConnected handler will subsequently call
#    1217                 :            :         //    MarkConflicted and update them with CONFLICTED status anyway. This
#    1218                 :            :         //    applies to any wallet transaction that has inputs spent in the
#    1219                 :            :         //    block, or that has ancestors in the wallet with inputs spent by
#    1220                 :            :         //    the block.
#    1221                 :            :         // 3. Longstanding behavior since the sync implementation in
#    1222                 :            :         //    https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
#    1223                 :            :         //    implementation before that was to mark these transactions
#    1224                 :            :         //    unconfirmed rather than conflicted.
#    1225                 :            :         //
#    1226                 :            :         // Nothing described above should be seen as an unchangeable requirement
#    1227                 :            :         // when improving this code in the future. The wallet's heuristics for
#    1228                 :            :         // distinguishing between conflicted and unconfirmed transactions are
#    1229                 :            :         // imperfect, and could be improved in general, see
#    1230                 :            :         // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
#    1231                 :         12 :         SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
#    1232                 :         12 :     }
#    1233                 :      78122 : }
#    1234                 :            : 
#    1235                 :            : void CWallet::blockConnected(const CBlock& block, int height)
#    1236                 :      44929 : {
#    1237                 :      44929 :     const uint256& block_hash = block.GetHash();
#    1238                 :      44929 :     LOCK(cs_wallet);
#    1239                 :            : 
#    1240                 :      44929 :     m_last_block_processed_height = height;
#    1241                 :      44929 :     m_last_block_processed = block_hash;
#    1242         [ +  + ]:     122577 :     for (size_t index = 0; index < block.vtx.size(); index++) {
#    1243                 :      77648 :         SyncTransaction(block.vtx[index], {CWalletTx::Status::CONFIRMED, height, block_hash, (int)index});
#    1244                 :      77648 :         transactionRemovedFromMempool(block.vtx[index], MemPoolRemovalReason::BLOCK, 0 /* mempool_sequence */);
#    1245                 :      77648 :     }
#    1246                 :      44929 : }
#    1247                 :            : 
#    1248                 :            : void CWallet::blockDisconnected(const CBlock& block, int height)
#    1249                 :       1746 : {
#    1250                 :       1746 :     LOCK(cs_wallet);
#    1251                 :            : 
#    1252                 :            :     // At block disconnection, this will change an abandoned transaction to
#    1253                 :            :     // be unconfirmed, whether or not the transaction is added back to the mempool.
#    1254                 :            :     // User may have to call abandontransaction again. It may be addressed in the
#    1255                 :            :     // future with a stickier abandoned state or even removing abandontransaction call.
#    1256                 :       1746 :     m_last_block_processed_height = height - 1;
#    1257                 :       1746 :     m_last_block_processed = block.hashPrevBlock;
#    1258         [ +  + ]:       3549 :     for (const CTransactionRef& ptx : block.vtx) {
#    1259                 :       3549 :         SyncTransaction(ptx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
#    1260                 :       3549 :     }
#    1261                 :       1746 : }
#    1262                 :            : 
#    1263                 :            : void CWallet::updatedBlockTip()
#    1264                 :      43451 : {
#    1265                 :      43451 :     m_best_block_time = GetTime();
#    1266                 :      43451 : }
#    1267                 :            : 
#    1268                 :            : 
#    1269                 :       7115 : void CWallet::BlockUntilSyncedToCurrentChain() const {
#    1270                 :       7115 :     AssertLockNotHeld(cs_wallet);
#    1271                 :            :     // Skip the queue-draining stuff if we know we're caught up with
#    1272                 :            :     // ::ChainActive().Tip(), otherwise put a callback in the validation interface queue and wait
#    1273                 :            :     // for the queue to drain enough to execute it (indicating we are caught up
#    1274                 :            :     // at least with the time we entered this function).
#    1275                 :       7115 :     uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
#    1276                 :       7115 :     chain().waitForNotificationsIfTipChanged(last_block_hash);
#    1277                 :       7115 : }
#    1278                 :            : 
#    1279                 :            : // Note that this function doesn't distinguish between a 0-valued input,
#    1280                 :            : // and a not-"is mine" (according to the filter) input.
#    1281                 :            : CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
#    1282                 :     242402 : {
#    1283                 :     242402 :     {
#    1284                 :     242402 :         LOCK(cs_wallet);
#    1285                 :     242402 :         std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
#    1286         [ +  + ]:     242402 :         if (mi != mapWallet.end())
#    1287                 :      40356 :         {
#    1288                 :      40356 :             const CWalletTx& prev = (*mi).second;
#    1289         [ +  - ]:      40356 :             if (txin.prevout.n < prev.tx->vout.size())
#    1290         [ +  + ]:      40356 :                 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
#    1291                 :      17810 :                     return prev.tx->vout[txin.prevout.n].nValue;
#    1292                 :     224592 :         }
#    1293                 :     224592 :     }
#    1294                 :     224592 :     return 0;
#    1295                 :     224592 : }
#    1296                 :            : 
#    1297                 :            : isminetype CWallet::IsMine(const CTxOut& txout) const
#    1298                 :    1549377 : {
#    1299                 :    1549377 :     AssertLockHeld(cs_wallet);
#    1300                 :    1549377 :     return IsMine(txout.scriptPubKey);
#    1301                 :    1549377 : }
#    1302                 :            : 
#    1303                 :            : isminetype CWallet::IsMine(const CTxDestination& dest) const
#    1304                 :      23086 : {
#    1305                 :      23086 :     AssertLockHeld(cs_wallet);
#    1306                 :      23086 :     return IsMine(GetScriptForDestination(dest));
#    1307                 :      23086 : }
#    1308                 :            : 
#    1309                 :            : isminetype CWallet::IsMine(const CScript& script) const
#    1310                 :    1575273 : {
#    1311                 :    1575273 :     AssertLockHeld(cs_wallet);
#    1312                 :    1575273 :     isminetype result = ISMINE_NO;
#    1313         [ +  + ]:    4548077 :     for (const auto& spk_man_pair : m_spk_managers) {
#    1314                 :    4548077 :         result = std::max(result, spk_man_pair.second->IsMine(script));
#    1315                 :    4548077 :     }
#    1316                 :    1575273 :     return result;
#    1317                 :    1575273 : }
#    1318                 :            : 
#    1319                 :            : bool CWallet::IsMine(const CTransaction& tx) const
#    1320                 :     163115 : {
#    1321                 :     163115 :     AssertLockHeld(cs_wallet);
#    1322         [ +  + ]:     163115 :     for (const CTxOut& txout : tx.vout)
#    1323         [ +  + ]:     420467 :         if (IsMine(txout))
#    1324                 :      25662 :             return true;
#    1325                 :     163115 :     return false;
#    1326                 :     163115 : }
#    1327                 :            : 
#    1328                 :            : bool CWallet::IsFromMe(const CTransaction& tx) const
#    1329                 :     137451 : {
#    1330                 :     137451 :     return (GetDebit(tx, ISMINE_ALL) > 0);
#    1331                 :     137451 : }
#    1332                 :            : 
#    1333                 :            : CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
#    1334                 :     176719 : {
#    1335                 :     176719 :     CAmount nDebit = 0;
#    1336         [ +  + ]:     176719 :     for (const CTxIn& txin : tx.vin)
#    1337                 :     242402 :     {
#    1338                 :     242402 :         nDebit += GetDebit(txin, filter);
#    1339         [ -  + ]:     242402 :         if (!MoneyRange(nDebit))
#    1340                 :          0 :             throw std::runtime_error(std::string(__func__) + ": value out of range");
#    1341                 :     242402 :     }
#    1342                 :     176719 :     return nDebit;
#    1343                 :     176719 : }
#    1344                 :            : 
#    1345                 :            : bool CWallet::IsHDEnabled() const
#    1346                 :          6 : {
#    1347                 :            :     // All Active ScriptPubKeyMans must be HD for this to be true
#    1348                 :          6 :     bool result = true;
#    1349         [ +  + ]:         21 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
#    1350                 :         21 :         result &= spk_man->IsHDEnabled();
#    1351                 :         21 :     }
#    1352                 :          6 :     return result;
#    1353                 :          6 : }
#    1354                 :            : 
#    1355                 :            : bool CWallet::CanGetAddresses(bool internal) const
#    1356                 :      12904 : {
#    1357                 :      12904 :     LOCK(cs_wallet);
#    1358         [ +  + ]:      12904 :     if (m_spk_managers.empty()) return false;
#    1359         [ +  + ]:      12996 :     for (OutputType t : OUTPUT_TYPES) {
#    1360                 :      12996 :         auto spk_man = GetScriptPubKeyMan(t, internal);
#    1361 [ +  + ][ +  + ]:      12996 :         if (spk_man && spk_man->CanGetAddresses(internal)) {
#    1362                 :      12845 :             return true;
#    1363                 :      12845 :         }
#    1364                 :      12996 :     }
#    1365                 :      12886 :     return false;
#    1366                 :      12886 : }
#    1367                 :            : 
#    1368                 :            : void CWallet::SetWalletFlag(uint64_t flags)
#    1369                 :        116 : {
#    1370                 :        116 :     LOCK(cs_wallet);
#    1371                 :        116 :     m_wallet_flags |= flags;
#    1372         [ -  + ]:        116 :     if (!WalletBatch(GetDatabase()).WriteWalletFlags(m_wallet_flags))
#    1373                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
#    1374                 :        116 : }
#    1375                 :            : 
#    1376                 :            : void CWallet::UnsetWalletFlag(uint64_t flag)
#    1377                 :          0 : {
#    1378                 :          0 :     WalletBatch batch(GetDatabase());
#    1379                 :          0 :     UnsetWalletFlagWithDB(batch, flag);
#    1380                 :          0 : }
#    1381                 :            : 
#    1382                 :            : void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
#    1383                 :      14308 : {
#    1384                 :      14308 :     LOCK(cs_wallet);
#    1385                 :      14308 :     m_wallet_flags &= ~flag;
#    1386         [ -  + ]:      14308 :     if (!batch.WriteWalletFlags(m_wallet_flags))
#    1387                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
#    1388                 :      14308 : }
#    1389                 :            : 
#    1390                 :            : void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
#    1391                 :      14308 : {
#    1392                 :      14308 :     UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
#    1393                 :      14308 : }
#    1394                 :            : 
#    1395                 :            : bool CWallet::IsWalletFlagSet(uint64_t flag) const
#    1396                 :     334584 : {
#    1397                 :     334584 :     return (m_wallet_flags & flag);
#    1398                 :     334584 : }
#    1399                 :            : 
#    1400                 :            : bool CWallet::LoadWalletFlags(uint64_t flags)
#    1401                 :        757 : {
#    1402                 :        757 :     LOCK(cs_wallet);
#    1403         [ -  + ]:        757 :     if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
#    1404                 :            :         // contains unknown non-tolerable wallet flags
#    1405                 :          0 :         return false;
#    1406                 :          0 :     }
#    1407                 :        757 :     m_wallet_flags = flags;
#    1408                 :            : 
#    1409                 :        757 :     return true;
#    1410                 :        757 : }
#    1411                 :            : 
#    1412                 :            : bool CWallet::AddWalletFlags(uint64_t flags)
#    1413                 :        416 : {
#    1414                 :        416 :     LOCK(cs_wallet);
#    1415                 :            :     // We should never be writing unknown non-tolerable wallet flags
#    1416                 :        416 :     assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
#    1417         [ -  + ]:        416 :     if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
#    1418                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
#    1419                 :          0 :     }
#    1420                 :            : 
#    1421                 :        416 :     return LoadWalletFlags(flags);
#    1422                 :        416 : }
#    1423                 :            : 
#    1424                 :            : // Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
#    1425                 :            : // or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
#    1426                 :            : bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
#    1427                 :     544451 : {
#    1428                 :            :     // Fill in dummy signatures for fee calculation.
#    1429                 :     544451 :     const CScript& scriptPubKey = txout.scriptPubKey;
#    1430                 :     544451 :     SignatureData sigdata;
#    1431                 :            : 
#    1432                 :     544451 :     std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
#    1433         [ +  + ]:     544451 :     if (!provider) {
#    1434                 :            :         // We don't know about this scriptpbuKey;
#    1435                 :     110039 :         return false;
#    1436                 :     110039 :     }
#    1437                 :            : 
#    1438 [ -  + ][ +  + ]:     434412 :     if (!ProduceSignature(*provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
#    1439                 :          0 :         return false;
#    1440                 :          0 :     }
#    1441                 :     434412 :     UpdateInput(tx_in, sigdata);
#    1442                 :     434412 :     return true;
#    1443                 :     434412 : }
#    1444                 :            : 
#    1445                 :            : // Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
#    1446                 :            : bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
#    1447                 :       5073 : {
#    1448                 :            :     // Fill in dummy signatures for fee calculation.
#    1449                 :       5073 :     int nIn = 0;
#    1450         [ +  + ]:       5073 :     for (const auto& txout : txouts)
#    1451                 :      27887 :     {
#    1452         [ -  + ]:      27887 :         if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
#    1453                 :          0 :             return false;
#    1454                 :          0 :         }
#    1455                 :            : 
#    1456                 :      27887 :         nIn++;
#    1457                 :      27887 :     }
#    1458                 :       5073 :     return true;
#    1459                 :       5073 : }
#    1460                 :            : 
#    1461                 :            : bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
#    1462                 :       1273 : {
#    1463                 :       1273 :     auto spk_man = GetLegacyScriptPubKeyMan();
#    1464         [ -  + ]:       1273 :     if (!spk_man) {
#    1465                 :          0 :         return false;
#    1466                 :          0 :     }
#    1467                 :       1273 :     LOCK(spk_man->cs_KeyStore);
#    1468                 :       1273 :     return spk_man->ImportScripts(scripts, timestamp);
#    1469                 :       1273 : }
#    1470                 :            : 
#    1471                 :            : bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
#    1472                 :       1231 : {
#    1473                 :       1231 :     auto spk_man = GetLegacyScriptPubKeyMan();
#    1474         [ -  + ]:       1231 :     if (!spk_man) {
#    1475                 :          0 :         return false;
#    1476                 :          0 :     }
#    1477                 :       1231 :     LOCK(spk_man->cs_KeyStore);
#    1478                 :       1231 :     return spk_man->ImportPrivKeys(privkey_map, timestamp);
#    1479                 :       1231 : }
#    1480                 :            : 
#    1481                 :            : bool CWallet::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
#    1482                 :        196 : {
#    1483                 :        196 :     auto spk_man = GetLegacyScriptPubKeyMan();
#    1484         [ -  + ]:        196 :     if (!spk_man) {
#    1485                 :          0 :         return false;
#    1486                 :          0 :     }
#    1487                 :        196 :     LOCK(spk_man->cs_KeyStore);
#    1488                 :        196 :     return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
#    1489                 :        196 : }
#    1490                 :            : 
#    1491                 :            : bool CWallet::ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp)
#    1492                 :        278 : {
#    1493                 :        278 :     auto spk_man = GetLegacyScriptPubKeyMan();
#    1494         [ -  + ]:        278 :     if (!spk_man) {
#    1495                 :          0 :         return false;
#    1496                 :          0 :     }
#    1497                 :        278 :     LOCK(spk_man->cs_KeyStore);
#    1498         [ -  + ]:        278 :     if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
#    1499                 :          0 :         return false;
#    1500                 :          0 :     }
#    1501         [ +  + ]:        278 :     if (apply_label) {
#    1502                 :        263 :         WalletBatch batch(GetDatabase());
#    1503         [ +  + ]:        381 :         for (const CScript& script : script_pub_keys) {
#    1504                 :        381 :             CTxDestination dest;
#    1505                 :        381 :             ExtractDestination(script, dest);
#    1506         [ +  + ]:        381 :             if (IsValidDestination(dest)) {
#    1507                 :        372 :                 SetAddressBookWithDB(batch, dest, label, "receive");
#    1508                 :        372 :             }
#    1509                 :        381 :         }
#    1510                 :        263 :     }
#    1511                 :        278 :     return true;
#    1512                 :        278 : }
#    1513                 :            : 
#    1514                 :            : /**
#    1515                 :            :  * Scan active chain for relevant transactions after importing keys. This should
#    1516                 :            :  * be called whenever new keys are added to the wallet, with the oldest key
#    1517                 :            :  * creation time.
#    1518                 :            :  *
#    1519                 :            :  * @return Earliest timestamp that could be successfully scanned from. Timestamp
#    1520                 :            :  * returned will be higher than startTime if relevant blocks could not be read.
#    1521                 :            :  */
#    1522                 :            : int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
#    1523                 :        537 : {
#    1524                 :            :     // Find starting block. May be null if nCreateTime is greater than the
#    1525                 :            :     // highest blockchain timestamp, in which case there is nothing that needs
#    1526                 :            :     // to be scanned.
#    1527                 :        537 :     int start_height = 0;
#    1528                 :        537 :     uint256 start_block;
#    1529                 :        537 :     bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
#    1530         [ +  - ]:        537 :     WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
#    1531                 :            : 
#    1532         [ +  - ]:        537 :     if (start) {
#    1533                 :            :         // TODO: this should take into account failure by ScanResult::USER_ABORT
#    1534                 :        537 :         ScanResult result = ScanForWalletTransactions(start_block, start_height, {} /* max_height */, reserver, update);
#    1535         [ +  + ]:        537 :         if (result.status == ScanResult::FAILURE) {
#    1536                 :          1 :             int64_t time_max;
#    1537         [ -  + ]:          1 :             CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
#    1538                 :          1 :             return time_max + TIMESTAMP_WINDOW + 1;
#    1539                 :        536 :         }
#    1540                 :        537 :     }
#    1541                 :        536 :     return startTime;
#    1542                 :        536 : }
#    1543                 :            : 
#    1544                 :            : /**
#    1545                 :            :  * Scan the block chain (starting in start_block) for transactions
#    1546                 :            :  * from or to us. If fUpdate is true, found transactions that already
#    1547                 :            :  * exist in the wallet will be updated.
#    1548                 :            :  *
#    1549                 :            :  * @param[in] start_block Scan starting block. If block is not on the active
#    1550                 :            :  *                        chain, the scan will return SUCCESS immediately.
#    1551                 :            :  * @param[in] start_height Height of start_block
#    1552                 :            :  * @param[in] max_height  Optional max scanning height. If unset there is
#    1553                 :            :  *                        no maximum and scanning can continue to the tip
#    1554                 :            :  *
#    1555                 :            :  * @return ScanResult returning scan information and indicating success or
#    1556                 :            :  *         failure. Return status will be set to SUCCESS if scan was
#    1557                 :            :  *         successful. FAILURE if a complete rescan was not possible (due to
#    1558                 :            :  *         pruning or corruption). USER_ABORT if the rescan was aborted before
#    1559                 :            :  *         it could complete.
#    1560                 :            :  *
#    1561                 :            :  * @pre Caller needs to make sure start_block (and the optional stop_block) are on
#    1562                 :            :  * the main chain after to the addition of any new keys you want to detect
#    1563                 :            :  * transactions for.
#    1564                 :            :  */
#    1565                 :            : CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate)
#    1566                 :        650 : {
#    1567                 :        650 :     int64_t nNow = GetTime();
#    1568                 :        650 :     int64_t start_time = GetTimeMillis();
#    1569                 :            : 
#    1570                 :        650 :     assert(reserver.isReserved());
#    1571                 :            : 
#    1572                 :        650 :     uint256 block_hash = start_block;
#    1573                 :        650 :     ScanResult result;
#    1574                 :            : 
#    1575                 :        650 :     WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
#    1576                 :            : 
#    1577                 :        650 :     fAbortRescan = false;
#    1578                 :        650 :     ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
#    1579                 :        650 :     uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
#    1580                 :        650 :     uint256 end_hash = tip_hash;
#    1581         [ +  + ]:        650 :     if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
#    1582                 :        650 :     double progress_begin = chain().guessVerificationProgress(block_hash);
#    1583                 :        650 :     double progress_end = chain().guessVerificationProgress(end_hash);
#    1584                 :        650 :     double progress_current = progress_begin;
#    1585                 :        650 :     int block_height = start_height;
#    1586 [ +  - ][ +  - ]:      78752 :     while (!fAbortRescan && !chain().shutdownRequested()) {
#    1587         [ +  + ]:      78752 :         if (progress_end - progress_begin > 0.0) {
#    1588                 :          1 :             m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
#    1589                 :      78751 :         } else { // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
#    1590                 :      78751 :             m_scanning_progress = 0;
#    1591                 :      78751 :         }
#    1592 [ +  + ][ +  + ]:      78752 :         if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
#    1593                 :          1 :             ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
#    1594                 :          1 :         }
#    1595         [ -  + ]:      78752 :         if (GetTime() >= nNow + 60) {
#    1596                 :          0 :             nNow = GetTime();
#    1597                 :          0 :             WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
#    1598                 :          0 :         }
#    1599                 :            : 
#    1600                 :            :         // Read block data
#    1601                 :      78752 :         CBlock block;
#    1602                 :      78752 :         chain().findBlock(block_hash, FoundBlock().data(block));
#    1603                 :            : 
#    1604                 :            :         // Find next block separately from reading data above, because reading
#    1605                 :            :         // is slow and there might be a reorg while it is read.
#    1606                 :      78752 :         bool block_still_active = false;
#    1607                 :      78752 :         bool next_block = false;
#    1608                 :      78752 :         uint256 next_block_hash;
#    1609                 :      78752 :         chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
#    1610                 :            : 
#    1611         [ +  + ]:      78752 :         if (!block.IsNull()) {
#    1612                 :      78647 :             LOCK(cs_wallet);
#    1613         [ -  + ]:      78647 :             if (!block_still_active) {
#    1614                 :            :                 // Abort scan if current block is no longer active, to prevent
#    1615                 :            :                 // marking transactions as coming from the wrong block.
#    1616                 :          0 :                 result.last_failed_block = block_hash;
#    1617                 :          0 :                 result.status = ScanResult::FAILURE;
#    1618                 :          0 :                 break;
#    1619                 :          0 :             }
#    1620         [ +  + ]:     167358 :             for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
#    1621                 :      88711 :                 SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate);
#    1622                 :      88711 :             }
#    1623                 :            :             // scan succeeded, record block as most recent successfully scanned
#    1624                 :      78647 :             result.last_scanned_block = block_hash;
#    1625                 :      78647 :             result.last_scanned_height = block_height;
#    1626                 :      78647 :         } else {
#    1627                 :            :             // could not scan block, keep scanning but record this block as the most recent failure
#    1628                 :        105 :             result.last_failed_block = block_hash;
#    1629                 :        105 :             result.status = ScanResult::FAILURE;
#    1630                 :        105 :         }
#    1631 [ +  + ][ +  + ]:      78752 :         if (max_height && block_height >= *max_height) {
#    1632                 :          2 :             break;
#    1633                 :          2 :         }
#    1634                 :      78750 :         {
#    1635         [ +  + ]:      78750 :             if (!next_block) {
#    1636                 :            :                 // break successfully when rescan has reached the tip, or
#    1637                 :            :                 // previous block is no longer on the chain due to a reorg
#    1638                 :        648 :                 break;
#    1639                 :        648 :             }
#    1640                 :            : 
#    1641                 :            :             // increment block and verification progress
#    1642                 :      78102 :             block_hash = next_block_hash;
#    1643                 :      78102 :             ++block_height;
#    1644                 :      78102 :             progress_current = chain().guessVerificationProgress(block_hash);
#    1645                 :            : 
#    1646                 :            :             // handle updated tip hash
#    1647                 :      78102 :             const uint256 prev_tip_hash = tip_hash;
#    1648                 :      78102 :             tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
#    1649 [ +  + ][ -  + ]:      78102 :             if (!max_height && prev_tip_hash != tip_hash) {
#    1650                 :            :                 // in case the tip has changed, update progress max
#    1651                 :          0 :                 progress_end = chain().guessVerificationProgress(tip_hash);
#    1652                 :          0 :             }
#    1653                 :      78102 :         }
#    1654                 :      78102 :     }
#    1655                 :        650 :     ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 100); // hide progress dialog in GUI
#    1656 [ +  + ][ -  + ]:        650 :     if (block_height && fAbortRescan) {
#    1657                 :          0 :         WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
#    1658                 :          0 :         result.status = ScanResult::USER_ABORT;
#    1659 [ +  + ][ -  + ]:        650 :     } else if (block_height && chain().shutdownRequested()) {
#    1660                 :          0 :         WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
#    1661                 :          0 :         result.status = ScanResult::USER_ABORT;
#    1662                 :        650 :     } else {
#    1663                 :        650 :         WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
#    1664                 :        650 :     }
#    1665                 :        650 :     return result;
#    1666                 :        650 : }
#    1667                 :            : 
#    1668                 :            : void CWallet::ReacceptWalletTransactions()
#    1669                 :       1072 : {
#    1670                 :            :     // If transactions aren't being broadcasted, don't let them into local mempool either
#    1671         [ +  + ]:       1072 :     if (!fBroadcastTransactions)
#    1672                 :          8 :         return;
#    1673                 :       1064 :     std::map<int64_t, CWalletTx*> mapSorted;
#    1674                 :            : 
#    1675                 :            :     // Sort pending wallet transactions based on their initial wallet insertion order
#    1676         [ +  + ]:      25333 :     for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
#    1677                 :      25333 :         const uint256& wtxid = item.first;
#    1678                 :      25333 :         CWalletTx& wtx = item.second;
#    1679                 :      25333 :         assert(wtx.GetHash() == wtxid);
#    1680                 :            : 
#    1681                 :      25333 :         int nDepth = wtx.GetDepthInMainChain();
#    1682                 :            : 
#    1683 [ +  + ][ +  + ]:      25333 :         if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
#                 [ +  + ]
#    1684                 :        182 :             mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
#    1685                 :        182 :         }
#    1686                 :      25333 :     }
#    1687                 :            : 
#    1688                 :            :     // Try to add wallet transactions to memory pool
#    1689         [ +  + ]:       1064 :     for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
#    1690                 :        182 :         CWalletTx& wtx = *(item.second);
#    1691                 :        182 :         std::string unused_err_string;
#    1692                 :        182 :         wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
#    1693                 :        182 :     }
#    1694                 :       1064 : }
#    1695                 :            : 
#    1696                 :            : bool CWalletTx::SubmitMemoryPoolAndRelay(std::string& err_string, bool relay)
#    1697                 :       2621 : {
#    1698                 :            :     // Can't relay if wallet is not broadcasting
#    1699         [ -  + ]:       2621 :     if (!pwallet->GetBroadcastTransactions()) return false;
#    1700                 :            :     // Don't relay abandoned transactions
#    1701         [ -  + ]:       2621 :     if (isAbandoned()) return false;
#    1702                 :            :     // Don't try to submit coinbase transactions. These would fail anyway but would
#    1703                 :            :     // cause log spam.
#    1704         [ +  + ]:       2621 :     if (IsCoinBase()) return false;
#    1705                 :            :     // Don't try to submit conflicted or confirmed transactions.
#    1706         [ +  + ]:       2388 :     if (GetDepthInMainChain() != 0) return false;
#    1707                 :            : 
#    1708                 :            :     // Submit transaction to mempool for relay
#    1709                 :       2374 :     pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n", GetHash().ToString());
#    1710                 :            :     // We must set fInMempool here - while it will be re-set to true by the
#    1711                 :            :     // entered-mempool callback, if we did not there would be a race where a
#    1712                 :            :     // user could call sendmoney in a loop and hit spurious out of funds errors
#    1713                 :            :     // because we think that this newly generated transaction's change is
#    1714                 :            :     // unavailable as we're not yet aware that it is in the mempool.
#    1715                 :            :     //
#    1716                 :            :     // Irrespective of the failure reason, un-marking fInMempool
#    1717                 :            :     // out-of-order is incorrect - it should be unmarked when
#    1718                 :            :     // TransactionRemovedFromMempool fires.
#    1719                 :       2374 :     bool ret = pwallet->chain().broadcastTransaction(tx, pwallet->m_default_max_tx_fee, relay, err_string);
#    1720                 :       2374 :     fInMempool |= ret;
#    1721                 :       2374 :     return ret;
#    1722                 :       2374 : }
#    1723                 :            : 
#    1724                 :            : std::set<uint256> CWalletTx::GetConflicts() const
#    1725                 :       3181 : {
#    1726                 :       3181 :     std::set<uint256> result;
#    1727         [ +  - ]:       3181 :     if (pwallet != nullptr)
#    1728                 :       3181 :     {
#    1729                 :       3181 :         uint256 myHash = GetHash();
#    1730                 :       3181 :         result = pwallet->GetConflicts(myHash);
#    1731                 :       3181 :         result.erase(myHash);
#    1732                 :       3181 :     }
#    1733                 :       3181 :     return result;
#    1734                 :       3181 : }
#    1735                 :            : 
#    1736                 :            : // Rebroadcast transactions from the wallet. We do this on a random timer
#    1737                 :            : // to slightly obfuscate which transactions come from our wallet.
#    1738                 :            : //
#    1739                 :            : // Ideally, we'd only resend transactions that we think should have been
#    1740                 :            : // mined in the most recent block. Any transaction that wasn't in the top
#    1741                 :            : // blockweight of transactions in the mempool shouldn't have been mined,
#    1742                 :            : // and so is probably just sitting in the mempool waiting to be confirmed.
#    1743                 :            : // Rebroadcasting does nothing to speed up confirmation and only damages
#    1744                 :            : // privacy.
#    1745                 :            : void CWallet::ResendWalletTransactions()
#    1746                 :       7001 : {
#    1747                 :            :     // During reindex, importing and IBD, old wallet transactions become
#    1748                 :            :     // unconfirmed. Don't resend them as that would spam other nodes.
#    1749         [ +  + ]:       7001 :     if (!chain().isReadyToBroadcast()) return;
#    1750                 :            : 
#    1751                 :            :     // Do this infrequently and randomly to avoid giving away
#    1752                 :            :     // that these are our transactions.
#    1753 [ +  + ][ +  + ]:       6953 :     if (GetTime() < nNextResend || !fBroadcastTransactions) return;
#    1754                 :        427 :     bool fFirst = (nNextResend == 0);
#    1755                 :            :     // resend 12-36 hours from now, ~1 day on average.
#    1756                 :        427 :     nNextResend = GetTime() + (12 * 60 * 60) + GetRand(24 * 60 * 60);
#    1757         [ +  + ]:        427 :     if (fFirst) return;
#    1758                 :            : 
#    1759                 :          3 :     int submitted_tx_count = 0;
#    1760                 :            : 
#    1761                 :          3 :     { // cs_wallet scope
#    1762                 :          3 :         LOCK(cs_wallet);
#    1763                 :            : 
#    1764                 :            :         // Relay transactions
#    1765         [ +  + ]:        249 :         for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
#    1766                 :        249 :             CWalletTx& wtx = item.second;
#    1767                 :            :             // Attempt to rebroadcast all txes more than 5 minutes older than
#    1768                 :            :             // the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
#    1769                 :            :             // any confirmed or conflicting txs.
#    1770         [ -  + ]:        249 :             if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
#    1771                 :        249 :             std::string unused_err_string;
#    1772         [ +  + ]:        249 :             if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) ++submitted_tx_count;
#    1773                 :        249 :         }
#    1774                 :          3 :     } // cs_wallet
#    1775                 :            : 
#    1776         [ +  + ]:          3 :     if (submitted_tx_count > 0) {
#    1777                 :          2 :         WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
#    1778                 :          2 :     }
#    1779                 :          3 : }
#    1780                 :            : 
#    1781                 :            : /** @} */ // end of mapWallet
#    1782                 :            : 
#    1783                 :            : void MaybeResendWalletTxs()
#    1784                 :      12800 : {
#    1785         [ +  + ]:      12800 :     for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
#    1786                 :       7001 :         pwallet->ResendWalletTransactions();
#    1787                 :       7001 :     }
#    1788                 :      12800 : }
#    1789                 :            : 
#    1790                 :            : 
#    1791                 :            : /** @defgroup Actions
#    1792                 :            :  *
#    1793                 :            :  * @{
#    1794                 :            :  */
#    1795                 :            : 
#    1796                 :            : bool CWallet::SignTransaction(CMutableTransaction& tx) const
#    1797                 :       4194 : {
#    1798                 :       4194 :     AssertLockHeld(cs_wallet);
#    1799                 :            : 
#    1800                 :            :     // Build coins map
#    1801                 :       4194 :     std::map<COutPoint, Coin> coins;
#    1802         [ +  + ]:      21529 :     for (auto& input : tx.vin) {
#    1803                 :      21529 :         std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
#    1804 [ -  + ][ -  + ]:      21529 :         if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
#                 [ -  + ]
#    1805                 :          0 :             return false;
#    1806                 :          0 :         }
#    1807                 :      21529 :         const CWalletTx& wtx = mi->second;
#    1808                 :      21529 :         coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase());
#    1809                 :      21529 :     }
#    1810                 :       4194 :     std::map<int, std::string> input_errors;
#    1811                 :       4194 :     return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
#    1812                 :       4194 : }
#    1813                 :            : 
#    1814                 :            : bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
#    1815                 :       5387 : {
#    1816                 :            :     // Try to sign with all ScriptPubKeyMans
#    1817         [ +  + ]:      13682 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
#    1818                 :            :         // spk_man->SignTransaction will return true if the transaction is complete,
#    1819                 :            :         // so we can exit early and return true if that happens
#    1820         [ +  + ]:      13682 :         if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
#    1821                 :       5371 :             return true;
#    1822                 :       5371 :         }
#    1823                 :      13682 :     }
#    1824                 :            : 
#    1825                 :            :     // At this point, one input was not fully signed otherwise we would have exited already
#    1826                 :       5387 :     return false;
#    1827                 :       5387 : }
#    1828                 :            : 
#    1829                 :            : TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed) const
#    1830                 :        424 : {
#    1831         [ -  + ]:        424 :     if (n_signed) {
#    1832                 :          0 :         *n_signed = 0;
#    1833                 :          0 :     }
#    1834                 :        424 :     LOCK(cs_wallet);
#    1835                 :            :     // Get all of the previous transactions
#    1836         [ +  + ]:        993 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
#    1837                 :        569 :         const CTxIn& txin = psbtx.tx->vin[i];
#    1838                 :        569 :         PSBTInput& input = psbtx.inputs.at(i);
#    1839                 :            : 
#    1840         [ +  + ]:        569 :         if (PSBTInputSigned(input)) {
#    1841                 :         29 :             continue;
#    1842                 :         29 :         }
#    1843                 :            : 
#    1844                 :            :         // If we have no utxo, grab it from the wallet.
#    1845         [ +  + ]:        540 :         if (!input.non_witness_utxo) {
#    1846                 :        406 :             const uint256& txhash = txin.prevout.hash;
#    1847                 :        406 :             const auto it = mapWallet.find(txhash);
#    1848         [ +  + ]:        406 :             if (it != mapWallet.end()) {
#    1849                 :        376 :                 const CWalletTx& wtx = it->second;
#    1850                 :            :                 // We only need the non_witness_utxo, which is a superset of the witness_utxo.
#    1851                 :            :                 //   The signing code will switch to the smaller witness_utxo if this is ok.
#    1852                 :        376 :                 input.non_witness_utxo = wtx.tx;
#    1853                 :        376 :             }
#    1854                 :        406 :         }
#    1855                 :        540 :     }
#    1856                 :            : 
#    1857                 :            :     // Fill in information from ScriptPubKeyMans
#    1858         [ +  + ]:       1404 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
#    1859                 :       1404 :         int n_signed_this_spkm = 0;
#    1860                 :       1404 :         TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs, &n_signed_this_spkm);
#    1861         [ +  + ]:       1404 :         if (res != TransactionError::OK) {
#    1862                 :          2 :             return res;
#    1863                 :          2 :         }
#    1864                 :            : 
#    1865         [ -  + ]:       1402 :         if (n_signed) {
#    1866                 :          0 :             (*n_signed) += n_signed_this_spkm;
#    1867                 :          0 :         }
#    1868                 :       1402 :     }
#    1869                 :            : 
#    1870                 :            :     // Complete if every input is now signed
#    1871                 :        424 :     complete = true;
#    1872         [ +  + ]:        565 :     for (const auto& input : psbtx.inputs) {
#    1873                 :        565 :         complete &= PSBTInputSigned(input);
#    1874                 :        565 :     }
#    1875                 :            : 
#    1876                 :        422 :     return TransactionError::OK;
#    1877                 :        424 : }
#    1878                 :            : 
#    1879                 :            : SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
#    1880                 :         13 : {
#    1881                 :         13 :     SignatureData sigdata;
#    1882                 :         13 :     CScript script_pub_key = GetScriptForDestination(pkhash);
#    1883         [ +  - ]:         27 :     for (const auto& spk_man_pair : m_spk_managers) {
#    1884         [ +  + ]:         27 :         if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
#    1885                 :         13 :             return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
#    1886                 :         13 :         }
#    1887                 :         27 :     }
#    1888                 :         13 :     return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
#    1889                 :         13 : }
#    1890                 :            : 
#    1891                 :            : OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
#    1892                 :       5009 : {
#    1893                 :            :     // If -changetype is specified, always use that change type.
#    1894         [ +  + ]:       5009 :     if (change_type) {
#    1895                 :        104 :         return *change_type;
#    1896                 :        104 :     }
#    1897                 :            : 
#    1898                 :            :     // if m_default_address_type is legacy, use legacy address as change (even
#    1899                 :            :     // if some of the outputs are P2WPKH or P2WSH).
#    1900         [ +  + ]:       4905 :     if (m_default_address_type == OutputType::LEGACY) {
#    1901                 :         42 :         return OutputType::LEGACY;
#    1902                 :         42 :     }
#    1903                 :            : 
#    1904                 :            :     // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
#    1905                 :            :     // output.
#    1906         [ +  + ]:       4911 :     for (const auto& recipient : vecSend) {
#    1907                 :            :         // Check if any destination contains a witness program:
#    1908                 :       4911 :         int witnessversion = 0;
#    1909                 :       4911 :         std::vector<unsigned char> witnessprogram;
#    1910         [ +  + ]:       4911 :         if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
#    1911                 :       4216 :             return OutputType::BECH32;
#    1912                 :       4216 :         }
#    1913                 :       4911 :     }
#    1914                 :            : 
#    1915                 :            :     // else use m_default_address_type for change
#    1916                 :       4863 :     return m_default_address_type;
#    1917                 :       4863 : }
#    1918                 :            : 
#    1919                 :            : void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
#    1920                 :       2195 : {
#    1921                 :       2195 :     LOCK(cs_wallet);
#    1922                 :       2195 :     WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); /* Continued */
#    1923                 :            : 
#    1924                 :            :     // Add tx to wallet, because if it has change it's also ours,
#    1925                 :            :     // otherwise just for transaction history.
#    1926                 :       2195 :     AddToWallet(tx, {}, [&](CWalletTx& wtx, bool new_tx) {
#    1927         [ -  + ]:       2195 :         CHECK_NONFATAL(wtx.mapValue.empty());
#    1928         [ -  + ]:       2195 :         CHECK_NONFATAL(wtx.vOrderForm.empty());
#    1929                 :       2195 :         wtx.mapValue = std::move(mapValue);
#    1930                 :       2195 :         wtx.vOrderForm = std::move(orderForm);
#    1931                 :       2195 :         wtx.fTimeReceivedIsTxTime = true;
#    1932                 :       2195 :         wtx.fFromMe = true;
#    1933                 :       2195 :         return true;
#    1934                 :       2195 :     });
#    1935                 :            : 
#    1936                 :            :     // Notify that old coins are spent
#    1937         [ +  + ]:       6092 :     for (const CTxIn& txin : tx->vin) {
#    1938                 :       6092 :         CWalletTx &coin = mapWallet.at(txin.prevout.hash);
#    1939                 :       6092 :         coin.MarkDirty();
#    1940                 :       6092 :         NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
#    1941                 :       6092 :     }
#    1942                 :            : 
#    1943                 :            :     // Get the inserted-CWalletTx from mapWallet so that the
#    1944                 :            :     // fInMempool flag is cached properly
#    1945                 :       2195 :     CWalletTx& wtx = mapWallet.at(tx->GetHash());
#    1946                 :            : 
#    1947         [ +  + ]:       2195 :     if (!fBroadcastTransactions) {
#    1948                 :            :         // Don't submit tx to the mempool
#    1949                 :          5 :         return;
#    1950                 :          5 :     }
#    1951                 :            : 
#    1952                 :       2190 :     std::string err_string;
#    1953         [ +  + ]:       2190 :     if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
#    1954                 :          6 :         WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
#    1955                 :            :         // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
#    1956                 :          6 :     }
#    1957                 :       2190 : }
#    1958                 :            : 
#    1959                 :            : DBErrors CWallet::LoadWallet()
#    1960                 :        786 : {
#    1961                 :        786 :     LOCK(cs_wallet);
#    1962                 :            : 
#    1963                 :        786 :     DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
#    1964         [ -  + ]:        786 :     if (nLoadWalletRet == DBErrors::NEED_REWRITE)
#    1965                 :          0 :     {
#    1966         [ #  # ]:          0 :         if (GetDatabase().Rewrite("\x04pool"))
#    1967                 :          0 :         {
#    1968         [ #  # ]:          0 :             for (const auto& spk_man_pair : m_spk_managers) {
#    1969                 :          0 :                 spk_man_pair.second->RewriteDB();
#    1970                 :          0 :             }
#    1971                 :          0 :         }
#    1972                 :          0 :     }
#    1973                 :            : 
#    1974         [ +  + ]:        786 :     if (m_spk_managers.empty()) {
#    1975                 :        440 :         assert(m_external_spk_managers.empty());
#    1976                 :        440 :         assert(m_internal_spk_managers.empty());
#    1977                 :        440 :     }
#    1978                 :            : 
#    1979         [ -  + ]:        786 :     if (nLoadWalletRet != DBErrors::LOAD_OK)
#    1980                 :          0 :         return nLoadWalletRet;
#    1981                 :            : 
#    1982                 :        786 :     return DBErrors::LOAD_OK;
#    1983                 :        786 : }
#    1984                 :            : 
#    1985                 :            : DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
#    1986                 :          7 : {
#    1987                 :          7 :     AssertLockHeld(cs_wallet);
#    1988                 :          7 :     DBErrors nZapSelectTxRet = WalletBatch(GetDatabase()).ZapSelectTx(vHashIn, vHashOut);
#    1989         [ +  + ]:          7 :     for (const uint256& hash : vHashOut) {
#    1990                 :          5 :         const auto& it = mapWallet.find(hash);
#    1991                 :          5 :         wtxOrdered.erase(it->second.m_it_wtxOrdered);
#    1992         [ +  + ]:          5 :         for (const auto& txin : it->second.tx->vin)
#    1993                 :          5 :             mapTxSpends.erase(txin.prevout);
#    1994                 :          5 :         mapWallet.erase(it);
#    1995                 :          5 :         NotifyTransactionChanged(this, hash, CT_DELETED);
#    1996                 :          5 :     }
#    1997                 :            : 
#    1998         [ -  + ]:          7 :     if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
#    1999                 :          0 :     {
#    2000         [ #  # ]:          0 :         if (GetDatabase().Rewrite("\x04pool"))
#    2001                 :          0 :         {
#    2002         [ #  # ]:          0 :             for (const auto& spk_man_pair : m_spk_managers) {
#    2003                 :          0 :                 spk_man_pair.second->RewriteDB();
#    2004                 :          0 :             }
#    2005                 :          0 :         }
#    2006                 :          0 :     }
#    2007                 :            : 
#    2008         [ -  + ]:          7 :     if (nZapSelectTxRet != DBErrors::LOAD_OK)
#    2009                 :          0 :         return nZapSelectTxRet;
#    2010                 :            : 
#    2011                 :          7 :     MarkDirty();
#    2012                 :            : 
#    2013                 :          7 :     return DBErrors::LOAD_OK;
#    2014                 :          7 : }
#    2015                 :            : 
#    2016                 :            : bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
#    2017                 :      13953 : {
#    2018                 :      13953 :     bool fUpdated = false;
#    2019                 :      13953 :     bool is_mine;
#    2020                 :      13953 :     {
#    2021                 :      13953 :         LOCK(cs_wallet);
#    2022                 :      13953 :         std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
#    2023 [ +  + ][ +  - ]:      13953 :         fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
#    2024                 :      13953 :         m_address_book[address].SetLabel(strName);
#    2025         [ +  - ]:      13953 :         if (!strPurpose.empty()) /* update purpose only if requested */
#    2026                 :      13953 :             m_address_book[address].purpose = strPurpose;
#    2027                 :      13953 :         is_mine = IsMine(address) != ISMINE_NO;
#    2028                 :      13953 :     }
#    2029                 :      13953 :     NotifyAddressBookChanged(this, address, strName, is_mine,
#    2030         [ +  + ]:      13953 :                              strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
#    2031 [ -  + ][ +  - ]:      13953 :     if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
#                 [ -  + ]
#    2032                 :          0 :         return false;
#    2033                 :      13953 :     return batch.WriteName(EncodeDestination(address), strName);
#    2034                 :      13953 : }
#    2035                 :            : 
#    2036                 :            : bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
#    2037                 :      13581 : {
#    2038                 :      13581 :     WalletBatch batch(GetDatabase());
#    2039                 :      13581 :     return SetAddressBookWithDB(batch, address, strName, strPurpose);
#    2040                 :      13581 : }
#    2041                 :            : 
#    2042                 :            : bool CWallet::DelAddressBook(const CTxDestination& address)
#    2043                 :          0 : {
#    2044                 :          0 :     bool is_mine;
#    2045                 :          0 :     WalletBatch batch(GetDatabase());
#    2046                 :          0 :     {
#    2047                 :          0 :         LOCK(cs_wallet);
#    2048                 :            :         // If we want to delete receiving addresses, we need to take care that DestData "used" (and possibly newer DestData) gets preserved (and the "deleted" address transformed into a change entry instead of actually being deleted)
#    2049                 :            :         // NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
#    2050                 :            :         // When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
#    2051         [ #  # ]:          0 :         if (IsMine(address)) {
#    2052                 :          0 :             WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
#    2053                 :          0 :             return false;
#    2054                 :          0 :         }
#    2055                 :            :         // Delete destdata tuples associated with address
#    2056                 :          0 :         std::string strAddress = EncodeDestination(address);
#    2057         [ #  # ]:          0 :         for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
#    2058                 :          0 :         {
#    2059                 :          0 :             batch.EraseDestData(strAddress, item.first);
#    2060                 :          0 :         }
#    2061                 :          0 :         m_address_book.erase(address);
#    2062                 :          0 :         is_mine = IsMine(address) != ISMINE_NO;
#    2063                 :          0 :     }
#    2064                 :            : 
#    2065                 :          0 :     NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
#    2066                 :            : 
#    2067                 :          0 :     batch.ErasePurpose(EncodeDestination(address));
#    2068                 :          0 :     return batch.EraseName(EncodeDestination(address));
#    2069                 :          0 : }
#    2070                 :            : 
#    2071                 :            : size_t CWallet::KeypoolCountExternalKeys() const
#    2072                 :        978 : {
#    2073                 :        978 :     AssertLockHeld(cs_wallet);
#    2074                 :            : 
#    2075                 :        978 :     unsigned int count = 0;
#    2076         [ +  + ]:       2161 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
#    2077                 :       2161 :         count += spk_man->KeypoolCountExternalKeys();
#    2078                 :       2161 :     }
#    2079                 :            : 
#    2080                 :        978 :     return count;
#    2081                 :        978 : }
#    2082                 :            : 
#    2083                 :            : unsigned int CWallet::GetKeyPoolSize() const
#    2084                 :       1739 : {
#    2085                 :       1739 :     AssertLockHeld(cs_wallet);
#    2086                 :            : 
#    2087                 :       1739 :     unsigned int count = 0;
#    2088         [ +  + ]:       3952 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
#    2089                 :       3952 :         count += spk_man->GetKeyPoolSize();
#    2090                 :       3952 :     }
#    2091                 :       1739 :     return count;
#    2092                 :       1739 : }
#    2093                 :            : 
#    2094                 :            : bool CWallet::TopUpKeyPool(unsigned int kpSize)
#    2095                 :        815 : {
#    2096                 :        815 :     LOCK(cs_wallet);
#    2097                 :        815 :     bool res = true;
#    2098         [ +  + ]:       1958 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
#    2099                 :       1958 :         res &= spk_man->TopUp(kpSize);
#    2100                 :       1958 :     }
#    2101                 :        815 :     return res;
#    2102                 :        815 : }
#    2103                 :            : 
#    2104                 :            : bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
#    2105                 :      12648 : {
#    2106                 :      12648 :     LOCK(cs_wallet);
#    2107                 :      12648 :     error.clear();
#    2108                 :      12648 :     bool result = false;
#    2109                 :      12648 :     auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
#    2110         [ +  - ]:      12648 :     if (spk_man) {
#    2111                 :      12648 :         spk_man->TopUp();
#    2112                 :      12648 :         result = spk_man->GetNewDestination(type, dest, error);
#    2113                 :      12648 :     } else {
#    2114                 :          0 :         error = strprintf("Error: No %s addresses available.", FormatOutputType(type));
#    2115                 :          0 :     }
#    2116         [ +  + ]:      12648 :     if (result) {
#    2117                 :      12640 :         SetAddressBook(dest, label, "receive");
#    2118                 :      12640 :     }
#    2119                 :            : 
#    2120                 :      12648 :     return result;
#    2121                 :      12648 : }
#    2122                 :            : 
#    2123                 :            : bool CWallet::GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error)
#    2124                 :        195 : {
#    2125                 :        195 :     LOCK(cs_wallet);
#    2126                 :        195 :     error.clear();
#    2127                 :            : 
#    2128                 :        195 :     ReserveDestination reservedest(this, type);
#    2129         [ +  + ]:        195 :     if (!reservedest.GetReservedDestination(dest, true)) {
#    2130                 :          2 :         error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
#    2131                 :          2 :         return false;
#    2132                 :          2 :     }
#    2133                 :            : 
#    2134                 :        193 :     reservedest.KeepDestination();
#    2135                 :        193 :     return true;
#    2136                 :        193 : }
#    2137                 :            : 
#    2138                 :            : int64_t CWallet::GetOldestKeyPoolTime() const
#    2139                 :        978 : {
#    2140                 :        978 :     LOCK(cs_wallet);
#    2141                 :        978 :     int64_t oldestKey = std::numeric_limits<int64_t>::max();
#    2142         [ +  + ]:       2539 :     for (const auto& spk_man_pair : m_spk_managers) {
#    2143                 :       2539 :         oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
#    2144                 :       2539 :     }
#    2145                 :        978 :     return oldestKey;
#    2146                 :        978 : }
#    2147                 :            : 
#    2148                 :       1668 : void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
#    2149         [ +  + ]:     494368 :     for (auto& entry : mapWallet) {
#    2150                 :     494368 :         CWalletTx& wtx = entry.second;
#    2151         [ +  + ]:     494368 :         if (wtx.m_is_cache_empty) continue;
#    2152         [ +  + ]:     671217 :         for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
#    2153                 :     444055 :             CTxDestination dst;
#    2154 [ +  + ][ +  + ]:     444055 :             if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
#    2155                 :        941 :                 wtx.MarkDirty();
#    2156                 :        941 :                 break;
#    2157                 :        941 :             }
#    2158                 :     444055 :         }
#    2159                 :     228103 :     }
#    2160                 :       1668 : }
#    2161                 :            : 
#    2162                 :            : std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
#    2163                 :         34 : {
#    2164                 :         34 :     LOCK(cs_wallet);
#    2165                 :         34 :     std::set<CTxDestination> result;
#    2166         [ +  + ]:         34 :     for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
#    2167                 :        280 :     {
#    2168         [ -  + ]:        280 :         if (item.second.IsChange()) continue;
#    2169                 :        280 :         const CTxDestination& address = item.first;
#    2170                 :        280 :         const std::string& strName = item.second.GetLabel();
#    2171         [ +  + ]:        280 :         if (strName == label)
#    2172                 :         68 :             result.insert(address);
#    2173                 :        280 :     }
#    2174                 :         34 :     return result;
#    2175                 :         34 : }
#    2176                 :            : 
#    2177                 :            : bool ReserveDestination::GetReservedDestination(CTxDestination& dest, bool internal)
#    2178                 :       4870 : {
#    2179                 :       4870 :     m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
#    2180         [ +  + ]:       4870 :     if (!m_spk_man) {
#    2181                 :         13 :         return false;
#    2182                 :         13 :     }
#    2183                 :            : 
#    2184                 :            : 
#    2185         [ +  - ]:       4857 :     if (nIndex == -1)
#    2186                 :       4857 :     {
#    2187                 :       4857 :         m_spk_man->TopUp();
#    2188                 :            : 
#    2189                 :       4857 :         CKeyPool keypool;
#    2190         [ +  + ]:       4857 :         if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
#    2191                 :         20 :             return false;
#    2192                 :         20 :         }
#    2193                 :       4837 :         fInternal = keypool.fInternal;
#    2194                 :       4837 :     }
#    2195                 :       4857 :     dest = address;
#    2196                 :       4837 :     return true;
#    2197                 :       4857 : }
#    2198                 :            : 
#    2199                 :            : void ReserveDestination::KeepDestination()
#    2200                 :       5068 : {
#    2201         [ +  + ]:       5068 :     if (nIndex != -1) {
#    2202                 :       4716 :         m_spk_man->KeepDestination(nIndex, type);
#    2203                 :       4716 :     }
#    2204                 :       5068 :     nIndex = -1;
#    2205                 :       5068 :     address = CNoDestination();
#    2206                 :       5068 : }
#    2207                 :            : 
#    2208                 :            : void ReserveDestination::ReturnDestination()
#    2209                 :       5204 : {
#    2210         [ +  + ]:       5204 :     if (nIndex != -1) {
#    2211                 :        125 :         m_spk_man->ReturnDestination(nIndex, fInternal, address);
#    2212                 :        125 :     }
#    2213                 :       5204 :     nIndex = -1;
#    2214                 :       5204 :     address = CNoDestination();
#    2215                 :       5204 : }
#    2216                 :            : 
#    2217                 :            : bool CWallet::DisplayAddress(const CTxDestination& dest)
#    2218                 :          0 : {
#    2219                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#    2220                 :            :     CScript scriptPubKey = GetScriptForDestination(dest);
#    2221                 :            :     const auto spk_man = GetScriptPubKeyMan(scriptPubKey);
#    2222                 :            :     if (spk_man == nullptr) {
#    2223                 :            :         return false;
#    2224                 :            :     }
#    2225                 :            :     auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan*>(spk_man);
#    2226                 :            :     if (signer_spk_man == nullptr) {
#    2227                 :            :         return false;
#    2228                 :            :     }
#    2229                 :            :     ExternalSigner signer = ExternalSignerScriptPubKeyMan::GetExternalSigner();
#    2230                 :            :     return signer_spk_man->DisplayAddress(scriptPubKey, signer);
#    2231                 :            : #else
#    2232                 :          0 :     return false;
#    2233                 :          0 : #endif
#    2234                 :          0 : }
#    2235                 :            : 
#    2236                 :            : void CWallet::LockCoin(const COutPoint& output)
#    2237                 :         16 : {
#    2238                 :         16 :     AssertLockHeld(cs_wallet);
#    2239                 :         16 :     setLockedCoins.insert(output);
#    2240                 :         16 : }
#    2241                 :            : 
#    2242                 :            : void CWallet::UnlockCoin(const COutPoint& output)
#    2243                 :          4 : {
#    2244                 :          4 :     AssertLockHeld(cs_wallet);
#    2245                 :          4 :     setLockedCoins.erase(output);
#    2246                 :          4 : }
#    2247                 :            : 
#    2248                 :            : void CWallet::UnlockAllCoins()
#    2249                 :          0 : {
#    2250                 :          0 :     AssertLockHeld(cs_wallet);
#    2251                 :          0 :     setLockedCoins.clear();
#    2252                 :          0 : }
#    2253                 :            : 
#    2254                 :            : bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
#    2255                 :    1782150 : {
#    2256                 :    1782150 :     AssertLockHeld(cs_wallet);
#    2257                 :    1782150 :     COutPoint outpt(hash, n);
#    2258                 :            : 
#    2259                 :    1782150 :     return (setLockedCoins.count(outpt) > 0);
#    2260                 :    1782150 : }
#    2261                 :            : 
#    2262                 :            : void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
#    2263                 :         19 : {
#    2264                 :         19 :     AssertLockHeld(cs_wallet);
#    2265                 :         19 :     for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
#    2266         [ +  + ]:         29 :          it != setLockedCoins.end(); it++) {
#    2267                 :         10 :         COutPoint outpt = (*it);
#    2268                 :         10 :         vOutpts.push_back(outpt);
#    2269                 :         10 :     }
#    2270                 :         19 : }
#    2271                 :            : 
#    2272                 :            : /** @} */ // end of Actions
#    2273                 :            : 
#    2274                 :          6 : void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
#    2275                 :          6 :     AssertLockHeld(cs_wallet);
#    2276                 :          6 :     mapKeyBirth.clear();
#    2277                 :            : 
#    2278                 :          6 :     LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
#    2279                 :          6 :     assert(spk_man != nullptr);
#    2280                 :          6 :     LOCK(spk_man->cs_KeyStore);
#    2281                 :            : 
#    2282                 :            :     // get birth times for keys with metadata
#    2283         [ +  + ]:       1250 :     for (const auto& entry : spk_man->mapKeyMetadata) {
#    2284         [ +  - ]:       1250 :         if (entry.second.nCreateTime) {
#    2285                 :       1250 :             mapKeyBirth[entry.first] = entry.second.nCreateTime;
#    2286                 :       1250 :         }
#    2287                 :       1250 :     }
#    2288                 :            : 
#    2289                 :            :     // map in which we'll infer heights of other keys
#    2290                 :          6 :     std::map<CKeyID, const CWalletTx::Confirmation*> mapKeyFirstBlock;
#    2291                 :          6 :     CWalletTx::Confirmation max_confirm;
#    2292         [ +  + ]:          6 :     max_confirm.block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
#    2293         [ -  + ]:          6 :     CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.block_height, FoundBlock().hash(max_confirm.hashBlock)));
#    2294         [ +  + ]:       1250 :     for (const CKeyID &keyid : spk_man->GetKeys()) {
#    2295         [ -  + ]:       1250 :         if (mapKeyBirth.count(keyid) == 0)
#    2296                 :          0 :             mapKeyFirstBlock[keyid] = &max_confirm;
#    2297                 :       1250 :     }
#    2298                 :            : 
#    2299                 :            :     // if there are no such keys, we're done
#    2300         [ +  - ]:          6 :     if (mapKeyFirstBlock.empty())
#    2301                 :          6 :         return;
#    2302                 :            : 
#    2303                 :            :     // find first block that affects those keys, if there are any left
#    2304         [ #  # ]:          0 :     for (const auto& entry : mapWallet) {
#    2305                 :            :         // iterate over all wallet transactions...
#    2306                 :          0 :         const CWalletTx &wtx = entry.second;
#    2307         [ #  # ]:          0 :         if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
#    2308                 :            :             // ... which are already in a block
#    2309         [ #  # ]:          0 :             for (const CTxOut &txout : wtx.tx->vout) {
#    2310                 :            :                 // iterate over all their outputs
#    2311         [ #  # ]:          0 :                 for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
#    2312                 :            :                     // ... and all their affected keys
#    2313                 :          0 :                     auto rit = mapKeyFirstBlock.find(keyid);
#    2314 [ #  # ][ #  # ]:          0 :                     if (rit != mapKeyFirstBlock.end() && wtx.m_confirm.block_height < rit->second->block_height) {
#                 [ #  # ]
#    2315                 :          0 :                         rit->second = &wtx.m_confirm;
#    2316                 :          0 :                     }
#    2317                 :          0 :                 }
#    2318                 :          0 :             }
#    2319                 :          0 :         }
#    2320                 :          0 :     }
#    2321                 :            : 
#    2322                 :            :     // Extract block timestamps for those keys
#    2323         [ #  # ]:          0 :     for (const auto& entry : mapKeyFirstBlock) {
#    2324                 :          0 :         int64_t block_time;
#    2325         [ #  # ]:          0 :         CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock, FoundBlock().time(block_time)));
#    2326                 :          0 :         mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
#    2327                 :          0 :     }
#    2328                 :          0 : }
#    2329                 :            : 
#    2330                 :            : /**
#    2331                 :            :  * Compute smart timestamp for a transaction being added to the wallet.
#    2332                 :            :  *
#    2333                 :            :  * Logic:
#    2334                 :            :  * - If sending a transaction, assign its timestamp to the current time.
#    2335                 :            :  * - If receiving a transaction outside a block, assign its timestamp to the
#    2336                 :            :  *   current time.
#    2337                 :            :  * - If receiving a block with a future timestamp, assign all its (not already
#    2338                 :            :  *   known) transactions' timestamps to the current time.
#    2339                 :            :  * - If receiving a block with a past timestamp, before the most recent known
#    2340                 :            :  *   transaction (that we care about), assign all its (not already known)
#    2341                 :            :  *   transactions' timestamps to the same timestamp as that most-recent-known
#    2342                 :            :  *   transaction.
#    2343                 :            :  * - If receiving a block with a past timestamp, but after the most recent known
#    2344                 :            :  *   transaction, assign all its (not already known) transactions' timestamps to
#    2345                 :            :  *   the block time.
#    2346                 :            :  *
#    2347                 :            :  * For more information see CWalletTx::nTimeSmart,
#    2348                 :            :  * https://bitcointalk.org/?topic=54527, or
#    2349                 :            :  * https://github.com/bitcoin/bitcoin/pull/1393.
#    2350                 :            :  */
#    2351                 :            : unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
#    2352                 :     138063 : {
#    2353                 :     138063 :     unsigned int nTimeSmart = wtx.nTimeReceived;
#    2354 [ +  + ][ +  - ]:     138063 :     if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
#    2355                 :      23823 :         int64_t blocktime;
#    2356         [ +  - ]:      23823 :         if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
#    2357                 :      23823 :             int64_t latestNow = wtx.nTimeReceived;
#    2358                 :      23823 :             int64_t latestEntry = 0;
#    2359                 :            : 
#    2360                 :            :             // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
#    2361                 :      23823 :             int64_t latestTolerated = latestNow + 300;
#    2362                 :      23823 :             const TxItems& txOrdered = wtxOrdered;
#    2363         [ +  + ]:      47660 :             for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
#    2364                 :      47404 :                 CWalletTx* const pwtx = it->second;
#    2365         [ +  + ]:      47404 :                 if (pwtx == &wtx) {
#    2366                 :      23823 :                     continue;
#    2367                 :      23823 :                 }
#    2368                 :      23581 :                 int64_t nSmartTime;
#    2369                 :      23581 :                 nSmartTime = pwtx->nTimeSmart;
#    2370         [ -  + ]:      23581 :                 if (!nSmartTime) {
#    2371                 :          0 :                     nSmartTime = pwtx->nTimeReceived;
#    2372                 :          0 :                 }
#    2373         [ +  + ]:      23581 :                 if (nSmartTime <= latestTolerated) {
#    2374                 :      23567 :                     latestEntry = nSmartTime;
#    2375         [ +  + ]:      23567 :                     if (nSmartTime > latestNow) {
#    2376                 :          1 :                         latestNow = nSmartTime;
#    2377                 :          1 :                     }
#    2378                 :      23567 :                     break;
#    2379                 :      23567 :                 }
#    2380                 :      23581 :             }
#    2381                 :            : 
#    2382                 :      23823 :             nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
#    2383                 :      23823 :         } else {
#    2384                 :          0 :             WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
#    2385                 :          0 :         }
#    2386                 :      23823 :     }
#    2387                 :     138063 :     return nTimeSmart;
#    2388                 :     138063 : }
#    2389                 :            : 
#    2390                 :            : bool CWallet::AddDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key, const std::string &value)
#    2391                 :         46 : {
#    2392         [ -  + ]:         46 :     if (std::get_if<CNoDestination>(&dest))
#    2393                 :          0 :         return false;
#    2394                 :            : 
#    2395                 :         46 :     m_address_book[dest].destdata.insert(std::make_pair(key, value));
#    2396                 :         46 :     return batch.WriteDestData(EncodeDestination(dest), key, value);
#    2397                 :         46 : }
#    2398                 :            : 
#    2399                 :            : bool CWallet::EraseDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key)
#    2400                 :          0 : {
#    2401         [ #  # ]:          0 :     if (!m_address_book[dest].destdata.erase(key))
#    2402                 :          0 :         return false;
#    2403                 :          0 :     return batch.EraseDestData(EncodeDestination(dest), key);
#    2404                 :          0 : }
#    2405                 :            : 
#    2406                 :            : void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
#    2407                 :          0 : {
#    2408                 :          0 :     m_address_book[dest].destdata.insert(std::make_pair(key, value));
#    2409                 :          0 : }
#    2410                 :            : 
#    2411                 :            : bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
#    2412                 :       5781 : {
#    2413                 :       5781 :     std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
#    2414         [ +  + ]:       5781 :     if(i != m_address_book.end())
#    2415                 :       4105 :     {
#    2416                 :       4105 :         CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
#    2417         [ +  + ]:       4105 :         if(j != i->second.destdata.end())
#    2418                 :       2421 :         {
#    2419         [ -  + ]:       2421 :             if(value)
#    2420                 :          0 :                 *value = j->second;
#    2421                 :       2421 :             return true;
#    2422                 :       2421 :         }
#    2423                 :       3360 :     }
#    2424                 :       3360 :     return false;
#    2425                 :       3360 : }
#    2426                 :            : 
#    2427                 :            : std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
#    2428                 :          1 : {
#    2429                 :          1 :     std::vector<std::string> values;
#    2430         [ +  + ]:          1 :     for (const auto& address : m_address_book) {
#    2431         [ +  + ]:          3 :         for (const auto& data : address.second.destdata) {
#    2432         [ +  + ]:          3 :             if (!data.first.compare(0, prefix.size(), prefix)) {
#    2433                 :          2 :                 values.emplace_back(data.second);
#    2434                 :          2 :             }
#    2435                 :          3 :         }
#    2436                 :          1 :     }
#    2437                 :          1 :     return values;
#    2438                 :          1 : }
#    2439                 :            : 
#    2440                 :            : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
#    2441                 :       1393 : {
#    2442                 :            :     // Do some checking on wallet path. It should be either a:
#    2443                 :            :     //
#    2444                 :            :     // 1. Path where a directory can be created.
#    2445                 :            :     // 2. Path to an existing directory.
#    2446                 :            :     // 3. Path to a symlink to a directory.
#    2447                 :            :     // 4. For backwards compatibility, the name of a data file in -walletdir.
#    2448                 :       1393 :     const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), name);
#    2449                 :       1393 :     fs::file_type path_type = fs::symlink_status(wallet_path).type();
#    2450 [ +  + ][ +  + ]:       1393 :     if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
#                 [ +  + ]
#    2451 [ +  + ][ +  + ]:       1393 :           (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
#    2452 [ +  + ][ +  - ]:       1393 :           (path_type == fs::regular_file && fs::path(name).filename() == name))) {
#    2453                 :          6 :         error_string = Untranslated(strprintf(
#    2454                 :          6 :               "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
#    2455                 :          6 :               "database/log.?????????? files can be stored, a location where such a directory could be created, "
#    2456                 :          6 :               "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
#    2457                 :          6 :               name, GetWalletDir()));
#    2458                 :          6 :         status = DatabaseStatus::FAILED_BAD_PATH;
#    2459                 :          6 :         return nullptr;
#    2460                 :          6 :     }
#    2461                 :       1387 :     return MakeDatabase(wallet_path, options, status, error_string);
#    2462                 :       1387 : }
#    2463                 :            : 
#    2464                 :            : std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings)
#    2465                 :        745 : {
#    2466                 :        745 :     const std::string& walletFile = database->Filename();
#    2467                 :            : 
#    2468                 :        745 :     int64_t nStart = GetTimeMillis();
#    2469                 :            :     // TODO: Can't use std::make_shared because we need a custom deleter but
#    2470                 :            :     // should be possible to use std::allocate_shared.
#    2471                 :        745 :     std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
#    2472                 :        745 :     DBErrors nLoadWalletRet = walletInstance->LoadWallet();
#    2473         [ -  + ]:        745 :     if (nLoadWalletRet != DBErrors::LOAD_OK) {
#    2474         [ #  # ]:          0 :         if (nLoadWalletRet == DBErrors::CORRUPT) {
#    2475                 :          0 :             error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
#    2476                 :          0 :             return nullptr;
#    2477                 :          0 :         }
#    2478         [ #  # ]:          0 :         else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
#    2479                 :          0 :         {
#    2480                 :          0 :             warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
#    2481                 :          0 :                                            " or address book entries might be missing or incorrect."),
#    2482                 :          0 :                 walletFile));
#    2483                 :          0 :         }
#    2484         [ #  # ]:          0 :         else if (nLoadWalletRet == DBErrors::TOO_NEW) {
#    2485                 :          0 :             error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
#    2486                 :          0 :             return nullptr;
#    2487                 :          0 :         }
#    2488         [ #  # ]:          0 :         else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
#    2489                 :          0 :         {
#    2490                 :          0 :             error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
#    2491                 :          0 :             return nullptr;
#    2492                 :          0 :         }
#    2493                 :          0 :         else {
#    2494                 :          0 :             error = strprintf(_("Error loading %s"), walletFile);
#    2495                 :          0 :             return nullptr;
#    2496                 :          0 :         }
#    2497                 :        745 :     }
#    2498                 :            : 
#    2499                 :            :     // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
#    2500         [ +  + ]:        745 :     const bool fFirstRun = walletInstance->m_spk_managers.empty() &&
#    2501         [ +  - ]:        745 :                      !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
#    2502         [ +  + ]:        745 :                      !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
#    2503         [ +  + ]:        745 :     if (fFirstRun)
#    2504                 :        414 :     {
#    2505                 :            :         // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
#    2506                 :        414 :         walletInstance->SetMinVersion(FEATURE_LATEST);
#    2507                 :            : 
#    2508                 :        414 :         walletInstance->AddWalletFlags(wallet_creation_flags);
#    2509                 :            : 
#    2510                 :            :         // Only create LegacyScriptPubKeyMan when not descriptor wallet
#    2511         [ +  + ]:        414 :         if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    2512                 :        265 :             walletInstance->SetupLegacyScriptPubKeyMan();
#    2513                 :        265 :         }
#    2514                 :            : 
#    2515 [ -  + ][ +  + ]:        414 :         if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) || !(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
#    2516                 :        344 :             LOCK(walletInstance->cs_wallet);
#    2517         [ +  + ]:        344 :             if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    2518                 :        115 :                 walletInstance->SetupDescriptorScriptPubKeyMans();
#    2519                 :            :                 // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
#    2520                 :        229 :             } else {
#    2521                 :            :                 // Legacy wallets need SetupGeneration here.
#    2522         [ +  + ]:        229 :                 for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
#    2523         [ -  + ]:        229 :                     if (!spk_man->SetupGeneration()) {
#    2524                 :          0 :                         error = _("Unable to generate initial keys");
#    2525                 :          0 :                         return nullptr;
#    2526                 :          0 :                     }
#    2527                 :        229 :                 }
#    2528                 :        229 :             }
#    2529                 :        344 :         }
#    2530                 :            : 
#    2531         [ +  + ]:        414 :         if (chain) {
#    2532                 :        413 :             walletInstance->chainStateFlushed(chain->getTipLocator());
#    2533                 :        413 :         }
#    2534         [ -  + ]:        414 :     } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
#    2535                 :            :         // Make it impossible to disable private keys after creation
#    2536                 :          0 :         error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
#    2537                 :          0 :         return NULL;
#    2538         [ +  + ]:        331 :     } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
#    2539         [ +  + ]:         28 :         for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
#    2540         [ -  + ]:         16 :             if (spk_man->HavePrivateKeys()) {
#    2541                 :          0 :                 warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
#    2542                 :          0 :                 break;
#    2543                 :          0 :             }
#    2544                 :         16 :         }
#    2545                 :         28 :     }
#    2546                 :            : 
#    2547         [ +  + ]:        745 :     if (!gArgs.GetArg("-addresstype", "").empty()) {
#    2548         [ -  + ]:         56 :         if (!ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
#    2549                 :          0 :             error = strprintf(_("Unknown address type '%s'"), gArgs.GetArg("-addresstype", ""));
#    2550                 :          0 :             return nullptr;
#    2551                 :          0 :         }
#    2552                 :        745 :     }
#    2553                 :            : 
#    2554         [ +  + ]:        745 :     if (!gArgs.GetArg("-changetype", "").empty()) {
#    2555                 :          6 :         OutputType out_type;
#    2556         [ -  + ]:          6 :         if (!ParseOutputType(gArgs.GetArg("-changetype", ""), out_type)) {
#    2557                 :          0 :             error = strprintf(_("Unknown change type '%s'"), gArgs.GetArg("-changetype", ""));
#    2558                 :          0 :             return nullptr;
#    2559                 :          0 :         }
#    2560                 :          6 :         walletInstance->m_default_change_type = out_type;
#    2561                 :          6 :     }
#    2562                 :            : 
#    2563         [ +  + ]:        745 :     if (gArgs.IsArgSet("-mintxfee")) {
#    2564                 :         18 :         CAmount n = 0;
#    2565 [ -  + ][ -  + ]:         18 :         if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
#                 [ -  + ]
#    2566                 :          0 :             error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
#    2567                 :          0 :             return nullptr;
#    2568                 :          0 :         }
#    2569         [ -  + ]:         18 :         if (n > HIGH_TX_FEE_PER_KB) {
#    2570                 :          0 :             warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
#    2571                 :          0 :                                _("This is the minimum transaction fee you pay on every transaction."));
#    2572                 :          0 :         }
#    2573                 :         18 :         walletInstance->m_min_fee = CFeeRate(n);
#    2574                 :         18 :     }
#    2575                 :            : 
#    2576         [ +  + ]:        745 :     if (gArgs.IsArgSet("-maxapsfee")) {
#    2577                 :          4 :         const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
#    2578                 :          4 :         CAmount n = 0;
#    2579         [ -  + ]:          4 :         if (max_aps_fee == "-1") {
#    2580                 :          0 :             n = -1;
#    2581         [ -  + ]:          4 :         } else if (!ParseMoney(max_aps_fee, n)) {
#    2582                 :          0 :             error = AmountErrMsg("maxapsfee", max_aps_fee);
#    2583                 :          0 :             return nullptr;
#    2584                 :          0 :         }
#    2585         [ -  + ]:          4 :         if (n > HIGH_APS_FEE) {
#    2586                 :          0 :             warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
#    2587                 :          0 :                               _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
#    2588                 :          0 :         }
#    2589                 :          4 :         walletInstance->m_max_aps_fee = n;
#    2590                 :          4 :     }
#    2591                 :            : 
#    2592         [ +  + ]:        745 :     if (gArgs.IsArgSet("-fallbackfee")) {
#    2593                 :        734 :         CAmount nFeePerK = 0;
#    2594         [ -  + ]:        734 :         if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
#    2595                 :          0 :             error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""));
#    2596                 :          0 :             return nullptr;
#    2597                 :          0 :         }
#    2598         [ -  + ]:        734 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
#    2599                 :          0 :             warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
#    2600                 :          0 :                                _("This is the transaction fee you may pay when fee estimates are not available."));
#    2601                 :          0 :         }
#    2602                 :        734 :         walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
#    2603                 :        734 :     }
#    2604                 :            :     // Disable fallback fee in case value was set to 0, enable if non-null value
#    2605                 :        745 :     walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
#    2606                 :            : 
#    2607         [ -  + ]:        745 :     if (gArgs.IsArgSet("-discardfee")) {
#    2608                 :          0 :         CAmount nFeePerK = 0;
#    2609         [ #  # ]:          0 :         if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
#    2610                 :          0 :             error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""));
#    2611                 :          0 :             return nullptr;
#    2612                 :          0 :         }
#    2613         [ #  # ]:          0 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
#    2614                 :          0 :             warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
#    2615                 :          0 :                                _("This is the transaction fee you may discard if change is smaller than dust at this level"));
#    2616                 :          0 :         }
#    2617                 :          0 :         walletInstance->m_discard_rate = CFeeRate(nFeePerK);
#    2618                 :          0 :     }
#    2619         [ +  + ]:        745 :     if (gArgs.IsArgSet("-paytxfee")) {
#    2620                 :          2 :         CAmount nFeePerK = 0;
#    2621         [ -  + ]:          2 :         if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
#    2622                 :          0 :             error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
#    2623                 :          0 :             return nullptr;
#    2624                 :          0 :         }
#    2625         [ -  + ]:          2 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
#    2626                 :          0 :             warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
#    2627                 :          0 :                                _("This is the transaction fee you will pay if you send a transaction."));
#    2628                 :          0 :         }
#    2629                 :          2 :         walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
#    2630 [ +  - ][ -  + ]:          2 :         if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
#                 [ -  + ]
#    2631                 :          0 :             error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
#    2632                 :          0 :                 gArgs.GetArg("-paytxfee", ""), chain->relayMinFee().ToString());
#    2633                 :          0 :             return nullptr;
#    2634                 :          0 :         }
#    2635                 :        745 :     }
#    2636                 :            : 
#    2637         [ +  + ]:        745 :     if (gArgs.IsArgSet("-maxtxfee")) {
#    2638                 :          4 :         CAmount nMaxFee = 0;
#    2639         [ -  + ]:          4 :         if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
#    2640                 :          0 :             error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
#    2641                 :          0 :             return nullptr;
#    2642                 :          0 :         }
#    2643         [ -  + ]:          4 :         if (nMaxFee > HIGH_MAX_TX_FEE) {
#    2644                 :          0 :             warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
#    2645                 :          0 :         }
#    2646 [ +  - ][ -  + ]:          4 :         if (chain && CFeeRate(nMaxFee, 1000) < chain->relayMinFee()) {
#                 [ -  + ]
#    2647                 :          0 :             error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
#    2648                 :          0 :                 gArgs.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
#    2649                 :          0 :             return nullptr;
#    2650                 :          0 :         }
#    2651                 :          4 :         walletInstance->m_default_max_tx_fee = nMaxFee;
#    2652                 :          4 :     }
#    2653                 :            : 
#    2654 [ +  + ][ -  + ]:        745 :     if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
#                 [ -  + ]
#    2655                 :          0 :         warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
#    2656                 :          0 :                            _("The wallet will avoid paying less than the minimum relay fee."));
#    2657                 :          0 :     }
#    2658                 :            : 
#    2659                 :        745 :     walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
#    2660                 :        745 :     walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
#    2661                 :        745 :     walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
#    2662                 :            : 
#    2663                 :        745 :     walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
#    2664                 :            : 
#    2665                 :            :     // Try to top up keypool. No-op if the wallet is locked.
#    2666                 :        745 :     walletInstance->TopUpKeyPool();
#    2667                 :            : 
#    2668                 :        745 :     LOCK(walletInstance->cs_wallet);
#    2669                 :            : 
#    2670 [ +  + ][ -  + ]:        745 :     if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
#    2671                 :          0 :         return nullptr;
#    2672                 :          0 :     }
#    2673                 :            : 
#    2674                 :        745 :     {
#    2675                 :        745 :         LOCK(cs_wallets);
#    2676         [ +  + ]:        745 :         for (auto& load_wallet : g_load_wallet_fns) {
#    2677                 :          1 :             load_wallet(interfaces::MakeWallet(walletInstance));
#    2678                 :          1 :         }
#    2679                 :        745 :     }
#    2680                 :            : 
#    2681                 :        745 :     walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
#    2682                 :            : 
#    2683                 :        745 :     {
#    2684                 :        745 :         walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n",      walletInstance->GetKeyPoolSize());
#    2685                 :        745 :         walletInstance->WalletLogPrintf("mapWallet.size() = %u\n",       walletInstance->mapWallet.size());
#    2686                 :        745 :         walletInstance->WalletLogPrintf("m_address_book.size() = %u\n",  walletInstance->m_address_book.size());
#    2687                 :        745 :     }
#    2688                 :            : 
#    2689                 :        745 :     return walletInstance;
#    2690                 :        745 : }
#    2691                 :            : 
#    2692                 :            : bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings)
#    2693                 :        738 : {
#    2694                 :        738 :     LOCK(walletInstance->cs_wallet);
#    2695                 :            :     // allow setting the chain if it hasn't been set already but prevent changing it
#    2696                 :        738 :     assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
#    2697                 :        738 :     walletInstance->m_chain = &chain;
#    2698                 :            : 
#    2699                 :            :     // Register wallet with validationinterface. It's done before rescan to avoid
#    2700                 :            :     // missing block connections between end of rescan and validation subscribing.
#    2701                 :            :     // Because of wallet lock being hold, block connection notifications are going to
#    2702                 :            :     // be pending on the validation-side until lock release. It's likely to have
#    2703                 :            :     // block processing duplicata (if rescan block range overlaps with notification one)
#    2704                 :            :     // but we guarantee at least than wallet state is correct after notifications delivery.
#    2705                 :            :     // This is temporary until rescan and notifications delivery are unified under same
#    2706                 :            :     // interface.
#    2707                 :        738 :     walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
#    2708                 :            : 
#    2709                 :        738 :     int rescan_height = 0;
#    2710         [ +  + ]:        738 :     if (!gArgs.GetBoolArg("-rescan", false))
#    2711                 :        728 :     {
#    2712                 :        728 :         WalletBatch batch(walletInstance->GetDatabase());
#    2713                 :        728 :         CBlockLocator locator;
#    2714         [ +  + ]:        728 :         if (batch.ReadBestBlock(locator)) {
#    2715         [ +  + ]:        726 :             if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
#    2716                 :        713 :                 rescan_height = *fork_height;
#    2717                 :        713 :             }
#    2718                 :        726 :         }
#    2719                 :        728 :     }
#    2720                 :            : 
#    2721                 :        738 :     const std::optional<int> tip_height = chain.getHeight();
#    2722         [ +  + ]:        738 :     if (tip_height) {
#    2723                 :        725 :         walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
#    2724                 :        725 :         walletInstance->m_last_block_processed_height = *tip_height;
#    2725                 :        725 :     } else {
#    2726                 :         13 :         walletInstance->m_last_block_processed.SetNull();
#    2727                 :         13 :         walletInstance->m_last_block_processed_height = -1;
#    2728                 :         13 :     }
#    2729                 :            : 
#    2730 [ +  + ][ +  + ]:        738 :     if (tip_height && *tip_height != rescan_height)
#    2731                 :        101 :     {
#    2732         [ -  + ]:        101 :         if (chain.havePruned()) {
#    2733                 :          0 :             int block_height = *tip_height;
#    2734 [ #  # ][ #  # ]:          0 :             while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
#                 [ #  # ]
#    2735                 :          0 :                 --block_height;
#    2736                 :          0 :             }
#    2737                 :            : 
#    2738         [ #  # ]:          0 :             if (rescan_height != block_height) {
#    2739                 :            :                 // We can't rescan beyond non-pruned blocks, stop and throw an error.
#    2740                 :            :                 // This might happen if a user uses an old wallet within a pruned node
#    2741                 :            :                 // or if they ran -disablewallet for a longer time, then decided to re-enable
#    2742                 :            :                 // Exit early and print an error.
#    2743                 :            :                 // If a block is pruned after this check, we will load the wallet,
#    2744                 :            :                 // but fail the rescan with a generic error.
#    2745                 :          0 :                 error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
#    2746                 :          0 :                 return false;
#    2747                 :          0 :             }
#    2748                 :        101 :         }
#    2749                 :            : 
#    2750                 :        101 :         chain.initMessage(_("Rescanning…").translated);
#    2751                 :        101 :         walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
#    2752                 :            : 
#    2753                 :            :         // No need to read and scan block if block was created before
#    2754                 :            :         // our wallet birthday (as adjusted for block time variability)
#    2755                 :        101 :         std::optional<int64_t> time_first_key;
#    2756         [ +  + ]:        294 :         for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
#    2757                 :        294 :             int64_t time = spk_man->GetTimeFirstKey();
#    2758 [ +  + ][ +  + ]:        294 :             if (!time_first_key || time < *time_first_key) time_first_key = time;
#    2759                 :        294 :         }
#    2760         [ +  - ]:        101 :         if (time_first_key) {
#    2761                 :        101 :             chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, FoundBlock().height(rescan_height));
#    2762                 :        101 :         }
#    2763                 :            : 
#    2764                 :        101 :         {
#    2765                 :        101 :             WalletRescanReserver reserver(*walletInstance);
#    2766 [ -  + ][ -  + ]:        101 :             if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
#                 [ -  + ]
#    2767                 :          0 :                 error = _("Failed to rescan the wallet during initialization");
#    2768                 :          0 :                 return false;
#    2769                 :          0 :             }
#    2770                 :        101 :         }
#    2771                 :        101 :         walletInstance->chainStateFlushed(chain.getTipLocator());
#    2772                 :        101 :         walletInstance->GetDatabase().IncrementUpdateCounter();
#    2773                 :        101 :     }
#    2774                 :            : 
#    2775                 :        738 :     return true;
#    2776                 :        738 : }
#    2777                 :            : 
#    2778                 :            : const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
#    2779                 :      67919 : {
#    2780                 :      67919 :     const auto& address_book_it = m_address_book.find(dest);
#    2781         [ +  + ]:      67919 :     if (address_book_it == m_address_book.end()) return nullptr;
#    2782 [ +  - ][ +  + ]:      56687 :     if ((!allow_change) && address_book_it->second.IsChange()) {
#    2783                 :         16 :         return nullptr;
#    2784                 :         16 :     }
#    2785                 :      56671 :     return &address_book_it->second;
#    2786                 :      56671 : }
#    2787                 :            : 
#    2788                 :            : bool CWallet::UpgradeWallet(int version, bilingual_str& error)
#    2789                 :          0 : {
#    2790                 :          0 :     int prev_version = GetVersion();
#    2791         [ #  # ]:          0 :     if (version == 0) {
#    2792                 :          0 :         WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
#    2793                 :          0 :         version = FEATURE_LATEST;
#    2794                 :          0 :     } else {
#    2795                 :          0 :         WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
#    2796                 :          0 :     }
#    2797         [ #  # ]:          0 :     if (version < prev_version) {
#    2798                 :          0 :         error = strprintf(_("Cannot downgrade wallet from version %i to version %i. Wallet version unchanged."), prev_version, version);
#    2799                 :          0 :         return false;
#    2800                 :          0 :     }
#    2801                 :            : 
#    2802                 :          0 :     LOCK(cs_wallet);
#    2803                 :            : 
#    2804                 :            :     // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
#    2805 [ #  # ][ #  # ]:          0 :     if (!CanSupportFeature(FEATURE_HD_SPLIT) && version >= FEATURE_HD_SPLIT && version < FEATURE_PRE_SPLIT_KEYPOOL) {
#                 [ #  # ]
#    2806                 :          0 :         error = strprintf(_("Cannot upgrade a non HD split wallet from version %i to version %i without upgrading to support pre-split keypool. Please use version %i or no version specified."), prev_version, version, FEATURE_PRE_SPLIT_KEYPOOL);
#    2807                 :          0 :         return false;
#    2808                 :          0 :     }
#    2809                 :            : 
#    2810                 :            :     // Permanently upgrade to the version
#    2811                 :          0 :     SetMinVersion(GetClosestWalletFeature(version));
#    2812                 :            : 
#    2813         [ #  # ]:          0 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
#    2814         [ #  # ]:          0 :         if (!spk_man->Upgrade(prev_version, version, error)) {
#    2815                 :          0 :             return false;
#    2816                 :          0 :         }
#    2817                 :          0 :     }
#    2818                 :          0 :     return true;
#    2819                 :          0 : }
#    2820                 :            : 
#    2821                 :            : void CWallet::postInitProcess()
#    2822                 :        736 : {
#    2823                 :        736 :     LOCK(cs_wallet);
#    2824                 :            : 
#    2825                 :            :     // Add wallet transactions that aren't already in a block to mempool
#    2826                 :            :     // Do this here as mempool requires genesis block to be loaded
#    2827                 :        736 :     ReacceptWalletTransactions();
#    2828                 :            : 
#    2829                 :            :     // Update wallet transactions with current mempool transactions.
#    2830                 :        736 :     chain().requestMempoolTransactions(*this);
#    2831                 :        736 : }
#    2832                 :            : 
#    2833                 :            : bool CWallet::BackupWallet(const std::string& strDest) const
#    2834                 :         43 : {
#    2835                 :         43 :     return GetDatabase().Backup(strDest);
#    2836                 :         43 : }
#    2837                 :            : 
#    2838                 :            : CKeyPool::CKeyPool()
#    2839                 :      22912 : {
#    2840                 :      22912 :     nTime = GetTime();
#    2841                 :      22912 :     fInternal = false;
#    2842                 :      22912 :     m_pre_split = false;
#    2843                 :      22912 : }
#    2844                 :            : 
#    2845                 :            : CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
#    2846                 :      26395 : {
#    2847                 :      26395 :     nTime = GetTime();
#    2848                 :      26395 :     vchPubKey = vchPubKeyIn;
#    2849                 :      26395 :     fInternal = internalIn;
#    2850                 :      26395 :     m_pre_split = false;
#    2851                 :      26395 : }
#    2852                 :            : 
#    2853                 :            : int CWalletTx::GetDepthInMainChain() const
#    2854                 :    4401663 : {
#    2855                 :    4401663 :     assert(pwallet != nullptr);
#    2856                 :    4401663 :     AssertLockHeld(pwallet->cs_wallet);
#    2857 [ +  + ][ +  + ]:    4401663 :     if (isUnconfirmed() || isAbandoned()) return 0;
#    2858                 :            : 
#    2859         [ +  + ]:    3812078 :     return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
#    2860                 :    3812078 : }
#    2861                 :            : 
#    2862                 :            : int CWalletTx::GetBlocksToMaturity() const
#    2863                 :    1728031 : {
#    2864         [ +  + ]:    1728031 :     if (!IsCoinBase())
#    2865                 :     602516 :         return 0;
#    2866                 :    1125515 :     int chain_depth = GetDepthInMainChain();
#    2867                 :    1125515 :     assert(chain_depth >= 0); // coinbase tx should not be conflicted
#    2868                 :    1125515 :     return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
#    2869                 :    1125515 : }
#    2870                 :            : 
#    2871                 :            : bool CWalletTx::IsImmatureCoinBase() const
#    2872                 :    1728031 : {
#    2873                 :            :     // note GetBlocksToMaturity is 0 for non-coinbase tx
#    2874                 :    1728031 :     return GetBlocksToMaturity() > 0;
#    2875                 :    1728031 : }
#    2876                 :            : 
#    2877                 :            : bool CWallet::IsCrypted() const
#    2878                 :      28229 : {
#    2879                 :      28229 :     return HasEncryptionKeys();
#    2880                 :      28229 : }
#    2881                 :            : 
#    2882                 :            : bool CWallet::IsLocked() const
#    2883                 :      26267 : {
#    2884         [ +  + ]:      26267 :     if (!IsCrypted()) {
#    2885                 :      20012 :         return false;
#    2886                 :      20012 :     }
#    2887                 :       6255 :     LOCK(cs_wallet);
#    2888                 :       6255 :     return vMasterKey.empty();
#    2889                 :       6255 : }
#    2890                 :            : 
#    2891                 :            : bool CWallet::Lock()
#    2892                 :         82 : {
#    2893         [ -  + ]:         82 :     if (!IsCrypted())
#    2894                 :          0 :         return false;
#    2895                 :            : 
#    2896                 :         82 :     {
#    2897                 :         82 :         LOCK(cs_wallet);
#    2898                 :         82 :         vMasterKey.clear();
#    2899                 :         82 :     }
#    2900                 :            : 
#    2901                 :         82 :     NotifyStatusChanged(this);
#    2902                 :         82 :     return true;
#    2903                 :         82 : }
#    2904                 :            : 
#    2905                 :            : bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
#    2906                 :         90 : {
#    2907                 :         90 :     {
#    2908                 :         90 :         LOCK(cs_wallet);
#    2909         [ +  + ]:        452 :         for (const auto& spk_man_pair : m_spk_managers) {
#    2910         [ -  + ]:        452 :             if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
#    2911                 :          0 :                 return false;
#    2912                 :          0 :             }
#    2913                 :        452 :         }
#    2914                 :         90 :         vMasterKey = vMasterKeyIn;
#    2915                 :         90 :     }
#    2916                 :         90 :     NotifyStatusChanged(this);
#    2917                 :         90 :     return true;
#    2918                 :         90 : }
#    2919                 :            : 
#    2920                 :            : std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
#    2921                 :       4731 : {
#    2922                 :       4731 :     std::set<ScriptPubKeyMan*> spk_mans;
#    2923         [ +  + ]:       9462 :     for (bool internal : {false, true}) {
#    2924         [ +  + ]:      28386 :         for (OutputType t : OUTPUT_TYPES) {
#    2925                 :      28386 :             auto spk_man = GetScriptPubKeyMan(t, internal);
#    2926         [ +  + ]:      28386 :             if (spk_man) {
#    2927                 :      26024 :                 spk_mans.insert(spk_man);
#    2928                 :      26024 :             }
#    2929                 :      28386 :         }
#    2930                 :       9462 :     }
#    2931                 :       4731 :     return spk_mans;
#    2932                 :       4731 : }
#    2933                 :            : 
#    2934                 :            : std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
#    2935                 :       5916 : {
#    2936                 :       5916 :     std::set<ScriptPubKeyMan*> spk_mans;
#    2937         [ +  + ]:      17311 :     for (const auto& spk_man_pair : m_spk_managers) {
#    2938                 :      17311 :         spk_mans.insert(spk_man_pair.second.get());
#    2939                 :      17311 :     }
#    2940                 :       5916 :     return spk_mans;
#    2941                 :       5916 : }
#    2942                 :            : 
#    2943                 :            : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
#    2944                 :      58982 : {
#    2945         [ +  + ]:      58982 :     const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
#    2946                 :      58982 :     std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
#    2947         [ +  + ]:      58982 :     if (it == spk_managers.end()) {
#    2948         [ +  + ]:       2499 :         WalletLogPrintf("%s scriptPubKey Manager for output type %d does not exist\n", internal ? "Internal" : "External", static_cast<int>(type));
#    2949                 :       2499 :         return nullptr;
#    2950                 :       2499 :     }
#    2951                 :      56483 :     return it->second;
#    2952                 :      56483 : }
#    2953                 :            : 
#    2954                 :            : std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const
#    2955                 :          0 : {
#    2956                 :          0 :     std::set<ScriptPubKeyMan*> spk_mans;
#    2957         [ #  # ]:          0 :     for (const auto& spk_man_pair : m_spk_managers) {
#    2958         [ #  # ]:          0 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
#    2959                 :          0 :             spk_mans.insert(spk_man_pair.second.get());
#    2960                 :          0 :         }
#    2961                 :          0 :     }
#    2962                 :          0 :     return spk_mans;
#    2963                 :          0 : }
#    2964                 :            : 
#    2965                 :            : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const CScript& script) const
#    2966                 :       2366 : {
#    2967                 :       2366 :     SignatureData sigdata;
#    2968         [ +  + ]:       4940 :     for (const auto& spk_man_pair : m_spk_managers) {
#    2969         [ +  + ]:       4940 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
#    2970                 :       2180 :             return spk_man_pair.second.get();
#    2971                 :       2180 :         }
#    2972                 :       4940 :     }
#    2973                 :       2366 :     return nullptr;
#    2974                 :       2366 : }
#    2975                 :            : 
#    2976                 :            : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
#    2977                 :       1452 : {
#    2978         [ +  - ]:       1452 :     if (m_spk_managers.count(id) > 0) {
#    2979                 :       1452 :         return m_spk_managers.at(id).get();
#    2980                 :       1452 :     }
#    2981                 :          0 :     return nullptr;
#    2982                 :          0 : }
#    2983                 :            : 
#    2984                 :            : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
#    2985                 :    1034554 : {
#    2986                 :    1034554 :     SignatureData sigdata;
#    2987                 :    1034554 :     return GetSolvingProvider(script, sigdata);
#    2988                 :    1034554 : }
#    2989                 :            : 
#    2990                 :            : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
#    2991                 :    1034554 : {
#    2992         [ +  + ]:    2036609 :     for (const auto& spk_man_pair : m_spk_managers) {
#    2993         [ +  + ]:    2036609 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
#    2994                 :     924329 :             return spk_man_pair.second->GetSolvingProvider(script);
#    2995                 :     924329 :         }
#    2996                 :    2036609 :     }
#    2997                 :    1034554 :     return nullptr;
#    2998                 :    1034554 : }
#    2999                 :            : 
#    3000                 :            : LegacyScriptPubKeyMan* CWallet::GetLegacyScriptPubKeyMan() const
#    3001                 :      41091 : {
#    3002         [ +  + ]:      41091 :     if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    3003                 :       1127 :         return nullptr;
#    3004                 :       1127 :     }
#    3005                 :            :     // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
#    3006                 :            :     // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
#    3007                 :      39964 :     auto it = m_internal_spk_managers.find(OutputType::LEGACY);
#    3008         [ +  + ]:      39964 :     if (it == m_internal_spk_managers.end()) return nullptr;
#    3009                 :      39523 :     return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
#    3010                 :      39523 : }
#    3011                 :            : 
#    3012                 :            : LegacyScriptPubKeyMan* CWallet::GetOrCreateLegacyScriptPubKeyMan()
#    3013                 :      32726 : {
#    3014                 :      32726 :     SetupLegacyScriptPubKeyMan();
#    3015                 :      32726 :     return GetLegacyScriptPubKeyMan();
#    3016                 :      32726 : }
#    3017                 :            : 
#    3018                 :            : void CWallet::SetupLegacyScriptPubKeyMan()
#    3019                 :      33019 : {
#    3020 [ +  + ][ -  + ]:      33019 :     if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#         [ -  + ][ -  + ]
#    3021                 :      32491 :         return;
#    3022                 :      32491 :     }
#    3023                 :            : 
#    3024                 :        528 :     auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
#    3025         [ +  + ]:       1584 :     for (const auto& type : OUTPUT_TYPES) {
#    3026                 :       1584 :         m_internal_spk_managers[type] = spk_manager.get();
#    3027                 :       1584 :         m_external_spk_managers[type] = spk_manager.get();
#    3028                 :       1584 :     }
#    3029                 :        528 :     m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
#    3030                 :        528 : }
#    3031                 :            : 
#    3032                 :            : const CKeyingMaterial& CWallet::GetEncryptionKey() const
#    3033                 :       6075 : {
#    3034                 :       6075 :     return vMasterKey;
#    3035                 :       6075 : }
#    3036                 :            : 
#    3037                 :            : bool CWallet::HasEncryptionKeys() const
#    3038                 :    4043010 : {
#    3039                 :    4043010 :     return !mapMasterKeys.empty();
#    3040                 :    4043010 : }
#    3041                 :            : 
#    3042                 :            : void CWallet::ConnectScriptPubKeyManNotifiers()
#    3043                 :        930 : {
#    3044         [ +  + ]:       2369 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
#    3045                 :       2369 :         spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
#    3046                 :       2369 :         spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
#    3047                 :       2369 :     }
#    3048                 :        930 : }
#    3049                 :            : 
#    3050                 :            : void CWallet::LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc)
#    3051                 :        763 : {
#    3052         [ -  + ]:        763 :     if (IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
#    3053                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#    3054                 :            :         auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, desc));
#    3055                 :            :         m_spk_managers[id] = std::move(spk_manager);
#    3056                 :            : #else
#    3057                 :          0 :         throw std::runtime_error(std::string(__func__) + ": Compiled without external signing support (required for external signing)");
#    3058                 :          0 : #endif
#    3059                 :        763 :     } else {
#    3060                 :        763 :         auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
#    3061                 :        763 :         m_spk_managers[id] = std::move(spk_manager);
#    3062                 :        763 :     }
#    3063                 :        763 : }
#    3064                 :            : 
#    3065                 :            : void CWallet::SetupDescriptorScriptPubKeyMans()
#    3066                 :        125 : {
#    3067                 :        125 :     AssertLockHeld(cs_wallet);
#    3068                 :            : 
#    3069         [ +  - ]:        125 :     if (!IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
#    3070                 :            :         // Make a seed
#    3071                 :        125 :         CKey seed_key;
#    3072                 :        125 :         seed_key.MakeNewKey(true);
#    3073                 :        125 :         CPubKey seed = seed_key.GetPubKey();
#    3074                 :        125 :         assert(seed_key.VerifyPubKey(seed));
#    3075                 :            : 
#    3076                 :            :         // Get the extended key
#    3077                 :        125 :         CExtKey master_key;
#    3078                 :        125 :         master_key.SetSeed(seed_key.begin(), seed_key.size());
#    3079                 :            : 
#    3080         [ +  + ]:        250 :         for (bool internal : {false, true}) {
#    3081         [ +  + ]:        750 :             for (OutputType t : OUTPUT_TYPES) {
#    3082                 :        750 :                 auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, internal));
#    3083         [ +  + ]:        750 :                 if (IsCrypted()) {
#    3084         [ -  + ]:         54 :                     if (IsLocked()) {
#    3085                 :          0 :                         throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
#    3086                 :          0 :                     }
#    3087 [ -  + ][ #  # ]:         54 :                     if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
#    3088                 :          0 :                         throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
#    3089                 :          0 :                     }
#    3090                 :        750 :                 }
#    3091                 :        750 :                 spk_manager->SetupDescriptorGeneration(master_key, t);
#    3092                 :        750 :                 uint256 id = spk_manager->GetID();
#    3093                 :        750 :                 m_spk_managers[id] = std::move(spk_manager);
#    3094                 :        750 :                 AddActiveScriptPubKeyMan(id, t, internal);
#    3095                 :        750 :             }
#    3096                 :        250 :         }
#    3097                 :        125 :     } else {
#    3098                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#    3099                 :            :         ExternalSigner signer = ExternalSignerScriptPubKeyMan::GetExternalSigner();
#    3100                 :            : 
#    3101                 :            :         // TODO: add account parameter
#    3102                 :            :         int account = 0;
#    3103                 :            :         UniValue signer_res = signer.GetDescriptors(account);
#    3104                 :            : 
#    3105                 :            :         if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
#    3106                 :            :         for (bool internal : {false, true}) {
#    3107                 :            :             const UniValue& descriptor_vals = find_value(signer_res, internal ? "internal" : "receive");
#    3108                 :            :             if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
#    3109                 :            :             for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
#    3110                 :            :                 std::string desc_str = desc_val.getValStr();
#    3111                 :            :                 FlatSigningProvider keys;
#    3112                 :            :                 std::string dummy_error;
#    3113                 :            :                 std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, dummy_error, false);
#    3114                 :            :                 if (!desc->GetOutputType()) {
#    3115                 :            :                     continue;
#    3116                 :            :                 }
#    3117                 :            :                 OutputType t =  *desc->GetOutputType();
#    3118                 :            :                 auto spk_manager = std::unique_ptr<ExternalSignerScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, internal));
#    3119                 :            :                 spk_manager->SetupDescriptor(std::move(desc));
#    3120                 :            :                 uint256 id = spk_manager->GetID();
#    3121                 :            :                 m_spk_managers[id] = std::move(spk_manager);
#    3122                 :            :                 AddActiveScriptPubKeyMan(id, t, internal);
#    3123                 :            :             }
#    3124                 :            :         }
#    3125                 :            : #else
#    3126                 :          0 :         throw std::runtime_error(std::string(__func__) + ": Compiled without external signing support (required for external signing)");
#    3127                 :          0 : #endif // ENABLE_EXTERNAL_SIGNER
#    3128                 :          0 :     }
#    3129                 :        125 : }
#    3130                 :            : 
#    3131                 :            : void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
#    3132                 :        791 : {
#    3133                 :        791 :     WalletBatch batch(GetDatabase());
#    3134         [ -  + ]:        791 :     if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
#    3135                 :          0 :         throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
#    3136                 :          0 :     }
#    3137                 :        791 :     LoadActiveScriptPubKeyMan(id, type, internal);
#    3138                 :        791 : }
#    3139                 :            : 
#    3140                 :            : void CWallet::LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
#    3141                 :       1394 : {
#    3142                 :       1394 :     WalletLogPrintf("Setting spkMan to active: id = %s, type = %d, internal = %d\n", id.ToString(), static_cast<int>(type), static_cast<int>(internal));
#    3143         [ +  + ]:       1394 :     auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
#    3144                 :       1394 :     auto spk_man = m_spk_managers.at(id).get();
#    3145                 :       1394 :     spk_man->SetInternal(internal);
#    3146                 :       1394 :     spk_mans[type] = spk_man;
#    3147                 :            : 
#    3148                 :       1394 :     NotifyCanGetAddressesChanged();
#    3149                 :       1394 : }
#    3150                 :            : 
#    3151                 :            : bool CWallet::IsLegacy() const
#    3152                 :       2388 : {
#    3153         [ +  + ]:       2388 :     if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
#    3154                 :        456 :         return false;
#    3155                 :        456 :     }
#    3156                 :       1932 :     auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
#    3157                 :       1932 :     return spk_man != nullptr;
#    3158                 :       1932 : }
#    3159                 :            : 
#    3160                 :            : DescriptorScriptPubKeyMan* CWallet::GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const
#    3161                 :        380 : {
#    3162         [ +  + ]:       1796 :     for (auto& spk_man_pair : m_spk_managers) {
#    3163                 :            :         // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
#    3164                 :       1796 :         DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
#    3165 [ +  - ][ +  + ]:       1796 :         if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
#    3166                 :         26 :             return spk_manager;
#    3167                 :         26 :         }
#    3168                 :       1796 :     }
#    3169                 :            : 
#    3170                 :        380 :     return nullptr;
#    3171                 :        380 : }
#    3172                 :            : 
#    3173                 :            : ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
#    3174                 :        190 : {
#    3175         [ -  + ]:        190 :     if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
#    3176                 :          0 :         WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
#    3177                 :          0 :         return nullptr;
#    3178                 :          0 :     }
#    3179                 :            : 
#    3180                 :        190 :     LOCK(cs_wallet);
#    3181                 :        190 :     auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
#    3182                 :            : 
#    3183                 :            :     // If we already have this descriptor, remove it from the maps but add the existing cache to desc
#    3184                 :        190 :     auto old_spk_man = GetDescriptorScriptPubKeyMan(desc);
#    3185         [ +  + ]:        190 :     if (old_spk_man) {
#    3186                 :         13 :         WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
#    3187                 :            : 
#    3188                 :         13 :         {
#    3189                 :         13 :             LOCK(old_spk_man->cs_desc_man);
#    3190                 :         13 :             new_spk_man->SetCache(old_spk_man->GetWalletDescriptor().cache);
#    3191                 :         13 :         }
#    3192                 :            : 
#    3193                 :            :         // Remove from maps of active spkMans
#    3194                 :         13 :         auto old_spk_man_id = old_spk_man->GetID();
#    3195         [ +  + ]:         26 :         for (bool internal : {false, true}) {
#    3196         [ +  + ]:         76 :             for (OutputType t : OUTPUT_TYPES) {
#    3197                 :         76 :                 auto active_spk_man = GetScriptPubKeyMan(t, internal);
#    3198 [ +  + ][ +  + ]:         76 :                 if (active_spk_man && active_spk_man->GetID() == old_spk_man_id) {
#                 [ +  - ]
#    3199         [ -  + ]:          1 :                     if (internal) {
#    3200                 :          0 :                         m_internal_spk_managers.erase(t);
#    3201                 :          1 :                     } else {
#    3202                 :          1 :                         m_external_spk_managers.erase(t);
#    3203                 :          1 :                     }
#    3204                 :          1 :                     break;
#    3205                 :          1 :                 }
#    3206                 :         76 :             }
#    3207                 :         26 :         }
#    3208                 :         13 :         m_spk_managers.erase(old_spk_man_id);
#    3209                 :         13 :     }
#    3210                 :            : 
#    3211                 :            :     // Add the private keys to the descriptor
#    3212         [ +  + ]:        190 :     for (const auto& entry : signing_provider.keys) {
#    3213                 :        127 :         const CKey& key = entry.second;
#    3214                 :        127 :         new_spk_man->AddDescriptorKey(key, key.GetPubKey());
#    3215                 :        127 :     }
#    3216                 :            : 
#    3217                 :            :     // Top up key pool, the manager will generate new scriptPubKeys internally
#    3218         [ -  + ]:        190 :     if (!new_spk_man->TopUp()) {
#    3219                 :          0 :         WalletLogPrintf("Could not top up scriptPubKeys\n");
#    3220                 :          0 :         return nullptr;
#    3221                 :          0 :     }
#    3222                 :            : 
#    3223                 :            :     // Apply the label if necessary
#    3224                 :            :     // Note: we disable labels for ranged descriptors
#    3225         [ +  + ]:        190 :     if (!desc.descriptor->IsRange()) {
#    3226                 :        143 :         auto script_pub_keys = new_spk_man->GetScriptPubKeys();
#    3227         [ -  + ]:        143 :         if (script_pub_keys.empty()) {
#    3228                 :          0 :             WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
#    3229                 :          0 :             return nullptr;
#    3230                 :          0 :         }
#    3231                 :            : 
#    3232                 :        143 :         CTxDestination dest;
#    3233 [ +  + ][ +  + ]:        143 :         if (!internal && ExtractDestination(script_pub_keys.at(0), dest)) {
#    3234                 :        141 :             SetAddressBook(dest, label, "receive");
#    3235                 :        141 :         }
#    3236                 :        143 :     }
#    3237                 :            : 
#    3238                 :            :     // Save the descriptor to memory
#    3239                 :        190 :     auto ret = new_spk_man.get();
#    3240                 :        190 :     m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
#    3241                 :            : 
#    3242                 :            :     // Save the descriptor to DB
#    3243                 :        190 :     ret->WriteDescriptor();
#    3244                 :            : 
#    3245                 :        190 :     return ret;
#    3246                 :        190 : }

Generated by: LCOV version 1.14