LCOV - code coverage report
Current view: top level - src/wallet - wallet.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 2350 2753 85.4 %
Date: 2020-09-26 01:30:44 Functions: 197 209 94.3 %

          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 <optional.h>
      17             : #include <policy/fees.h>
      18             : #include <policy/policy.h>
      19             : #include <primitives/block.h>
      20             : #include <primitives/transaction.h>
      21             : #include <script/descriptor.h>
      22             : #include <script/script.h>
      23             : #include <script/signingprovider.h>
      24             : #include <txmempool.h>
      25             : #include <util/bip32.h>
      26             : #include <util/check.h>
      27             : #include <util/error.h>
      28             : #include <util/fees.h>
      29             : #include <util/moneystr.h>
      30             : #include <util/rbf.h>
      31             : #include <util/string.h>
      32             : #include <util/translation.h>
      33             : #include <wallet/coincontrol.h>
      34             : #include <wallet/fees.h>
      35             : 
      36             : #include <univalue.h>
      37             : 
      38             : #include <algorithm>
      39             : #include <assert.h>
      40             : 
      41             : #include <boost/algorithm/string/replace.hpp>
      42             : 
      43             : using interfaces::FoundBlock;
      44             : 
      45         650 : const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS{
      46         650 :     {WALLET_FLAG_AVOID_REUSE,
      47             :         "You need to rescan the blockchain in order to correctly mark used "
      48             :         "destinations in the past. Until this is done, some destinations may "
      49             :         "be considered unused, even if the opposite is the case."
      50             :     },
      51             : };
      52             : 
      53             : static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
      54             : 
      55         650 : static RecursiveMutex cs_wallets;
      56         650 : static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
      57         650 : static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
      58             : 
      59           4 : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
      60             : {
      61           4 :     util::SettingsValue setting_value = chain.getRwSetting("wallet");
      62           4 :     if (!setting_value.isArray()) setting_value.setArray();
      63          10 :     for (const util::SettingsValue& value : setting_value.getValues()) {
      64           6 :         if (value.isStr() && value.get_str() == wallet_name) return true;
      65           6 :     }
      66           4 :     setting_value.push_back(wallet_name);
      67           4 :     return chain.updateRwSetting("wallet", setting_value);
      68           4 : }
      69             : 
      70           7 : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
      71             : {
      72           7 :     util::SettingsValue setting_value = chain.getRwSetting("wallet");
      73           7 :     if (!setting_value.isArray()) return true;
      74           7 :     util::SettingsValue new_value(util::SettingsValue::VARR);
      75          25 :     for (const util::SettingsValue& value : setting_value.getValues()) {
      76          18 :         if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
      77             :     }
      78           7 :     if (new_value.size() == setting_value.size()) return true;
      79           3 :     return chain.updateRwSetting("wallet", new_value);
      80           7 : }
      81             : 
      82        1199 : static void UpdateWalletSetting(interfaces::Chain& chain,
      83             :                                 const std::string& wallet_name,
      84             :                                 Optional<bool> load_on_startup,
      85             :                                 std::vector<bilingual_str>& warnings)
      86             : {
      87        1199 :     if (load_on_startup == nullopt) return;
      88          11 :     if (load_on_startup.get() && !AddWalletSetting(chain, wallet_name)) {
      89           0 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
      90          11 :     } else if (!load_on_startup.get() && !RemoveWalletSetting(chain, wallet_name)) {
      91           0 :         warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
      92           0 :     }
      93        1199 : }
      94             : 
      95         726 : bool AddWallet(const std::shared_ptr<CWallet>& wallet)
      96             : {
      97         726 :     LOCK(cs_wallets);
      98         726 :     assert(wallet);
      99         726 :     std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
     100         726 :     if (i != vpwallets.end()) return false;
     101         726 :     vpwallets.push_back(wallet);
     102         726 :     wallet->ConnectScriptPubKeyManNotifiers();
     103         726 :     return true;
     104         726 : }
     105             : 
     106         726 : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, Optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
     107             : {
     108         726 :     assert(wallet);
     109             : 
     110         726 :     interfaces::Chain& chain = wallet->chain();
     111         726 :     std::string name = wallet->GetName();
     112             : 
     113             :     // Unregister with the validation interface which also drops shared ponters.
     114         726 :     wallet->m_chain_notifications_handler.reset();
     115         726 :     LOCK(cs_wallets);
     116         726 :     std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
     117         726 :     if (i == vpwallets.end()) return false;
     118         726 :     vpwallets.erase(i);
     119             : 
     120             :     // Write the wallet setting
     121         726 :     UpdateWalletSetting(chain, name, load_on_start, warnings);
     122             : 
     123         726 :     return true;
     124         726 : }
     125             : 
     126           3 : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, Optional<bool> load_on_start)
     127             : {
     128           3 :     std::vector<bilingual_str> warnings;
     129           3 :     return RemoveWallet(wallet, load_on_start, warnings);
     130           3 : }
     131             : 
     132       56273 : std::vector<std::shared_ptr<CWallet>> GetWallets()
     133             : {
     134       56273 :     LOCK(cs_wallets);
     135       56273 :     return vpwallets;
     136       56273 : }
     137             : 
     138        1818 : std::shared_ptr<CWallet> GetWallet(const std::string& name)
     139             : {
     140        1818 :     LOCK(cs_wallets);
     141        5948 :     for (const std::shared_ptr<CWallet>& wallet : vpwallets) {
     142        4130 :         if (wallet->GetName() == name) return wallet;
     143        2326 :     }
     144          14 :     return nullptr;
     145        1818 : }
     146             : 
     147           1 : std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet)
     148             : {
     149           1 :     LOCK(cs_wallets);
     150           1 :     auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(), std::move(load_wallet));
     151           2 :     return interfaces::MakeHandler([it] { LOCK(cs_wallets); g_load_wallet_fns.erase(it); });
     152           1 : }
     153             : 
     154         650 : static Mutex g_loading_wallet_mutex;
     155         650 : static Mutex g_wallet_release_mutex;
     156         650 : static std::condition_variable g_wallet_release_cv;
     157         650 : static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
     158         650 : static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
     159             : 
     160             : // Custom deleter for shared_ptr<CWallet>.
     161         733 : static void ReleaseWallet(CWallet* wallet)
     162             : {
     163         733 :     const std::string name = wallet->GetName();
     164         733 :     wallet->WalletLogPrintf("Releasing wallet\n");
     165         733 :     wallet->Flush();
     166         733 :     delete wallet;
     167             :     // Wallet is now released, notify UnloadWallet, if any.
     168             :     {
     169         733 :         LOCK(g_wallet_release_mutex);
     170         733 :         if (g_unloading_wallet_set.erase(name) == 0) {
     171             :             // UnloadWallet was not called for this wallet, all done.
     172           6 :             return;
     173             :         }
     174         733 :     }
     175         727 :     g_wallet_release_cv.notify_all();
     176         733 : }
     177             : 
     178         727 : void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
     179             : {
     180             :     // Mark wallet for unloading.
     181         727 :     const std::string name = wallet->GetName();
     182             :     {
     183         727 :         LOCK(g_wallet_release_mutex);
     184         727 :         auto it = g_unloading_wallet_set.insert(name);
     185         727 :         assert(it.second);
     186         727 :     }
     187             :     // The wallet can be in use so it's not possible to explicitly unload here.
     188             :     // Notify the unload intent so that all remaining shared pointers are
     189             :     // released.
     190         727 :     wallet->NotifyUnload();
     191             : 
     192             :     // Time to ditch our shared_ptr and wait for ReleaseWallet call.
     193         727 :     wallet.reset();
     194             :     {
     195         727 :         WAIT_LOCK(g_wallet_release_mutex, lock);
     196         739 :         while (g_unloading_wallet_set.count(name) == 1) {
     197          12 :             g_wallet_release_cv.wait(lock);
     198             :         }
     199         727 :     }
     200         727 : }
     201             : 
     202             : namespace {
     203         131 : std::shared_ptr<CWallet> LoadWalletInternal(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     204             : {
     205             :     try {
     206         131 :         std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
     207         131 :         if (!database) {
     208          14 :             error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
     209          14 :             return nullptr;
     210             :         }
     211             : 
     212         117 :         std::shared_ptr<CWallet> wallet = CWallet::Create(chain, name, std::move(database), options.create_flags, error, warnings);
     213         113 :         if (!wallet) {
     214           0 :             error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
     215           0 :             status = DatabaseStatus::FAILED_LOAD;
     216           0 :             return nullptr;
     217             :         }
     218         113 :         AddWallet(wallet);
     219         113 :         wallet->postInitProcess();
     220             : 
     221             :         // Write the wallet setting
     222         113 :         UpdateWalletSetting(chain, name, load_on_start, warnings);
     223             : 
     224         113 :         return wallet;
     225         131 :     } catch (const std::runtime_error& e) {
     226           4 :         error = Untranslated(e.what());
     227           4 :         status = DatabaseStatus::FAILED_LOAD;
     228           4 :         return nullptr;
     229           4 :     }
     230         139 : }
     231             : } // namespace
     232             : 
     233         135 : std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     234             : {
     235         270 :     auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
     236         135 :     if (!result.second) {
     237           4 :         error = Untranslated("Wallet already being loading.");
     238           4 :         status = DatabaseStatus::FAILED_LOAD;
     239           4 :         return nullptr;
     240             :     }
     241         131 :     auto wallet = LoadWalletInternal(chain, name, load_on_start, options, status, error, warnings);
     242         262 :     WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
     243         131 :     return wallet;
     244         135 : }
     245             : 
     246         364 : std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
     247             : {
     248         364 :     uint64_t wallet_creation_flags = options.create_flags;
     249         364 :     const SecureString& passphrase = options.create_passphrase;
     250             : 
     251         364 :     if (wallet_creation_flags & WALLET_FLAG_DESCRIPTORS) options.require_format = DatabaseFormat::SQLITE;
     252             : 
     253             :     // Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
     254         364 :     bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
     255             : 
     256             :     // Born encrypted wallets need to be created blank first.
     257         364 :     if (!passphrase.empty()) {
     258           7 :         wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
     259           7 :     }
     260             : 
     261             :     // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
     262         364 :     std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
     263         364 :     if (!database) {
     264           2 :         error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
     265           2 :         status = DatabaseStatus::FAILED_VERIFY;
     266           2 :         return nullptr;
     267             :     }
     268             : 
     269             :     // Do not allow a passphrase when private keys are disabled
     270         362 :     if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     271           2 :         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.");
     272           2 :         status = DatabaseStatus::FAILED_CREATE;
     273           2 :         return nullptr;
     274             :     }
     275             : 
     276             :     // Make the wallet
     277         360 :     std::shared_ptr<CWallet> wallet = CWallet::Create(chain, name, std::move(database), wallet_creation_flags, error, warnings);
     278         360 :     if (!wallet) {
     279           0 :         error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
     280           0 :         status = DatabaseStatus::FAILED_CREATE;
     281           0 :         return nullptr;
     282             :     }
     283             : 
     284             :     // Encrypt the wallet
     285         360 :     if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     286           5 :         if (!wallet->EncryptWallet(passphrase)) {
     287           0 :             error = Untranslated("Error: Wallet created but failed to encrypt.");
     288           0 :             status = DatabaseStatus::FAILED_ENCRYPT;
     289           0 :             return nullptr;
     290             :         }
     291           5 :         if (!create_blank) {
     292             :             // Unlock the wallet
     293           3 :             if (!wallet->Unlock(passphrase)) {
     294           0 :                 error = Untranslated("Error: Wallet was encrypted but could not be unlocked");
     295           0 :                 status = DatabaseStatus::FAILED_ENCRYPT;
     296           0 :                 return nullptr;
     297             :             }
     298             : 
     299             :             // Set a seed for the wallet
     300             :             {
     301           3 :                 LOCK(wallet->cs_wallet);
     302           3 :                 if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
     303           1 :                     wallet->SetupDescriptorScriptPubKeyMans();
     304             :                 } else {
     305           4 :                     for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
     306           2 :                         if (!spk_man->SetupGeneration()) {
     307           0 :                             error = Untranslated("Unable to generate initial keys");
     308           0 :                             status = DatabaseStatus::FAILED_CREATE;
     309           0 :                             return nullptr;
     310             :                         }
     311           2 :                     }
     312             :                 }
     313           3 :             }
     314             : 
     315             :             // Relock the wallet
     316           3 :             wallet->Lock();
     317             :         }
     318             :     }
     319         360 :     AddWallet(wallet);
     320         360 :     wallet->postInitProcess();
     321             : 
     322             :     // Write the wallet settings
     323         360 :     UpdateWalletSetting(chain, name, load_on_start, warnings);
     324             : 
     325         360 :     status = DatabaseStatus::SUCCESS;
     326         360 :     return wallet;
     327         364 : }
     328             : 
     329         650 : const uint256 CWalletTx::ABANDON_HASH(UINT256_ONE());
     330             : 
     331             : /** @defgroup mapWallet
     332             :  *
     333             :  * @{
     334             :  */
     335             : 
     336           0 : std::string COutput::ToString() const
     337             : {
     338           0 :     return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
     339           0 : }
     340             : 
     341       19109 : const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
     342             : {
     343       19109 :     AssertLockHeld(cs_wallet);
     344       19109 :     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
     345       19109 :     if (it == mapWallet.end())
     346         159 :         return nullptr;
     347       18950 :     return &(it->second);
     348       19109 : }
     349             : 
     350         807 : void CWallet::UpgradeKeyMetadata()
     351             : {
     352         807 :     if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
     353             :         return;
     354             :     }
     355             : 
     356         621 :     auto spk_man = GetLegacyScriptPubKeyMan();
     357         621 :     if (!spk_man) {
     358         485 :         return;
     359             :     }
     360             : 
     361         136 :     spk_man->UpgradeKeyMetadata();
     362         136 :     SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
     363         943 : }
     364             : 
     365          66 : bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
     366             : {
     367          66 :     CCrypter crypter;
     368          66 :     CKeyingMaterial _vMasterKey;
     369             : 
     370             :     {
     371          66 :         LOCK(cs_wallet);
     372         132 :         for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
     373             :         {
     374          66 :             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
     375           0 :                 return false;
     376          66 :             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
     377           4 :                 continue; // try another master key
     378          62 :             if (Unlock(_vMasterKey, accept_no_keys)) {
     379             :                 // Now that we've unlocked, upgrade the key metadata
     380          62 :                 UpgradeKeyMetadata();
     381          62 :                 return true;
     382             :             }
     383           0 :         }
     384          66 :     }
     385           4 :     return false;
     386          66 : }
     387             : 
     388           2 : bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
     389             : {
     390           2 :     bool fWasLocked = IsLocked();
     391             : 
     392             :     {
     393           2 :         LOCK(cs_wallet);
     394           2 :         Lock();
     395             : 
     396           2 :         CCrypter crypter;
     397           2 :         CKeyingMaterial _vMasterKey;
     398           4 :         for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
     399             :         {
     400           2 :             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
     401           0 :                 return false;
     402           2 :             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
     403           0 :                 return false;
     404           2 :             if (Unlock(_vMasterKey))
     405             :             {
     406           2 :                 int64_t nStartTime = GetTimeMillis();
     407           2 :                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
     408           2 :                 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
     409             : 
     410           2 :                 nStartTime = GetTimeMillis();
     411           2 :                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
     412           2 :                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
     413             : 
     414           2 :                 if (pMasterKey.second.nDeriveIterations < 25000)
     415           0 :                     pMasterKey.second.nDeriveIterations = 25000;
     416             : 
     417           2 :                 WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
     418             : 
     419           2 :                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
     420           0 :                     return false;
     421           2 :                 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
     422           0 :                     return false;
     423           2 :                 WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
     424           2 :                 if (fWasLocked)
     425           2 :                     Lock();
     426           2 :                 return true;
     427           0 :             }
     428           0 :         }
     429           2 :     }
     430             : 
     431           0 :     return false;
     432           2 : }
     433             : 
     434        1114 : void CWallet::chainStateFlushed(const CBlockLocator& loc)
     435             : {
     436        1114 :     WalletBatch batch(*database);
     437        1114 :     batch.WriteBestBlock(loc);
     438        1114 : }
     439             : 
     440       19364 : void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
     441             : {
     442       19364 :     LOCK(cs_wallet);
     443       19364 :     if (nWalletVersion >= nVersion)
     444       18939 :         return;
     445             : 
     446             :     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
     447         425 :     if (fExplicit && nVersion > nWalletMaxVersion)
     448           0 :             nVersion = FEATURE_LATEST;
     449             : 
     450         425 :     nWalletVersion = nVersion;
     451             : 
     452         425 :     if (nVersion > nWalletMaxVersion)
     453         423 :         nWalletMaxVersion = nVersion;
     454             : 
     455             :     {
     456         425 :         WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
     457         425 :         if (nWalletVersion > 40000)
     458         425 :             batch->WriteMinVersion(nWalletVersion);
     459         425 :         if (!batch_in)
     460         425 :             delete batch;
     461             :     }
     462       19364 : }
     463             : 
     464           2 : bool CWallet::SetMaxVersion(int nVersion)
     465             : {
     466           2 :     LOCK(cs_wallet);
     467             :     // cannot downgrade below current version
     468           2 :     if (nWalletVersion > nVersion)
     469           0 :         return false;
     470             : 
     471           2 :     nWalletMaxVersion = nVersion;
     472             : 
     473           2 :     return true;
     474           2 : }
     475             : 
     476        2028 : std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
     477             : {
     478        2028 :     std::set<uint256> result;
     479        2028 :     AssertLockHeld(cs_wallet);
     480             : 
     481        2028 :     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
     482        2028 :     if (it == mapWallet.end())
     483           0 :         return result;
     484        2028 :     const CWalletTx& wtx = it->second;
     485             : 
     486        2028 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
     487             : 
     488        4648 :     for (const CTxIn& txin : wtx.tx->vin)
     489             :     {
     490        2620 :         if (mapTxSpends.count(txin.prevout) <= 1)
     491        2583 :             continue;  // No conflict if zero or one spends
     492          37 :         range = mapTxSpends.equal_range(txin.prevout);
     493         178 :         for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
     494         141 :             result.insert(_it->second);
     495          37 :     }
     496             :     return result;
     497        2028 : }
     498             : 
     499         185 : bool CWallet::HasWalletSpend(const uint256& txid) const
     500             : {
     501         185 :     AssertLockHeld(cs_wallet);
     502         185 :     auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
     503         185 :     return (iter != mapTxSpends.end() && iter->first.hash == txid);
     504         185 : }
     505             : 
     506        1337 : void CWallet::Flush()
     507             : {
     508        1337 :     database->Flush();
     509        1337 : }
     510             : 
     511         610 : void CWallet::Close()
     512             : {
     513         610 :     database->Close();
     514         610 : }
     515             : 
     516       12877 : void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
     517             : {
     518             :     // We want all the wallet transactions in range to have the same metadata as
     519             :     // the oldest (smallest nOrderPos).
     520             :     // So: find smallest nOrderPos:
     521             : 
     522       12877 :     int nMinOrderPos = std::numeric_limits<int>::max();
     523             :     const CWalletTx* copyFrom = nullptr;
     524       28326 :     for (TxSpends::iterator it = range.first; it != range.second; ++it) {
     525       15449 :         const CWalletTx* wtx = &mapWallet.at(it->second);
     526       15449 :         if (wtx->nOrderPos < nMinOrderPos) {
     527       12905 :             nMinOrderPos = wtx->nOrderPos;
     528             :             copyFrom = wtx;
     529       12905 :         }
     530             :     }
     531             : 
     532       12877 :     if (!copyFrom) {
     533           0 :         return;
     534             :     }
     535             : 
     536             :     // Now copy data from copyFrom to rest:
     537       28326 :     for (TxSpends::iterator it = range.first; it != range.second; ++it)
     538             :     {
     539       15449 :         const uint256& hash = it->second;
     540       15449 :         CWalletTx* copyTo = &mapWallet.at(hash);
     541       15449 :         if (copyFrom == copyTo) continue;
     542        2572 :         assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
     543        2572 :         if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
     544           3 :         copyTo->mapValue = copyFrom->mapValue;
     545           3 :         copyTo->vOrderForm = copyFrom->vOrderForm;
     546             :         // fTimeReceivedIsTxTime not copied on purpose
     547             :         // nTimeReceived not copied on purpose
     548           3 :         copyTo->nTimeSmart = copyFrom->nTimeSmart;
     549           3 :         copyTo->fFromMe = copyFrom->fFromMe;
     550             :         // nOrderPos not copied on purpose
     551             :         // cached members not copied on purpose
     552           3 :     }
     553       12877 : }
     554             : 
     555             : /**
     556             :  * Outpoint is spent if any non-conflicted transaction
     557             :  * spends it:
     558             :  */
     559      842595 : bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
     560             : {
     561      842595 :     const COutPoint outpoint(hash, n);
     562      842595 :     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
     563      842595 :     range = mapTxSpends.equal_range(outpoint);
     564             : 
     565     1209948 :     for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
     566             :     {
     567      367353 :         const uint256& wtxid = it->second;
     568      367353 :         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
     569      367353 :         if (mit != mapWallet.end()) {
     570      367353 :             int depth = mit->second.GetDepthInMainChain();
     571      367353 :             if (depth > 0  || (depth == 0 && !mit->second.isAbandoned()))
     572      733013 :                 return true; // Spent
     573        1693 :         }
     574      367353 :     }
     575      476935 :     return false;
     576      842595 : }
     577             : 
     578       12877 : void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
     579             : {
     580       12877 :     mapTxSpends.insert(std::make_pair(outpoint, wtxid));
     581             : 
     582       12877 :     setLockedCoins.erase(outpoint);
     583             : 
     584       12877 :     std::pair<TxSpends::iterator, TxSpends::iterator> range;
     585       12877 :     range = mapTxSpends.equal_range(outpoint);
     586       12877 :     SyncMetaData(range);
     587       12877 : }
     588             : 
     589             : 
     590      145790 : void CWallet::AddToSpends(const uint256& wtxid)
     591             : {
     592      145790 :     auto it = mapWallet.find(wtxid);
     593      145790 :     assert(it != mapWallet.end());
     594      145790 :     CWalletTx& thisTx = it->second;
     595      145790 :     if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
     596       31423 :         return;
     597             : 
     598      127244 :     for (const CTxIn& txin : thisTx.tx->vin)
     599       12877 :         AddToSpends(txin.prevout, wtxid);
     600      145790 : }
     601             : 
     602          20 : bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
     603             : {
     604          20 :     if (IsCrypted())
     605           0 :         return false;
     606             : 
     607          20 :     CKeyingMaterial _vMasterKey;
     608             : 
     609          20 :     _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
     610          20 :     GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
     611             : 
     612          20 :     CMasterKey kMasterKey;
     613             : 
     614          20 :     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
     615          20 :     GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
     616             : 
     617          20 :     CCrypter crypter;
     618          20 :     int64_t nStartTime = GetTimeMillis();
     619          20 :     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
     620          20 :     kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
     621             : 
     622          20 :     nStartTime = GetTimeMillis();
     623          20 :     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
     624          20 :     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
     625             : 
     626          20 :     if (kMasterKey.nDeriveIterations < 25000)
     627           8 :         kMasterKey.nDeriveIterations = 25000;
     628             : 
     629          20 :     WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
     630             : 
     631          20 :     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
     632           0 :         return false;
     633          20 :     if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
     634           0 :         return false;
     635             : 
     636             :     {
     637          20 :         LOCK(cs_wallet);
     638          20 :         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
     639          20 :         WalletBatch* encrypted_batch = new WalletBatch(*database);
     640          20 :         if (!encrypted_batch->TxnBegin()) {
     641           0 :             delete encrypted_batch;
     642             :             encrypted_batch = nullptr;
     643           0 :             return false;
     644             :         }
     645          20 :         encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
     646             : 
     647          56 :         for (const auto& spk_man_pair : m_spk_managers) {
     648          36 :             auto spk_man = spk_man_pair.second.get();
     649          36 :             if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
     650           0 :                 encrypted_batch->TxnAbort();
     651           0 :                 delete encrypted_batch;
     652             :                 encrypted_batch = nullptr;
     653             :                 // We now probably have half of our keys encrypted in memory, and half not...
     654             :                 // die and let the user reload the unencrypted wallet.
     655           0 :                 assert(false);
     656             :             }
     657           0 :         }
     658             : 
     659             :         // Encryption was introduced in version 0.4.0
     660          20 :         SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
     661             : 
     662          20 :         if (!encrypted_batch->TxnCommit()) {
     663           0 :             delete encrypted_batch;
     664             :             encrypted_batch = nullptr;
     665             :             // We now have keys encrypted in memory, but not on disk...
     666             :             // die to avoid confusion and let the user reload the unencrypted wallet.
     667           0 :             assert(false);
     668             :         }
     669             : 
     670          20 :         delete encrypted_batch;
     671             :         encrypted_batch = nullptr;
     672             : 
     673          20 :         Lock();
     674          20 :         Unlock(strWalletPassphrase);
     675             : 
     676             :         // If we are using descriptors, make new descriptors with a new seed
     677          20 :         if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)) {
     678           3 :             SetupDescriptorScriptPubKeyMans();
     679          33 :         } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
     680             :             // if we are using HD, replace the HD seed with a new one
     681          16 :             if (spk_man->IsHDEnabled()) {
     682          10 :                 if (!spk_man->SetupGeneration(true)) {
     683           0 :                     return false;
     684             :                 }
     685             :             }
     686             :         }
     687          20 :         Lock();
     688             : 
     689             :         // Need to completely rewrite the wallet file; if we don't, bdb might keep
     690             :         // bits of the unencrypted private key in slack space in the database file.
     691          20 :         database->Rewrite();
     692             : 
     693             :         // BDB seems to have a bad habit of writing old data into
     694             :         // slack space in .dat files; that is bad if the old data is
     695             :         // unencrypted private keys. So:
     696          20 :         database->ReloadDbEnv();
     697             : 
     698          20 :     }
     699          20 :     NotifyStatusChanged(this);
     700             : 
     701          20 :     return true;
     702          20 : }
     703             : 
     704           0 : DBErrors CWallet::ReorderTransactions()
     705             : {
     706           0 :     LOCK(cs_wallet);
     707           0 :     WalletBatch batch(*database);
     708             : 
     709             :     // Old wallets didn't have any defined order for transactions
     710             :     // Probably a bad idea to change the output of this
     711             : 
     712             :     // First: get all CWalletTx into a sorted-by-time multimap.
     713             :     typedef std::multimap<int64_t, CWalletTx*> TxItems;
     714           0 :     TxItems txByTime;
     715             : 
     716           0 :     for (auto& entry : mapWallet)
     717             :     {
     718           0 :         CWalletTx* wtx = &entry.second;
     719           0 :         txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
     720           0 :     }
     721             : 
     722           0 :     nOrderPosNext = 0;
     723           0 :     std::vector<int64_t> nOrderPosOffsets;
     724           0 :     for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
     725             :     {
     726           0 :         CWalletTx *const pwtx = (*it).second;
     727           0 :         int64_t& nOrderPos = pwtx->nOrderPos;
     728             : 
     729           0 :         if (nOrderPos == -1)
     730             :         {
     731           0 :             nOrderPos = nOrderPosNext++;
     732           0 :             nOrderPosOffsets.push_back(nOrderPos);
     733             : 
     734           0 :             if (!batch.WriteTx(*pwtx))
     735           0 :                 return DBErrors::LOAD_FAIL;
     736             :         }
     737             :         else
     738             :         {
     739             :             int64_t nOrderPosOff = 0;
     740           0 :             for (const int64_t& nOffsetStart : nOrderPosOffsets)
     741             :             {
     742           0 :                 if (nOrderPos >= nOffsetStart)
     743           0 :                     ++nOrderPosOff;
     744             :             }
     745           0 :             nOrderPos += nOrderPosOff;
     746           0 :             nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
     747             : 
     748           0 :             if (!nOrderPosOff)
     749           0 :                 continue;
     750             : 
     751             :             // Since we're changing the order, write it back
     752           0 :             if (!batch.WriteTx(*pwtx))
     753           0 :                 return DBErrors::LOAD_FAIL;
     754           0 :         }
     755           0 :     }
     756           0 :     batch.WriteOrderPosNext(nOrderPosNext);
     757             : 
     758           0 :     return DBErrors::LOAD_OK;
     759           0 : }
     760             : 
     761      136216 : int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
     762             : {
     763      136216 :     AssertLockHeld(cs_wallet);
     764      136216 :     int64_t nRet = nOrderPosNext++;
     765      136216 :     if (batch) {
     766      136216 :         batch->WriteOrderPosNext(nOrderPosNext);
     767      136216 :     } else {
     768           0 :         WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
     769             :     }
     770      136216 :     return nRet;
     771           0 : }
     772             : 
     773         570 : void CWallet::MarkDirty()
     774             : {
     775             :     {
     776         570 :         LOCK(cs_wallet);
     777       25594 :         for (std::pair<const uint256, CWalletTx>& item : mapWallet)
     778       25024 :             item.second.MarkDirty();
     779         570 :     }
     780         570 : }
     781             : 
     782          85 : bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
     783             : {
     784          85 :     LOCK(cs_wallet);
     785             : 
     786          85 :     auto mi = mapWallet.find(originalHash);
     787             : 
     788             :     // There is a bug if MarkReplaced is not called on an existing wallet transaction.
     789          85 :     assert(mi != mapWallet.end());
     790             : 
     791          85 :     CWalletTx& wtx = (*mi).second;
     792             : 
     793             :     // Ensure for now that we're not overwriting data
     794          85 :     assert(wtx.mapValue.count("replaced_by_txid") == 0);
     795             : 
     796          85 :     wtx.mapValue["replaced_by_txid"] = newHash.ToString();
     797             : 
     798          85 :     WalletBatch batch(*database, "r+");
     799             : 
     800             :     bool success = true;
     801          85 :     if (!batch.WriteTx(wtx)) {
     802           0 :         WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
     803             :         success = false;
     804           0 :     }
     805             : 
     806          85 :     NotifyTransactionChanged(this, originalHash, CT_UPDATED);
     807             : 
     808          85 :     return success;
     809          85 : }
     810             : 
     811         813 : void CWallet::SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
     812             : {
     813         813 :     AssertLockHeld(cs_wallet);
     814         813 :     const CWalletTx* srctx = GetWalletTx(hash);
     815         813 :     if (!srctx) return;
     816             : 
     817         754 :     CTxDestination dst;
     818         754 :     if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
     819         754 :         if (IsMine(dst)) {
     820         634 :             if (used && !GetDestData(dst, "used", nullptr)) {
     821          43 :                 if (AddDestData(batch, dst, "used", "p")) { // p for "present", opposite of absent (null)
     822          43 :                     tx_destinations.insert(dst);
     823          43 :                 }
     824         591 :             } else if (!used && GetDestData(dst, "used", nullptr)) {
     825           0 :                 EraseDestData(batch, dst, "used");
     826           0 :             }
     827             :         }
     828             :     }
     829         813 : }
     830             : 
     831        1016 : bool CWallet::IsSpentKey(const uint256& hash, unsigned int n) const
     832             : {
     833        1016 :     AssertLockHeld(cs_wallet);
     834        1016 :     const CWalletTx* srctx = GetWalletTx(hash);
     835        1016 :     if (srctx) {
     836        1016 :         assert(srctx->tx->vout.size() > n);
     837        1016 :         CTxDestination dest;
     838        1016 :         if (!ExtractDestination(srctx->tx->vout[n].scriptPubKey, dest)) {
     839         400 :             return false;
     840             :         }
     841         616 :         if (GetDestData(dest, "used", nullptr)) {
     842          18 :             return true;
     843             :         }
     844         598 :         if (IsLegacy()) {
     845         333 :             LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
     846         333 :             assert(spk_man != nullptr);
     847         552 :             for (const auto& keyid : GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
     848         219 :                 WitnessV0KeyHash wpkh_dest(keyid);
     849         219 :                 if (GetDestData(wpkh_dest, "used", nullptr)) {
     850           0 :                     return true;
     851             :                 }
     852         219 :                 ScriptHash sh_wpkh_dest(GetScriptForDestination(wpkh_dest));
     853         219 :                 if (GetDestData(sh_wpkh_dest, "used", nullptr)) {
     854           0 :                     return true;
     855             :                 }
     856         219 :                 PKHash pkh_dest(keyid);
     857         219 :                 if (GetDestData(pkh_dest, "used", nullptr)) {
     858          12 :                     return true;
     859             :                 }
     860         219 :             }
     861         321 :         }
     862        1016 :     }
     863         586 :     return false;
     864        1016 : }
     865             : 
     866      161132 : CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose)
     867             : {
     868      161132 :     LOCK(cs_wallet);
     869             : 
     870      161132 :     WalletBatch batch(*database, "r+", fFlushOnClose);
     871             : 
     872      161132 :     uint256 hash = tx->GetHash();
     873             : 
     874      161132 :     if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
     875             :         // Mark used destinations
     876         291 :         std::set<CTxDestination> tx_destinations;
     877             : 
     878        1104 :         for (const CTxIn& txin : tx->vin) {
     879         813 :             const COutPoint& op = txin.prevout;
     880         813 :             SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
     881             :         }
     882             : 
     883         291 :         MarkDestinationsDirty(tx_destinations);
     884         291 :     }
     885             : 
     886             :     // Inserts only if not already there, returns tx inserted or tx found
     887      161132 :     auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, tx));
     888      161132 :     CWalletTx& wtx = (*ret.first).second;
     889      161132 :     bool fInsertedNew = ret.second;
     890      161132 :     bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
     891      161132 :     if (fInsertedNew) {
     892      136216 :         wtx.m_confirm = confirm;
     893      136216 :         wtx.nTimeReceived = chain().getAdjustedTime();
     894      136216 :         wtx.nOrderPos = IncOrderPosNext(&batch);
     895      136216 :         wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
     896      136216 :         wtx.nTimeSmart = ComputeTimeSmart(wtx);
     897      136216 :         AddToSpends(hash);
     898             :     }
     899             : 
     900      161132 :     if (!fInsertedNew)
     901             :     {
     902       24916 :         if (confirm.status != wtx.m_confirm.status) {
     903        3779 :             wtx.m_confirm.status = confirm.status;
     904        3779 :             wtx.m_confirm.nIndex = confirm.nIndex;
     905        3779 :             wtx.m_confirm.hashBlock = confirm.hashBlock;
     906        3779 :             wtx.m_confirm.block_height = confirm.block_height;
     907             :             fUpdated = true;
     908        3779 :         } else {
     909       21137 :             assert(wtx.m_confirm.nIndex == confirm.nIndex);
     910       21137 :             assert(wtx.m_confirm.hashBlock == confirm.hashBlock);
     911       21137 :             assert(wtx.m_confirm.block_height == confirm.block_height);
     912             :         }
     913             :         // If we have a witness-stripped version of this transaction, and we
     914             :         // see a new version with a witness, then we must be upgrading a pre-segwit
     915             :         // wallet.  Store the new version of the transaction with the witness,
     916             :         // as the stripped-version must be invalid.
     917             :         // TODO: Store all versions of the transaction, instead of just one.
     918       24916 :         if (tx->HasWitness() && !wtx.tx->HasWitness()) {
     919           0 :             wtx.SetTx(tx);
     920             :             fUpdated = true;
     921           0 :         }
     922             :     }
     923             : 
     924             :     //// debug print
     925      161132 :     WalletLogPrintf("AddToWallet %s  %s%s\n", hash.ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
     926             : 
     927             :     // Write to disk
     928      161132 :     if (fInsertedNew || fUpdated)
     929      139995 :         if (!batch.WriteTx(wtx))
     930           0 :             return nullptr;
     931             : 
     932             :     // Break debit/credit balance caches:
     933      161132 :     wtx.MarkDirty();
     934             : 
     935             :     // Notify UI of new or updated transaction
     936      161132 :     NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
     937             : 
     938             : #if HAVE_SYSTEM
     939             :     // notify an external script when a wallet transaction comes in or is updated
     940      161132 :     std::string strCmd = gArgs.GetArg("-walletnotify", "");
     941             : 
     942      161132 :     if (!strCmd.empty())
     943             :     {
     944          26 :         boost::replace_all(strCmd, "%s", hash.GetHex());
     945             : #ifndef WIN32
     946             :         // Substituting the wallet name isn't currently supported on windows
     947             :         // because windows shell escaping has not been implemented yet:
     948             :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
     949             :         // A few ways it could be implemented in the future are described in:
     950             :         // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
     951          26 :         boost::replace_all(strCmd, "%w", ShellEscape(GetName()));
     952             : #endif
     953          26 :         std::thread t(runCommand, strCmd);
     954          26 :         t.detach(); // thread runs free
     955          26 :     }
     956             : #endif
     957             : 
     958             :     return &wtx;
     959      161132 : }
     960             : 
     961        9574 : bool CWallet::LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx)
     962             : {
     963        9574 :     const auto& ins = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, nullptr));
     964        9574 :     CWalletTx& wtx = ins.first->second;
     965        9574 :     if (!fill_wtx(wtx, ins.second)) {
     966           0 :         return false;
     967             :     }
     968             :     // If wallet doesn't have a chain (e.g wallet-tool), don't bother to update txn.
     969        9574 :     if (HaveChain()) {
     970        9573 :         Optional<int> block_height = chain().getBlockHeight(wtx.m_confirm.hashBlock);
     971        9573 :         if (block_height) {
     972             :             // Update cached block height variable since it not stored in the
     973             :             // serialized transaction.
     974        8926 :             wtx.m_confirm.block_height = *block_height;
     975        9573 :         } else if (wtx.isConflicted() || wtx.isConfirmed()) {
     976             :             // If tx block (or conflicting block) was reorged out of chain
     977             :             // while the wallet was shutdown, change tx status to UNCONFIRMED
     978             :             // and reset block height, hash, and index. ABANDONED tx don't have
     979             :             // associated blocks and don't need to be updated. The case where a
     980             :             // transaction was reorged out while online and then reconfirmed
     981             :             // while offline is covered by the rescan logic.
     982         559 :             wtx.setUnconfirmed();
     983         559 :             wtx.m_confirm.hashBlock = uint256();
     984         559 :             wtx.m_confirm.block_height = 0;
     985         559 :             wtx.m_confirm.nIndex = 0;
     986         559 :         }
     987        9573 :     }
     988        9574 :     if (/* insertion took place */ ins.second) {
     989        9574 :         wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
     990        9574 :     }
     991        9574 :     AddToSpends(hash);
     992       19202 :     for (const CTxIn& txin : wtx.tx->vin) {
     993        9628 :         auto it = mapWallet.find(txin.prevout.hash);
     994        9628 :         if (it != mapWallet.end()) {
     995         545 :             CWalletTx& prevtx = it->second;
     996         545 :             if (prevtx.isConflicted()) {
     997           0 :                 MarkConflicted(prevtx.m_confirm.hashBlock, prevtx.m_confirm.block_height, wtx.GetHash());
     998           0 :             }
     999         545 :         }
    1000        9628 :     }
    1001        9574 :     return true;
    1002        9574 : }
    1003             : 
    1004      205040 : bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool fUpdate)
    1005             : {
    1006      205040 :     const CTransaction& tx = *ptx;
    1007             :     {
    1008      205040 :         AssertLockHeld(cs_wallet);
    1009             : 
    1010      205040 :         if (!confirm.hashBlock.IsNull()) {
    1011      385927 :             for (const CTxIn& txin : tx.vin) {
    1012      208730 :                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
    1013      219319 :                 while (range.first != range.second) {
    1014       10589 :                     if (range.first->second != tx.GetHash()) {
    1015         310 :                         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);
    1016         310 :                         MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
    1017         310 :                     }
    1018       10589 :                     range.first++;
    1019             :                 }
    1020      208730 :             }
    1021      177197 :         }
    1022             : 
    1023      205040 :         bool fExisted = mapWallet.count(tx.GetHash()) != 0;
    1024      205040 :         if (fExisted && !fUpdate) return false;
    1025      205040 :         if (fExisted || IsMine(tx) || IsFromMe(tx))
    1026             :         {
    1027             :             /* Check if any keys in the wallet keypool that were supposed to be unused
    1028             :              * have appeared in a new transaction. If so, remove those keys from the keypool.
    1029             :              * This can happen when restoring an old wallet backup that does not contain
    1030             :              * the mostly recently created transactions from newer versions of the wallet.
    1031             :              */
    1032             : 
    1033             :             // loop though all outputs
    1034      242325 :             for (const CTxOut& txout: tx.vout) {
    1035      420927 :                 for (const auto& spk_man_pair : m_spk_managers) {
    1036      228551 :                     spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
    1037             :                 }
    1038             :             }
    1039             : 
    1040             :             // Block disconnection override an abandoned tx as unconfirmed
    1041             :             // which means user may have to call abandontransaction again
    1042       49949 :             return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false);
    1043             :         }
    1044      155091 :     }
    1045      155091 :     return false;
    1046      205040 : }
    1047             : 
    1048           0 : bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
    1049             : {
    1050           0 :     LOCK(cs_wallet);
    1051           0 :     const CWalletTx* wtx = GetWalletTx(hashTx);
    1052           0 :     return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
    1053           0 : }
    1054             : 
    1055       50229 : void CWallet::MarkInputsDirty(const CTransactionRef& tx)
    1056             : {
    1057      120599 :     for (const CTxIn& txin : tx->vin) {
    1058       70370 :         auto it = mapWallet.find(txin.prevout.hash);
    1059       70370 :         if (it != mapWallet.end()) {
    1060       26748 :             it->second.MarkDirty();
    1061       26748 :         }
    1062       70370 :     }
    1063       50229 : }
    1064             : 
    1065           7 : bool CWallet::AbandonTransaction(const uint256& hashTx)
    1066             : {
    1067           7 :     LOCK(cs_wallet);
    1068             : 
    1069           7 :     WalletBatch batch(*database, "r+");
    1070             : 
    1071           7 :     std::set<uint256> todo;
    1072           7 :     std::set<uint256> done;
    1073             : 
    1074             :     // Can't mark abandoned if confirmed or in mempool
    1075           7 :     auto it = mapWallet.find(hashTx);
    1076           7 :     assert(it != mapWallet.end());
    1077           7 :     CWalletTx& origtx = it->second;
    1078           7 :     if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
    1079           2 :         return false;
    1080             :     }
    1081             : 
    1082           5 :     todo.insert(hashTx);
    1083             : 
    1084          12 :     while (!todo.empty()) {
    1085           7 :         uint256 now = *todo.begin();
    1086           7 :         todo.erase(now);
    1087           7 :         done.insert(now);
    1088           7 :         auto it = mapWallet.find(now);
    1089           7 :         assert(it != mapWallet.end());
    1090           7 :         CWalletTx& wtx = it->second;
    1091           7 :         int currentconfirm = wtx.GetDepthInMainChain();
    1092             :         // If the orig tx was not in block, none of its spends can be
    1093           7 :         assert(currentconfirm <= 0);
    1094             :         // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
    1095           7 :         if (currentconfirm == 0 && !wtx.isAbandoned()) {
    1096             :             // If the orig tx was not in block/mempool, none of its spends can be in mempool
    1097           7 :             assert(!wtx.InMempool());
    1098           7 :             wtx.setAbandoned();
    1099           7 :             wtx.MarkDirty();
    1100           7 :             batch.WriteTx(wtx);
    1101           7 :             NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
    1102             :             // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
    1103           7 :             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
    1104           9 :             while (iter != mapTxSpends.end() && iter->first.hash == now) {
    1105           2 :                 if (!done.count(iter->second)) {
    1106           2 :                     todo.insert(iter->second);
    1107           2 :                 }
    1108           2 :                 iter++;
    1109             :             }
    1110             :             // If a transaction changes 'conflicted' state, that changes the balance
    1111             :             // available of the outputs it spends. So force those to be recomputed
    1112           7 :             MarkInputsDirty(wtx.tx);
    1113           7 :         }
    1114           7 :     }
    1115             : 
    1116           5 :     return true;
    1117           7 : }
    1118             : 
    1119         310 : void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
    1120             : {
    1121         310 :     LOCK(cs_wallet);
    1122             : 
    1123         310 :     int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
    1124             :     // If number of conflict confirms cannot be determined, this means
    1125             :     // that the block is still unknown or not yet part of the main chain,
    1126             :     // for example when loading the wallet during a reindex. Do nothing in that
    1127             :     // case.
    1128         310 :     if (conflictconfirms >= 0)
    1129           0 :         return;
    1130             : 
    1131             :     // Do not flush the wallet here for performance reasons
    1132         310 :     WalletBatch batch(*database, "r+", false);
    1133             : 
    1134         310 :     std::set<uint256> todo;
    1135         310 :     std::set<uint256> done;
    1136             : 
    1137         310 :     todo.insert(hashTx);
    1138             : 
    1139         624 :     while (!todo.empty()) {
    1140         314 :         uint256 now = *todo.begin();
    1141         314 :         todo.erase(now);
    1142         314 :         done.insert(now);
    1143         314 :         auto it = mapWallet.find(now);
    1144         314 :         assert(it != mapWallet.end());
    1145         314 :         CWalletTx& wtx = it->second;
    1146         314 :         int currentconfirm = wtx.GetDepthInMainChain();
    1147         314 :         if (conflictconfirms < currentconfirm) {
    1148             :             // Block is 'more conflicted' than current confirm; update.
    1149             :             // Mark transaction as conflicted with this block.
    1150         273 :             wtx.m_confirm.nIndex = 0;
    1151         273 :             wtx.m_confirm.hashBlock = hashBlock;
    1152         273 :             wtx.m_confirm.block_height = conflicting_height;
    1153         273 :             wtx.setConflicted();
    1154         273 :             wtx.MarkDirty();
    1155         273 :             batch.WriteTx(wtx);
    1156             :             // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
    1157         273 :             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
    1158         277 :             while (iter != mapTxSpends.end() && iter->first.hash == now) {
    1159           4 :                  if (!done.count(iter->second)) {
    1160           4 :                      todo.insert(iter->second);
    1161           4 :                  }
    1162           4 :                  iter++;
    1163             :             }
    1164             :             // If a transaction changes 'conflicted' state, that changes the balance
    1165             :             // available of the outputs it spends. So force those to be recomputed
    1166         273 :             MarkInputsDirty(wtx.tx);
    1167         273 :         }
    1168         314 :     }
    1169         310 : }
    1170             : 
    1171      205040 : void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
    1172             : {
    1173      205040 :     if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
    1174             :         return; // Not one of ours
    1175             : 
    1176             :     // If a transaction changes 'conflicted' state, that changes the balance
    1177             :     // available of the outputs it spends. So force those to be
    1178             :     // recomputed, also:
    1179       49949 :     MarkInputsDirty(ptx);
    1180      205040 : }
    1181             : 
    1182       18877 : void CWallet::transactionAddedToMempool(const CTransactionRef& tx) {
    1183       18877 :     LOCK(cs_wallet);
    1184       18877 :     SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
    1185             : 
    1186       18877 :     auto it = mapWallet.find(tx->GetHash());
    1187       18877 :     if (it != mapWallet.end()) {
    1188        2754 :         it->second.fInMempool = true;
    1189        2754 :     }
    1190       18877 : }
    1191             : 
    1192       91311 : void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {
    1193       91311 :     LOCK(cs_wallet);
    1194       91311 :     auto it = mapWallet.find(tx->GetHash());
    1195       91311 :     if (it != mapWallet.end()) {
    1196       20483 :         it->second.fInMempool = false;
    1197       20483 :     }
    1198             :     // Handle transactions that were removed from the mempool because they
    1199             :     // conflict with transactions in a newly connected block.
    1200       91311 :     if (reason == MemPoolRemovalReason::CONFLICT) {
    1201             :         // Call SyncNotifications, so external -walletnotify notifications will
    1202             :         // be triggered for these transactions. Set Status::UNCONFIRMED instead
    1203             :         // of Status::CONFLICTED for a few reasons:
    1204             :         //
    1205             :         // 1. The transactionRemovedFromMempool callback does not currently
    1206             :         //    provide the conflicting block's hash and height, and for backwards
    1207             :         //    compatibility reasons it may not be not safe to store conflicted
    1208             :         //    wallet transactions with a null block hash. See
    1209             :         //    https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
    1210             :         // 2. For most of these transactions, the wallet's internal conflict
    1211             :         //    detection in the blockConnected handler will subsequently call
    1212             :         //    MarkConflicted and update them with CONFLICTED status anyway. This
    1213             :         //    applies to any wallet transaction that has inputs spent in the
    1214             :         //    block, or that has ancestors in the wallet with inputs spent by
    1215             :         //    the block.
    1216             :         // 3. Longstanding behavior since the sync implementation in
    1217             :         //    https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
    1218             :         //    implementation before that was to mark these transactions
    1219             :         //    unconfirmed rather than conflicted.
    1220             :         //
    1221             :         // Nothing described above should be seen as an unchangeable requirement
    1222             :         // when improving this code in the future. The wallet's heuristics for
    1223             :         // distinguishing between conflicted and unconfirmed transactions are
    1224             :         // imperfect, and could be improved in general, see
    1225             :         // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
    1226          49 :         SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
    1227             :     }
    1228       91311 : }
    1229             : 
    1230       45219 : void CWallet::blockConnected(const CBlock& block, int height)
    1231             : {
    1232       45219 :     const uint256& block_hash = block.GetHash();
    1233       45219 :     LOCK(cs_wallet);
    1234             : 
    1235       45219 :     m_last_block_processed_height = height;
    1236       45219 :     m_last_block_processed = block_hash;
    1237      136083 :     for (size_t index = 0; index < block.vtx.size(); index++) {
    1238       90864 :         SyncTransaction(block.vtx[index], {CWalletTx::Status::CONFIRMED, height, block_hash, (int)index});
    1239       90864 :         transactionRemovedFromMempool(block.vtx[index], MemPoolRemovalReason::BLOCK);
    1240             :     }
    1241       45219 : }
    1242             : 
    1243        2753 : void CWallet::blockDisconnected(const CBlock& block, int height)
    1244             : {
    1245        2753 :     LOCK(cs_wallet);
    1246             : 
    1247             :     // At block disconnection, this will change an abandoned transaction to
    1248             :     // be unconfirmed, whether or not the transaction is added back to the mempool.
    1249             :     // User may have to call abandontransaction again. It may be addressed in the
    1250             :     // future with a stickier abandoned state or even removing abandontransaction call.
    1251        2753 :     m_last_block_processed_height = height - 1;
    1252        2753 :     m_last_block_processed = block.hashPrevBlock;
    1253       11670 :     for (const CTransactionRef& ptx : block.vtx) {
    1254        8917 :         SyncTransaction(ptx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
    1255             :     }
    1256        2753 : }
    1257             : 
    1258       42874 : void CWallet::updatedBlockTip()
    1259             : {
    1260       42874 :     m_best_block_time = GetTime();
    1261       42874 : }
    1262             : 
    1263             : 
    1264        4635 : void CWallet::BlockUntilSyncedToCurrentChain() const {
    1265        4635 :     AssertLockNotHeld(cs_wallet);
    1266             :     // Skip the queue-draining stuff if we know we're caught up with
    1267             :     // ::ChainActive().Tip(), otherwise put a callback in the validation interface queue and wait
    1268             :     // for the queue to drain enough to execute it (indicating we are caught up
    1269             :     // at least with the time we entered this function).
    1270        9270 :     uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
    1271        4635 :     chain().waitForNotificationsIfTipChanged(last_block_hash);
    1272        4635 : }
    1273             : 
    1274             : 
    1275         412 : isminetype CWallet::IsMine(const CTxIn &txin) const
    1276             : {
    1277         412 :     AssertLockHeld(cs_wallet);
    1278         412 :     std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
    1279         412 :     if (mi != mapWallet.end())
    1280             :     {
    1281           4 :         const CWalletTx& prev = (*mi).second;
    1282           4 :         if (txin.prevout.n < prev.tx->vout.size())
    1283           4 :             return IsMine(prev.tx->vout[txin.prevout.n]);
    1284           0 :     }
    1285         408 :     return ISMINE_NO;
    1286         412 : }
    1287             : 
    1288             : // Note that this function doesn't distinguish between a 0-valued input,
    1289             : // and a not-"is mine" (according to the filter) input.
    1290      238071 : CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
    1291             : {
    1292             :     {
    1293      238071 :         LOCK(cs_wallet);
    1294      238071 :         std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
    1295      238071 :         if (mi != mapWallet.end())
    1296             :         {
    1297       26390 :             const CWalletTx& prev = (*mi).second;
    1298       26390 :             if (txin.prevout.n < prev.tx->vout.size())
    1299       26390 :                 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
    1300      250302 :                     return prev.tx->vout[txin.prevout.n].nValue;
    1301       14159 :         }
    1302      238071 :     }
    1303      225840 :     return 0;
    1304      238071 : }
    1305             : 
    1306      970384 : isminetype CWallet::IsMine(const CTxOut& txout) const
    1307             : {
    1308      970384 :     AssertLockHeld(cs_wallet);
    1309      970384 :     return IsMine(txout.scriptPubKey);
    1310             : }
    1311             : 
    1312       14866 : isminetype CWallet::IsMine(const CTxDestination& dest) const
    1313             : {
    1314       14866 :     AssertLockHeld(cs_wallet);
    1315       14866 :     return IsMine(GetScriptForDestination(dest));
    1316           0 : }
    1317             : 
    1318      987365 : isminetype CWallet::IsMine(const CScript& script) const
    1319             : {
    1320      987365 :     AssertLockHeld(cs_wallet);
    1321      987365 :     isminetype result = ISMINE_NO;
    1322     2286484 :     for (const auto& spk_man_pair : m_spk_managers) {
    1323     1299119 :         result = std::max(result, spk_man_pair.second->IsMine(script));
    1324             :     }
    1325     1974730 :     return result;
    1326      987365 : }
    1327             : 
    1328       94249 : CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
    1329             : {
    1330       94249 :     if (!MoneyRange(txout.nValue))
    1331           0 :         throw std::runtime_error(std::string(__func__) + ": value out of range");
    1332       94249 :     LOCK(cs_wallet);
    1333       94249 :     return ((IsMine(txout) & filter) ? txout.nValue : 0);
    1334       94249 : }
    1335             : 
    1336         958 : bool CWallet::IsChange(const CTxOut& txout) const
    1337             : {
    1338         958 :     return IsChange(txout.scriptPubKey);
    1339             : }
    1340             : 
    1341        1907 : bool CWallet::IsChange(const CScript& script) const
    1342             : {
    1343             :     // TODO: fix handling of 'change' outputs. The assumption is that any
    1344             :     // payment to a script that is ours, but is not in the address book
    1345             :     // is change. That assumption is likely to break when we implement multisignature
    1346             :     // wallets that return change back into a multi-signature-protected address;
    1347             :     // a better way of identifying which outputs are 'the send' and which are
    1348             :     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
    1349             :     // which output, if any, was change).
    1350        1907 :     AssertLockHeld(cs_wallet);
    1351        1907 :     if (IsMine(script))
    1352             :     {
    1353        1440 :         CTxDestination address;
    1354        1440 :         if (!ExtractDestination(script, address))
    1355           0 :             return true;
    1356        1440 :         if (!FindAddressBookEntry(address)) {
    1357         486 :             return true;
    1358             :         }
    1359        1440 :     }
    1360        1421 :     return false;
    1361        1907 : }
    1362             : 
    1363           0 : CAmount CWallet::GetChange(const CTxOut& txout) const
    1364             : {
    1365           0 :     AssertLockHeld(cs_wallet);
    1366           0 :     if (!MoneyRange(txout.nValue))
    1367           0 :         throw std::runtime_error(std::string(__func__) + ": value out of range");
    1368           0 :     return (IsChange(txout) ? txout.nValue : 0);
    1369           0 : }
    1370             : 
    1371      180128 : bool CWallet::IsMine(const CTransaction& tx) const
    1372             : {
    1373      180128 :     AssertLockHeld(cs_wallet);
    1374      560594 :     for (const CTxOut& txout : tx.vout)
    1375      380466 :         if (IsMine(txout))
    1376      380466 :             return true;
    1377      155248 :     return false;
    1378      180128 : }
    1379             : 
    1380      155247 : bool CWallet::IsFromMe(const CTransaction& tx) const
    1381             : {
    1382      155247 :     return (GetDebit(tx, ISMINE_ALL) > 0);
    1383             : }
    1384             : 
    1385      180466 : CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
    1386             : {
    1387      180466 :     CAmount nDebit = 0;
    1388      418537 :     for (const CTxIn& txin : tx.vin)
    1389             :     {
    1390      238071 :         nDebit += GetDebit(txin, filter);
    1391      238071 :         if (!MoneyRange(nDebit))
    1392           0 :             throw std::runtime_error(std::string(__func__) + ": value out of range");
    1393             :     }
    1394      360932 :     return nDebit;
    1395      180466 : }
    1396             : 
    1397         179 : bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
    1398             : {
    1399         179 :     LOCK(cs_wallet);
    1400             : 
    1401         494 :     for (const CTxIn& txin : tx.vin)
    1402             :     {
    1403         315 :         auto mi = mapWallet.find(txin.prevout.hash);
    1404         315 :         if (mi == mapWallet.end())
    1405           0 :             return false; // any unknown inputs can't be from us
    1406             : 
    1407         315 :         const CWalletTx& prev = (*mi).second;
    1408             : 
    1409         315 :         if (txin.prevout.n >= prev.tx->vout.size())
    1410           0 :             return false; // invalid input!
    1411             : 
    1412         315 :         if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
    1413           1 :             return false;
    1414         629 :     }
    1415         178 :     return true;
    1416         179 : }
    1417             : 
    1418       14733 : CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
    1419             : {
    1420       14733 :     CAmount nCredit = 0;
    1421       44160 :     for (const CTxOut& txout : tx.vout)
    1422             :     {
    1423       29427 :         nCredit += GetCredit(txout, filter);
    1424       29427 :         if (!MoneyRange(nCredit))
    1425           0 :             throw std::runtime_error(std::string(__func__) + ": value out of range");
    1426             :     }
    1427       29466 :     return nCredit;
    1428       14733 : }
    1429             : 
    1430           0 : CAmount CWallet::GetChange(const CTransaction& tx) const
    1431             : {
    1432           0 :     LOCK(cs_wallet);
    1433           0 :     CAmount nChange = 0;
    1434           0 :     for (const CTxOut& txout : tx.vout)
    1435             :     {
    1436           0 :         nChange += GetChange(txout);
    1437           0 :         if (!MoneyRange(nChange))
    1438           0 :             throw std::runtime_error(std::string(__func__) + ": value out of range");
    1439             :     }
    1440           0 :     return nChange;
    1441           0 : }
    1442             : 
    1443           3 : bool CWallet::IsHDEnabled() const
    1444             : {
    1445             :     // All Active ScriptPubKeyMans must be HD for this to be true
    1446             :     bool result = true;
    1447           6 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
    1448           3 :         result &= spk_man->IsHDEnabled();
    1449           0 :     }
    1450           3 :     return result;
    1451           0 : }
    1452             : 
    1453        8747 : bool CWallet::CanGetAddresses(bool internal) const
    1454             : {
    1455        8747 :     LOCK(cs_wallet);
    1456        8747 :     if (m_spk_managers.empty()) return false;
    1457        8873 :     for (OutputType t : OUTPUT_TYPES) {
    1458        8833 :         auto spk_man = GetScriptPubKeyMan(t, internal);
    1459        8833 :         if (spk_man && spk_man->CanGetAddresses(internal)) {
    1460        8705 :             return true;
    1461             :         }
    1462        8961 :     }
    1463          40 :     return false;
    1464        8747 : }
    1465             : 
    1466         139 : void CWallet::SetWalletFlag(uint64_t flags)
    1467             : {
    1468         139 :     LOCK(cs_wallet);
    1469         139 :     m_wallet_flags |= flags;
    1470         139 :     if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags))
    1471           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1472         139 : }
    1473             : 
    1474           0 : void CWallet::UnsetWalletFlag(uint64_t flag)
    1475             : {
    1476           0 :     WalletBatch batch(*database);
    1477           0 :     UnsetWalletFlagWithDB(batch, flag);
    1478           0 : }
    1479             : 
    1480       11323 : void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
    1481             : {
    1482       11323 :     LOCK(cs_wallet);
    1483       11323 :     m_wallet_flags &= ~flag;
    1484       11323 :     if (!batch.WriteWalletFlags(m_wallet_flags))
    1485           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1486       11323 : }
    1487             : 
    1488       11323 : void CWallet::UnsetBlankWalletFlag(WalletBatch& batch)
    1489             : {
    1490       11323 :     UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
    1491       11323 : }
    1492             : 
    1493      320075 : bool CWallet::IsWalletFlagSet(uint64_t flag) const
    1494             : {
    1495      320075 :     return (m_wallet_flags & flag);
    1496             : }
    1497             : 
    1498         725 : bool CWallet::LoadWalletFlags(uint64_t flags)
    1499             : {
    1500         725 :     LOCK(cs_wallet);
    1501         725 :     if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
    1502             :         // contains unknown non-tolerable wallet flags
    1503           0 :         return false;
    1504             :     }
    1505         725 :     m_wallet_flags = flags;
    1506             : 
    1507         725 :     return true;
    1508         725 : }
    1509             : 
    1510         420 : bool CWallet::AddWalletFlags(uint64_t flags)
    1511             : {
    1512         420 :     LOCK(cs_wallet);
    1513             :     // We should never be writing unknown non-tolerable wallet flags
    1514         420 :     assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
    1515         420 :     if (!WalletBatch(*database).WriteWalletFlags(flags)) {
    1516           0 :         throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
    1517             :     }
    1518             : 
    1519         420 :     return LoadWalletFlags(flags);
    1520         420 : }
    1521             : 
    1522        2028 : int64_t CWalletTx::GetTxTime() const
    1523             : {
    1524        2028 :     int64_t n = nTimeSmart;
    1525        2028 :     return n ? n : nTimeReceived;
    1526             : }
    1527             : 
    1528             : // Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
    1529             : // or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
    1530      353703 : bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
    1531             : {
    1532             :     // Fill in dummy signatures for fee calculation.
    1533      353703 :     const CScript& scriptPubKey = txout.scriptPubKey;
    1534      353703 :     SignatureData sigdata;
    1535             : 
    1536      353703 :     std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
    1537      353703 :     if (!provider) {
    1538             :         // We don't know about this scriptpbuKey;
    1539      111414 :         return false;
    1540             :     }
    1541             : 
    1542      242289 :     if (!ProduceSignature(*provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
    1543           0 :         return false;
    1544             :     }
    1545      242289 :     UpdateInput(tx_in, sigdata);
    1546      242289 :     return true;
    1547      353703 : }
    1548             : 
    1549             : // Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
    1550        3151 : bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
    1551             : {
    1552             :     // Fill in dummy signatures for fee calculation.
    1553             :     int nIn = 0;
    1554       17014 :     for (const auto& txout : txouts)
    1555             :     {
    1556       13863 :         if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
    1557           0 :             return false;
    1558             :         }
    1559             : 
    1560       13863 :         nIn++;
    1561       13863 :     }
    1562        3151 :     return true;
    1563        3151 : }
    1564             : 
    1565        1377 : bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
    1566             : {
    1567        1377 :     auto spk_man = GetLegacyScriptPubKeyMan();
    1568        1377 :     if (!spk_man) {
    1569           0 :         return false;
    1570             :     }
    1571        1377 :     LOCK(spk_man->cs_KeyStore);
    1572        1377 :     return spk_man->ImportScripts(scripts, timestamp);
    1573        1377 : }
    1574             : 
    1575        1335 : bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
    1576             : {
    1577        1335 :     auto spk_man = GetLegacyScriptPubKeyMan();
    1578        1335 :     if (!spk_man) {
    1579           0 :         return false;
    1580             :     }
    1581        1335 :     LOCK(spk_man->cs_KeyStore);
    1582        1335 :     return spk_man->ImportPrivKeys(privkey_map, timestamp);
    1583        1335 : }
    1584             : 
    1585         199 : 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)
    1586             : {
    1587         199 :     auto spk_man = GetLegacyScriptPubKeyMan();
    1588         199 :     if (!spk_man) {
    1589           0 :         return false;
    1590             :     }
    1591         199 :     LOCK(spk_man->cs_KeyStore);
    1592         199 :     return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
    1593         199 : }
    1594             : 
    1595         281 : 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)
    1596             : {
    1597         281 :     auto spk_man = GetLegacyScriptPubKeyMan();
    1598         281 :     if (!spk_man) {
    1599           0 :         return false;
    1600             :     }
    1601         281 :     LOCK(spk_man->cs_KeyStore);
    1602         281 :     if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
    1603           0 :         return false;
    1604             :     }
    1605         281 :     if (apply_label) {
    1606         265 :         WalletBatch batch(*database);
    1607         648 :         for (const CScript& script : script_pub_keys) {
    1608         383 :             CTxDestination dest;
    1609         383 :             ExtractDestination(script, dest);
    1610         383 :             if (IsValidDestination(dest)) {
    1611         374 :                 SetAddressBookWithDB(batch, dest, label, "receive");
    1612         374 :             }
    1613         383 :         }
    1614         265 :     }
    1615         281 :     return true;
    1616         281 : }
    1617             : 
    1618        3151 : int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig)
    1619             : {
    1620        3151 :     std::vector<CTxOut> txouts;
    1621       17014 :     for (const CTxIn& input : tx.vin) {
    1622       13863 :         const auto mi = wallet->mapWallet.find(input.prevout.hash);
    1623             :         // Can not estimate size without knowing the input details
    1624       13863 :         if (mi == wallet->mapWallet.end()) {
    1625           0 :             return -1;
    1626             :         }
    1627       13863 :         assert(input.prevout.n < mi->second.tx->vout.size());
    1628       13863 :         txouts.emplace_back(mi->second.tx->vout[input.prevout.n]);
    1629       13863 :     }
    1630        3151 :     return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
    1631        3151 : }
    1632             : 
    1633             : // txouts needs to be in the order of tx.vin
    1634        3151 : int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig)
    1635             : {
    1636        3151 :     CMutableTransaction txNew(tx);
    1637        3151 :     if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
    1638           0 :         return -1;
    1639             :     }
    1640        3151 :     return GetVirtualTransactionSize(CTransaction(txNew));
    1641        3151 : }
    1642             : 
    1643      339840 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, bool use_max_sig)
    1644             : {
    1645      339840 :     CMutableTransaction txn;
    1646      339840 :     txn.vin.push_back(CTxIn(COutPoint()));
    1647      339840 :     if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
    1648      111414 :         return -1;
    1649             :     }
    1650      228426 :     return GetVirtualTransactionInputSize(txn.vin[0]);
    1651      339840 : }
    1652             : 
    1653       19442 : void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
    1654             :                            std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const
    1655             : {
    1656       19442 :     nFee = 0;
    1657       19442 :     listReceived.clear();
    1658       19442 :     listSent.clear();
    1659             : 
    1660             :     // Compute fee:
    1661       19442 :     CAmount nDebit = GetDebit(filter);
    1662       19442 :     if (nDebit > 0) // debit>0 means we signed/sent this transaction
    1663             :     {
    1664         401 :         CAmount nValueOut = tx->GetValueOut();
    1665         401 :         nFee = nDebit - nValueOut;
    1666         401 :     }
    1667             : 
    1668       19442 :     LOCK(pwallet->cs_wallet);
    1669             :     // Sent/received.
    1670       58303 :     for (unsigned int i = 0; i < tx->vout.size(); ++i)
    1671             :     {
    1672       38861 :         const CTxOut& txout = tx->vout[i];
    1673       38861 :         isminetype fIsMine = pwallet->IsMine(txout);
    1674             :         // Only need to handle txouts if AT LEAST one of these is true:
    1675             :         //   1) they debit from us (sent)
    1676             :         //   2) the output is to us (received)
    1677       38861 :         if (nDebit > 0)
    1678             :         {
    1679             :             // Don't report 'change' txouts
    1680         765 :             if (pwallet->IsChange(txout))
    1681         315 :                 continue;
    1682             :         }
    1683       38096 :         else if (!(fIsMine & filter))
    1684       19057 :             continue;
    1685             : 
    1686             :         // In either case, we need to get the destination address
    1687       19489 :         CTxDestination address;
    1688             : 
    1689       19489 :         if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
    1690             :         {
    1691           0 :             pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
    1692           0 :                                     this->GetHash().ToString());
    1693           0 :             address = CNoDestination();
    1694           0 :         }
    1695             : 
    1696       19489 :         COutputEntry output = {address, txout.nValue, (int)i};
    1697             : 
    1698             :         // If we are debited by the transaction, add the output as a "sent" entry
    1699       19489 :         if (nDebit > 0)
    1700         450 :             listSent.push_back(output);
    1701             : 
    1702             :         // If we are receiving the output, add it as a "received" entry
    1703       19489 :         if (fIsMine & filter)
    1704       19218 :             listReceived.push_back(output);
    1705       19489 :     }
    1706             : 
    1707       19442 : }
    1708             : 
    1709             : /**
    1710             :  * Scan active chain for relevant transactions after importing keys. This should
    1711             :  * be called whenever new keys are added to the wallet, with the oldest key
    1712             :  * creation time.
    1713             :  *
    1714             :  * @return Earliest timestamp that could be successfully scanned from. Timestamp
    1715             :  * returned will be higher than startTime if relevant blocks could not be read.
    1716             :  */
    1717         547 : int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
    1718             : {
    1719             :     // Find starting block. May be null if nCreateTime is greater than the
    1720             :     // highest blockchain timestamp, in which case there is nothing that needs
    1721             :     // to be scanned.
    1722         547 :     int start_height = 0;
    1723         547 :     uint256 start_block;
    1724         547 :     bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
    1725        1094 :     WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
    1726             : 
    1727         547 :     if (start) {
    1728             :         // TODO: this should take into account failure by ScanResult::USER_ABORT
    1729         547 :         ScanResult result = ScanForWalletTransactions(start_block, start_height, {} /* max_height */, reserver, update);
    1730         547 :         if (result.status == ScanResult::FAILURE) {
    1731           1 :             int64_t time_max;
    1732           1 :             CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
    1733           1 :             return time_max + TIMESTAMP_WINDOW + 1;
    1734           1 :         }
    1735         547 :     }
    1736         546 :     return startTime;
    1737         547 : }
    1738             : 
    1739             : /**
    1740             :  * Scan the block chain (starting in start_block) for transactions
    1741             :  * from or to us. If fUpdate is true, found transactions that already
    1742             :  * exist in the wallet will be updated.
    1743             :  *
    1744             :  * @param[in] start_block Scan starting block. If block is not on the active
    1745             :  *                        chain, the scan will return SUCCESS immediately.
    1746             :  * @param[in] start_height Height of start_block
    1747             :  * @param[in] max_height  Optional max scanning height. If unset there is
    1748             :  *                        no maximum and scanning can continue to the tip
    1749             :  *
    1750             :  * @return ScanResult returning scan information and indicating success or
    1751             :  *         failure. Return status will be set to SUCCESS if scan was
    1752             :  *         successful. FAILURE if a complete rescan was not possible (due to
    1753             :  *         pruning or corruption). USER_ABORT if the rescan was aborted before
    1754             :  *         it could complete.
    1755             :  *
    1756             :  * @pre Caller needs to make sure start_block (and the optional stop_block) are on
    1757             :  * the main chain after to the addition of any new keys you want to detect
    1758             :  * transactions for.
    1759             :  */
    1760         639 : CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, int start_height, Optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate)
    1761             : {
    1762         639 :     int64_t nNow = GetTime();
    1763         639 :     int64_t start_time = GetTimeMillis();
    1764             : 
    1765         639 :     assert(reserver.isReserved());
    1766             : 
    1767         639 :     uint256 block_hash = start_block;
    1768         639 :     ScanResult result;
    1769             : 
    1770         639 :     WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
    1771             : 
    1772         639 :     fAbortRescan = false;
    1773         639 :     ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
    1774        1278 :     uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
    1775         639 :     uint256 end_hash = tip_hash;
    1776         639 :     if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
    1777         639 :     double progress_begin = chain().guessVerificationProgress(block_hash);
    1778       76903 :     double progress_end = chain().guessVerificationProgress(end_hash);
    1779       77542 :     double progress_current = progress_begin;
    1780         639 :     int block_height = start_height;
    1781       76903 :     while (!fAbortRescan && !chain().shutdownRequested()) {
    1782       76903 :         m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
    1783       76903 :         if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
    1784           1 :             ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
    1785           1 :         }
    1786       76903 :         if (GetTime() >= nNow + 60) {
    1787           0 :             nNow = GetTime();
    1788           0 :             WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
    1789           0 :         }
    1790             : 
    1791       76903 :         CBlock block;
    1792             :         bool next_block;
    1793       76903 :         uint256 next_block_hash;
    1794       76903 :         bool reorg = false;
    1795       76903 :         if (chain().findBlock(block_hash, FoundBlock().data(block)) && !block.IsNull()) {
    1796       76798 :             LOCK(cs_wallet);
    1797       76798 :             next_block = chain().findNextBlock(block_hash, block_height, FoundBlock().hash(next_block_hash), &reorg);
    1798       76798 :             if (reorg) {
    1799             :                 // Abort scan if current block is no longer active, to prevent
    1800             :                 // marking transactions as coming from the wrong block.
    1801             :                 // TODO: This should return success instead of failure, see
    1802             :                 // https://github.com/bitcoin/bitcoin/pull/14711#issuecomment-458342518
    1803           0 :                 result.last_failed_block = block_hash;
    1804           0 :                 result.status = ScanResult::FAILURE;
    1805           0 :                 break;
    1806             :             }
    1807      163131 :             for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
    1808       86333 :                 SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate);
    1809             :             }
    1810             :             // scan succeeded, record block as most recent successfully scanned
    1811       76798 :             result.last_scanned_block = block_hash;
    1812       76798 :             result.last_scanned_height = block_height;
    1813       76798 :         } else {
    1814             :             // could not scan block, keep scanning but record this block as the most recent failure
    1815         105 :             result.last_failed_block = block_hash;
    1816         105 :             result.status = ScanResult::FAILURE;
    1817         105 :             next_block = chain().findNextBlock(block_hash, block_height, FoundBlock().hash(next_block_hash), &reorg);
    1818             :         }
    1819       76903 :         if (max_height && block_height >= *max_height) {
    1820           2 :             break;
    1821             :         }
    1822             :         {
    1823       76901 :             if (!next_block || reorg) {
    1824             :                 // break successfully when rescan has reached the tip, or
    1825             :                 // previous block is no longer on the chain due to a reorg
    1826         637 :                 break;
    1827             :             }
    1828             : 
    1829             :             // increment block and verification progress
    1830       76264 :             block_hash = next_block_hash;
    1831       76264 :             ++block_height;
    1832       76264 :             progress_current = chain().guessVerificationProgress(block_hash);
    1833             : 
    1834             :             // handle updated tip hash
    1835       76264 :             const uint256 prev_tip_hash = tip_hash;
    1836      152528 :             tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
    1837       76264 :             if (!max_height && prev_tip_hash != tip_hash) {
    1838             :                 // in case the tip has changed, update progress max
    1839          12 :                 progress_end = chain().guessVerificationProgress(tip_hash);
    1840          12 :             }
    1841       76264 :         }
    1842       76903 :     }
    1843         639 :     ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 100); // hide progress dialog in GUI
    1844         639 :     if (block_height && fAbortRescan) {
    1845           0 :         WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
    1846           0 :         result.status = ScanResult::USER_ABORT;
    1847         639 :     } else if (block_height && chain().shutdownRequested()) {
    1848           0 :         WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
    1849           0 :         result.status = ScanResult::USER_ABORT;
    1850           0 :     } else {
    1851         639 :         WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
    1852             :     }
    1853             :     return result;
    1854         639 : }
    1855             : 
    1856         967 : void CWallet::ReacceptWalletTransactions()
    1857             : {
    1858             :     // If transactions aren't being broadcasted, don't let them into local mempool either
    1859         967 :     if (!fBroadcastTransactions)
    1860             :         return;
    1861         958 :     std::map<int64_t, CWalletTx*> mapSorted;
    1862             : 
    1863             :     // Sort pending wallet transactions based on their initial wallet insertion order
    1864       25997 :     for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
    1865       25039 :         const uint256& wtxid = item.first;
    1866       25039 :         CWalletTx& wtx = item.second;
    1867       25039 :         assert(wtx.GetHash() == wtxid);
    1868             : 
    1869       25039 :         int nDepth = wtx.GetDepthInMainChain();
    1870             : 
    1871       25039 :         if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
    1872         162 :             mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
    1873         162 :         }
    1874           0 :     }
    1875             : 
    1876             :     // Try to add wallet transactions to memory pool
    1877        1120 :     for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
    1878         162 :         CWalletTx& wtx = *(item.second);
    1879         162 :         std::string unused_err_string;
    1880         162 :         wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
    1881         162 :     }
    1882         967 : }
    1883             : 
    1884        1923 : bool CWalletTx::SubmitMemoryPoolAndRelay(std::string& err_string, bool relay)
    1885             : {
    1886             :     // Can't relay if wallet is not broadcasting
    1887        1923 :     if (!pwallet->GetBroadcastTransactions()) return false;
    1888             :     // Don't relay abandoned transactions
    1889        1923 :     if (isAbandoned()) return false;
    1890             :     // Don't try to submit coinbase transactions. These would fail anyway but would
    1891             :     // cause log spam.
    1892        1923 :     if (IsCoinBase()) return false;
    1893             :     // Don't try to submit conflicted or confirmed transactions.
    1894        1369 :     if (GetDepthInMainChain() != 0) return false;
    1895             : 
    1896             :     // Submit transaction to mempool for relay
    1897        1341 :     pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n", GetHash().ToString());
    1898             :     // We must set fInMempool here - while it will be re-set to true by the
    1899             :     // entered-mempool callback, if we did not there would be a race where a
    1900             :     // user could call sendmoney in a loop and hit spurious out of funds errors
    1901             :     // because we think that this newly generated transaction's change is
    1902             :     // unavailable as we're not yet aware that it is in the mempool.
    1903             :     //
    1904             :     // Irrespective of the failure reason, un-marking fInMempool
    1905             :     // out-of-order is incorrect - it should be unmarked when
    1906             :     // TransactionRemovedFromMempool fires.
    1907        1341 :     bool ret = pwallet->chain().broadcastTransaction(tx, pwallet->m_default_max_tx_fee, relay, err_string);
    1908        1341 :     fInMempool |= ret;
    1909             :     return ret;
    1910        1923 : }
    1911             : 
    1912        2028 : std::set<uint256> CWalletTx::GetConflicts() const
    1913             : {
    1914        2028 :     std::set<uint256> result;
    1915        2028 :     if (pwallet != nullptr)
    1916             :     {
    1917        2028 :         uint256 myHash = GetHash();
    1918        2028 :         result = pwallet->GetConflicts(myHash);
    1919        2028 :         result.erase(myHash);
    1920        2028 :     }
    1921             :     return result;
    1922        2028 : }
    1923             : 
    1924      980356 : CAmount CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
    1925             : {
    1926      980356 :     auto& amount = m_amounts[type];
    1927      980356 :     if (recalculate || !amount.m_cached[filter]) {
    1928       39952 :         amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter) : pwallet->GetCredit(*tx, filter));
    1929       39952 :         m_is_cache_empty = false;
    1930       39952 :     }
    1931      980356 :     return amount.m_value[filter];
    1932             : }
    1933             : 
    1934      477404 : CAmount CWalletTx::GetDebit(const isminefilter& filter) const
    1935             : {
    1936      477404 :     if (tx->vin.empty())
    1937           2 :         return 0;
    1938             : 
    1939             :     CAmount debit = 0;
    1940      477402 :     if (filter & ISMINE_SPENDABLE) {
    1941      457957 :         debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
    1942      457957 :     }
    1943      477402 :     if (filter & ISMINE_WATCH_ONLY) {
    1944      474920 :         debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
    1945      474920 :     }
    1946             :     return debit;
    1947      477404 : }
    1948             : 
    1949         237 : CAmount CWalletTx::GetCredit(const isminefilter& filter) const
    1950             : {
    1951             :     // Must wait until coinbase is safely deep enough in the chain before valuing it
    1952         237 :     if (IsImmatureCoinBase())
    1953           9 :         return 0;
    1954             : 
    1955             :     CAmount credit = 0;
    1956         228 :     if (filter & ISMINE_SPENDABLE) {
    1957             :         // GetBalance can assume transactions in mapWallet won't change
    1958         228 :         credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
    1959         228 :     }
    1960         228 :     if (filter & ISMINE_WATCH_ONLY) {
    1961           9 :         credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
    1962           9 :     }
    1963             :     return credit;
    1964         237 : }
    1965             : 
    1966       89910 : CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
    1967             : {
    1968       89910 :     if (IsImmatureCoinBase() && IsInMainChain()) {
    1969       23622 :         return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
    1970             :     }
    1971             : 
    1972       66288 :     return 0;
    1973       89910 : }
    1974             : 
    1975      179816 : CAmount CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter) const
    1976             : {
    1977      179816 :     if (pwallet == nullptr)
    1978           0 :         return 0;
    1979             : 
    1980             :     // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
    1981      179816 :     bool allow_cache = (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;
    1982             : 
    1983             :     // Must wait until coinbase is safely deep enough in the chain before valuing it
    1984      179816 :     if (IsImmatureCoinBase())
    1985       47262 :         return 0;
    1986             : 
    1987      132554 :     if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
    1988       97470 :         return m_amounts[AVAILABLE_CREDIT].m_value[filter];
    1989             :     }
    1990             : 
    1991       35084 :     bool allow_used_addresses = (filter & ISMINE_USED) || !pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
    1992       35084 :     CAmount nCredit = 0;
    1993       35084 :     uint256 hashTx = GetHash();
    1994      110528 :     for (unsigned int i = 0; i < tx->vout.size(); i++)
    1995             :     {
    1996       75444 :         if (!pwallet->IsSpent(hashTx, i) && (allow_used_addresses || !pwallet->IsSpentKey(hashTx, i))) {
    1997       64822 :             const CTxOut &txout = tx->vout[i];
    1998       64822 :             nCredit += pwallet->GetCredit(txout, filter);
    1999       64822 :             if (!MoneyRange(nCredit))
    2000           0 :                 throw std::runtime_error(std::string(__func__) + " : value out of range");
    2001       64822 :         }
    2002             :     }
    2003             : 
    2004       35084 :     if (allow_cache) {
    2005       35084 :         m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
    2006       35084 :         m_is_cache_empty = false;
    2007       35084 :     }
    2008             : 
    2009       35084 :     return nCredit;
    2010      214900 : }
    2011             : 
    2012       89908 : CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const
    2013             : {
    2014       89908 :     if (IsImmatureCoinBase() && IsInMainChain()) {
    2015       23620 :         return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
    2016             :     }
    2017             : 
    2018       66288 :     return 0;
    2019       89908 : }
    2020             : 
    2021           0 : CAmount CWalletTx::GetChange() const
    2022             : {
    2023           0 :     if (fChangeCached)
    2024           0 :         return nChangeCached;
    2025           0 :     nChangeCached = pwallet->GetChange(*tx);
    2026           0 :     fChangeCached = true;
    2027           0 :     return nChangeCached;
    2028           0 : }
    2029             : 
    2030       23913 : bool CWalletTx::InMempool() const
    2031             : {
    2032       23913 :     return fInMempool;
    2033             : }
    2034             : 
    2035         553 : bool CWalletTx::IsTrusted() const
    2036             : {
    2037         553 :     std::set<uint256> trusted_parents;
    2038         553 :     LOCK(pwallet->cs_wallet);
    2039         553 :     return pwallet->IsTrusted(*this, trusted_parents);
    2040         553 : }
    2041             : 
    2042      461327 : bool CWallet::IsTrusted(const CWalletTx& wtx, std::set<uint256>& trusted_parents) const
    2043             : {
    2044      461327 :     AssertLockHeld(cs_wallet);
    2045             :     // Quick answer in most cases
    2046      461327 :     if (!chain().checkFinalTx(*wtx.tx)) return false;
    2047      461326 :     int nDepth = wtx.GetDepthInMainChain();
    2048      461326 :     if (nDepth >= 1) return true;
    2049       11147 :     if (nDepth < 0) return false;
    2050             :     // using wtx's cached debit
    2051       11022 :     if (!m_spend_zero_conf_change || !wtx.IsFromMe(ISMINE_ALL)) return false;
    2052             : 
    2053             :     // Don't trust unconfirmed transactions from us unless they are in the mempool.
    2054        9971 :     if (!wtx.InMempool()) return false;
    2055             : 
    2056             :     // Trusted if all inputs are from us and are in the mempool:
    2057       27096 :     for (const CTxIn& txin : wtx.tx->vin)
    2058             :     {
    2059             :         // Transactions not sent by us: not trusted
    2060       17177 :         const CWalletTx* parent = GetWalletTx(txin.prevout.hash);
    2061       17177 :         if (parent == nullptr) return false;
    2062       17177 :         const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
    2063             :         // Check that this specific input being spent is trusted
    2064       17177 :         if (IsMine(parentOut) != ISMINE_SPENDABLE) return false;
    2065             :         // If we've already trusted this parent, continue
    2066       17172 :         if (trusted_parents.count(parent->GetHash())) continue;
    2067             :         // Recurse to check that the parent is also trusted
    2068       13801 :         if (!IsTrusted(*parent, trusted_parents)) return false;
    2069       13778 :         trusted_parents.insert(parent->GetHash());
    2070       27556 :     }
    2071        9891 :     return true;
    2072      461327 : }
    2073             : 
    2074        2572 : bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
    2075             : {
    2076        2572 :         CMutableTransaction tx1 {*this->tx};
    2077        2572 :         CMutableTransaction tx2 {*_tx.tx};
    2078        5155 :         for (auto& txin : tx1.vin) txin.scriptSig = CScript();
    2079        5186 :         for (auto& txin : tx2.vin) txin.scriptSig = CScript();
    2080        2572 :         return CTransaction(tx1) == CTransaction(tx2);
    2081        2572 : }
    2082             : 
    2083             : // Rebroadcast transactions from the wallet. We do this on a random timer
    2084             : // to slightly obfuscate which transactions come from our wallet.
    2085             : //
    2086             : // Ideally, we'd only resend transactions that we think should have been
    2087             : // mined in the most recent block. Any transaction that wasn't in the top
    2088             : // blockweight of transactions in the mempool shouldn't have been mined,
    2089             : // and so is probably just sitting in the mempool waiting to be confirmed.
    2090             : // Rebroadcasting does nothing to speed up confirmation and only damages
    2091             : // privacy.
    2092       13157 : void CWallet::ResendWalletTransactions()
    2093             : {
    2094             :     // During reindex, importing and IBD, old wallet transactions become
    2095             :     // unconfirmed. Don't resend them as that would spam other nodes.
    2096       13157 :     if (!chain().isReadyToBroadcast()) return;
    2097             : 
    2098             :     // Do this infrequently and randomly to avoid giving away
    2099             :     // that these are our transactions.
    2100       12161 :     if (GetTime() < nNextResend || !fBroadcastTransactions) return;
    2101         480 :     bool fFirst = (nNextResend == 0);
    2102             :     // resend 12-36 hours from now, ~1 day on average.
    2103         480 :     nNextResend = GetTime() + (12 * 60 * 60) + GetRand(24 * 60 * 60);
    2104         480 :     if (fFirst) return;
    2105             : 
    2106         915 :     int submitted_tx_count = 0;
    2107             : 
    2108             :     { // cs_wallet scope
    2109           8 :         LOCK(cs_wallet);
    2110             : 
    2111             :         // Relay transactions
    2112         915 :         for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
    2113         907 :             CWalletTx& wtx = item.second;
    2114             :             // Attempt to rebroadcast all txes more than 5 minutes older than
    2115             :             // the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
    2116             :             // any confirmed or conflicting txs.
    2117         907 :             if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
    2118         582 :             std::string unused_err_string;
    2119         582 :             if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) ++submitted_tx_count;
    2120        1164 :         }
    2121           8 :     } // cs_wallet
    2122             : 
    2123           8 :     if (submitted_tx_count > 0) {
    2124           0 :         WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
    2125           0 :     }
    2126       13165 : }
    2127             : 
    2128             : /** @} */ // end of mapWallet
    2129             : 
    2130       12554 : void MaybeResendWalletTxs()
    2131             : {
    2132       25711 :     for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
    2133       13157 :         pwallet->ResendWalletTransactions();
    2134             :     }
    2135       12554 : }
    2136             : 
    2137             : 
    2138             : /** @defgroup Actions
    2139             :  *
    2140             :  * @{
    2141             :  */
    2142             : 
    2143             : 
    2144        1809 : CWallet::Balance CWallet::GetBalance(const int min_depth, bool avoid_reuse) const
    2145             : {
    2146        1809 :     Balance ret;
    2147        1809 :     isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
    2148             :     {
    2149        1809 :         LOCK(cs_wallet);
    2150        1809 :         std::set<uint256> trusted_parents;
    2151       91717 :         for (const auto& entry : mapWallet)
    2152             :         {
    2153       89908 :             const CWalletTx& wtx = entry.second;
    2154       89908 :             const bool is_trusted{IsTrusted(wtx, trusted_parents)};
    2155       89908 :             const int tx_depth{wtx.GetDepthInMainChain()};
    2156       89908 :             const CAmount tx_credit_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE | reuse_filter)};
    2157       89908 :             const CAmount tx_credit_watchonly{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_WATCH_ONLY | reuse_filter)};
    2158       89908 :             if (is_trusted && tx_depth >= min_depth) {
    2159       89548 :                 ret.m_mine_trusted += tx_credit_mine;
    2160       89548 :                 ret.m_watchonly_trusted += tx_credit_watchonly;
    2161       89548 :             }
    2162       89908 :             if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
    2163         192 :                 ret.m_mine_untrusted_pending += tx_credit_mine;
    2164         192 :                 ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
    2165         192 :             }
    2166       89908 :             ret.m_mine_immature += wtx.GetImmatureCredit();
    2167       89908 :             ret.m_watchonly_immature += wtx.GetImmatureWatchOnlyCredit();
    2168           0 :         }
    2169        1809 :     }
    2170             :     return ret;
    2171        1809 : }
    2172             : 
    2173           1 : CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
    2174             : {
    2175           1 :     LOCK(cs_wallet);
    2176             : 
    2177             :     CAmount balance = 0;
    2178           1 :     std::vector<COutput> vCoins;
    2179           1 :     AvailableCoins(vCoins, true, coinControl);
    2180           2 :     for (const COutput& out : vCoins) {
    2181           1 :         if (out.fSpendable) {
    2182           1 :             balance += out.tx->tx->vout[out.i].nValue;
    2183           1 :         }
    2184             :     }
    2185             :     return balance;
    2186           1 : }
    2187             : 
    2188        3041 : void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe, const CCoinControl* coinControl, const CAmount& nMinimumAmount, const CAmount& nMaximumAmount, const CAmount& nMinimumSumAmount, const uint64_t nMaximumCount) const
    2189             : {
    2190        3041 :     AssertLockHeld(cs_wallet);
    2191             : 
    2192        3041 :     vCoins.clear();
    2193     2800446 :     CAmount nTotal = 0;
    2194             :     // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
    2195             :     // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
    2196        3041 :     bool allow_used_addresses = !IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
    2197        3041 :     const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
    2198        3041 :     const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
    2199             : 
    2200        3041 :     std::set<uint256> trusted_parents;
    2201      570341 :     for (const auto& entry : mapWallet)
    2202             :     {
    2203      567300 :         const uint256& wtxid = entry.first;
    2204      567300 :         const CWalletTx& wtx = entry.second;
    2205             : 
    2206      567300 :         if (!chain().checkFinalTx(*wtx.tx)) {
    2207           0 :             continue;
    2208             :         }
    2209             : 
    2210      567300 :         if (wtx.IsImmatureCoinBase())
    2211      203775 :             continue;
    2212             : 
    2213      363525 :         int nDepth = wtx.GetDepthInMainChain();
    2214      363525 :         if (nDepth < 0)
    2215        2163 :             continue;
    2216             : 
    2217             :         // We should not consider coins which aren't at least in our mempool
    2218             :         // It's possible for these to be conflicted via ancestors which we may never be able to detect
    2219      361362 :         if (nDepth == 0 && !wtx.InMempool())
    2220        4707 :             continue;
    2221             : 
    2222      356655 :         bool safeTx = IsTrusted(wtx, trusted_parents);
    2223             : 
    2224             :         // We should not consider coins from transactions that are replacing
    2225             :         // other transactions.
    2226             :         //
    2227             :         // Example: There is a transaction A which is replaced by bumpfee
    2228             :         // transaction B. In this case, we want to prevent creation of
    2229             :         // a transaction B' which spends an output of B.
    2230             :         //
    2231             :         // Reason: If transaction A were initially confirmed, transactions B
    2232             :         // and B' would no longer be valid, so the user would have to create
    2233             :         // a new transaction C to replace B'. However, in the case of a
    2234             :         // one-block reorg, transactions B' and C might BOTH be accepted,
    2235             :         // when the user only wanted one of them. Specifically, there could
    2236             :         // be a 1-block reorg away from the chain where transactions A and C
    2237             :         // were accepted to another chain where B, B', and C were all
    2238             :         // accepted.
    2239      356655 :         if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
    2240             :             safeTx = false;
    2241         139 :         }
    2242             : 
    2243             :         // Similarly, we should not consider coins from transactions that
    2244             :         // have been replaced. In the example above, we would want to prevent
    2245             :         // creation of a transaction A' spending an output of A, because if
    2246             :         // transaction B were initially confirmed, conflicting with A and
    2247             :         // A', we wouldn't want to the user to create a transaction D
    2248             :         // intending to replace A', but potentially resulting in a scenario
    2249             :         // where A, A', and D could all be accepted (instead of just B and
    2250             :         // D, or just A and A' like the user would want).
    2251      356655 :         if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
    2252             :             safeTx = false;
    2253           1 :         }
    2254             : 
    2255      356655 :         if (fOnlySafe && !safeTx) {
    2256         722 :             continue;
    2257             :         }
    2258             : 
    2259      355933 :         if (nDepth < min_depth || nDepth > max_depth) {
    2260        2866 :             continue;
    2261             :         }
    2262             : 
    2263     1309738 :         for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
    2264             :             // Only consider selected coins if add_inputs is false
    2265      956671 :             if (coinControl && !coinControl->m_add_inputs && !coinControl->IsSelected(COutPoint(entry.first, i))) {
    2266             :                 continue;
    2267             :             }
    2268             : 
    2269      955384 :             if (wtx.tx->vout[i].nValue < nMinimumAmount || wtx.tx->vout[i].nValue > nMaximumAmount)
    2270             :                 continue;
    2271             : 
    2272      767314 :             if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
    2273             :                 continue;
    2274             : 
    2275      767314 :             if (IsLockedCoin(entry.first, i))
    2276             :                 continue;
    2277             : 
    2278      767128 :             if (IsSpent(wtxid, i))
    2279             :                 continue;
    2280             : 
    2281      412082 :             isminetype mine = IsMine(wtx.tx->vout[i]);
    2282             : 
    2283      412082 :             if (mine == ISMINE_NO) {
    2284      188733 :                 continue;
    2285             :             }
    2286             : 
    2287      223349 :             if (!allow_used_addresses && IsSpentKey(wtxid, i)) {
    2288           6 :                 continue;
    2289             :             }
    2290             : 
    2291      223343 :             std::unique_ptr<SigningProvider> provider = GetSolvingProvider(wtx.tx->vout[i].scriptPubKey);
    2292             : 
    2293      223343 :             bool solvable = provider ? IsSolvable(*provider, wtx.tx->vout[i].scriptPubKey) : false;
    2294      223386 :             bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
    2295             : 
    2296      223343 :             vCoins.push_back(COutput(&wtx, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->fAllowWatchOnly)));
    2297             : 
    2298             :             // Checks the sum amount of all UTXO's.
    2299      223343 :             if (nMinimumSumAmount != MAX_MONEY) {
    2300      223343 :                 nTotal += wtx.tx->vout[i].nValue;
    2301             : 
    2302           0 :                 if (nTotal >= nMinimumSumAmount) {
    2303           0 :                     return;
    2304             :                 }
    2305             :             }
    2306             : 
    2307             :             // Checks the maximum number of UTXO's.
    2308      223343 :             if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
    2309           0 :                 return;
    2310             :             }
    2311      223343 :         }
    2312      706134 :     }
    2313        3041 : }
    2314             : 
    2315           3 : std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
    2316             : {
    2317           3 :     AssertLockHeld(cs_wallet);
    2318             : 
    2319           3 :     std::map<CTxDestination, std::vector<COutput>> result;
    2320           3 :     std::vector<COutput> availableCoins;
    2321             : 
    2322           3 :     AvailableCoins(availableCoins);
    2323             : 
    2324           6 :     for (const COutput& coin : availableCoins) {
    2325           3 :         CTxDestination address;
    2326           6 :         if ((coin.fSpendable || (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && coin.fSolvable)) &&
    2327           3 :             ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
    2328           3 :             result[address].emplace_back(std::move(coin));
    2329             :         }
    2330           3 :     }
    2331             : 
    2332           3 :     std::vector<COutPoint> lockedCoins;
    2333           3 :     ListLockedCoins(lockedCoins);
    2334             :     // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
    2335           3 :     const bool include_watch_only = GetLegacyScriptPubKeyMan() && IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
    2336           3 :     const isminetype is_mine_filter = include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
    2337           5 :     for (const COutPoint& output : lockedCoins) {
    2338           2 :         auto it = mapWallet.find(output.hash);
    2339           2 :         if (it != mapWallet.end()) {
    2340           2 :             int depth = it->second.GetDepthInMainChain();
    2341           4 :             if (depth >= 0 && output.n < it->second.tx->vout.size() &&
    2342           2 :                 IsMine(it->second.tx->vout[output.n]) == is_mine_filter
    2343             :             ) {
    2344           2 :                 CTxDestination address;
    2345           2 :                 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
    2346           4 :                     result[address].emplace_back(
    2347           2 :                         &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
    2348           2 :                 }
    2349           2 :             }
    2350           2 :         }
    2351           2 :     }
    2352             : 
    2353             :     return result;
    2354           3 : }
    2355             : 
    2356           5 : const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
    2357             : {
    2358           5 :     AssertLockHeld(cs_wallet);
    2359          12 :     const CTransaction* ptx = &tx;
    2360          12 :     int n = output;
    2361           7 :     while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
    2362           7 :         const COutPoint& prevout = ptx->vin[0].prevout;
    2363           7 :         auto it = mapWallet.find(prevout.hash);
    2364           7 :         if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
    2365           2 :             !IsMine(it->second.tx->vout[prevout.n])) {
    2366           5 :             break;
    2367             :         }
    2368           2 :         ptx = it->second.tx.get();
    2369           2 :         n = prevout.n;
    2370           7 :     }
    2371           5 :     return ptx->vout[n];
    2372             : }
    2373             : 
    2374       25524 : bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
    2375             :                                  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const
    2376             : {
    2377       25524 :     setCoinsRet.clear();
    2378       25524 :     nValueRet = 0;
    2379             : 
    2380       25524 :     std::vector<OutputGroup> utxo_pool;
    2381       25524 :     if (coin_selection_params.use_bnb) {
    2382             :         // Get long term estimate
    2383       16533 :         FeeCalculation feeCalc;
    2384       16533 :         CCoinControl temp;
    2385       16533 :         temp.m_confirm_target = 1008;
    2386       16533 :         CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp, &feeCalc);
    2387             : 
    2388             :         // Calculate cost of change
    2389       16533 :         CAmount cost_of_change = GetDiscardRate(*this).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size);
    2390             : 
    2391             :         // Filter by the min conf specs and add to utxo_pool and calculate effective value
    2392      818419 :         for (OutputGroup& group : groups) {
    2393      801886 :             if (!group.EligibleForSpending(eligibility_filter)) continue;
    2394             : 
    2395      781891 :             if (coin_selection_params.m_subtract_fee_outputs) {
    2396             :                 // Set the effective feerate to 0 as we don't want to use the effective value since the fees will be deducted from the output
    2397         959 :                 group.SetFees(CFeeRate(0) /* effective_feerate */, long_term_feerate);
    2398             :             } else {
    2399      780932 :                 group.SetFees(coin_selection_params.effective_fee, long_term_feerate);
    2400             :             }
    2401             : 
    2402      781891 :             OutputGroup pos_group = group.GetPositiveOnlyGroup();
    2403      781891 :             if (pos_group.effective_value > 0) utxo_pool.push_back(pos_group);
    2404      781891 :         }
    2405             :         // Calculate the fees for things that aren't inputs
    2406       16533 :         CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
    2407       16533 :         bnb_used = true;
    2408       16533 :         return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
    2409       16533 :     } else {
    2410             :         // Filter by the min conf specs and add to utxo_pool
    2411      714984 :         for (const OutputGroup& group : groups) {
    2412      705993 :             if (!group.EligibleForSpending(eligibility_filter)) continue;
    2413      691870 :             utxo_pool.push_back(group);
    2414      691870 :         }
    2415        8991 :         bnb_used = false;
    2416        8991 :         return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
    2417             :     }
    2418       25524 : }
    2419             : 
    2420        5389 : bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const
    2421             : {
    2422        5389 :     std::vector<COutput> vCoins(vAvailableCoins);
    2423        5389 :     CAmount value_to_select = nTargetValue;
    2424             : 
    2425             :     // Default to bnb was not used. If we use it, we set it later
    2426        5389 :     bnb_used = false;
    2427             : 
    2428             :     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
    2429        5389 :     if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
    2430             :     {
    2431           0 :         for (const COutput& out : vCoins)
    2432             :         {
    2433           0 :             if (!out.fSpendable)
    2434           0 :                  continue;
    2435           0 :             nValueRet += out.tx->tx->vout[out.i].nValue;
    2436           0 :             setCoinsRet.insert(out.GetInputCoin());
    2437           0 :         }
    2438           0 :         return (nValueRet >= nTargetValue);
    2439             :     }
    2440             : 
    2441             :     // calculate value from preset inputs and store them
    2442        5389 :     std::set<CInputCoin> setPresetCoins;
    2443       12735 :     CAmount nValueFromPresetInputs = 0;
    2444             : 
    2445        5389 :     std::vector<COutPoint> vPresetInputs;
    2446        5389 :     coin_control.ListSelected(vPresetInputs);
    2447        6368 :     for (const COutPoint& outpoint : vPresetInputs)
    2448             :     {
    2449         979 :         std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
    2450         979 :         if (it != mapWallet.end())
    2451             :         {
    2452         978 :             const CWalletTx& wtx = it->second;
    2453             :             // Clearly invalid input, fail
    2454         978 :             if (wtx.tx->vout.size() <= outpoint.n) {
    2455           0 :                 return false;
    2456             :             }
    2457             :             // Just to calculate the marginal byte size
    2458         978 :             CInputCoin coin(wtx.tx, outpoint.n, wtx.GetSpendSize(outpoint.n, false));
    2459         978 :             nValueFromPresetInputs += coin.txout.nValue;
    2460         978 :             if (coin.m_input_bytes <= 0) {
    2461           0 :                 return false; // Not solvable, can't estimate size for fee
    2462             :             }
    2463         978 :             coin.effective_value = coin.txout.nValue - coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
    2464         978 :             if (coin_selection_params.use_bnb) {
    2465         447 :                 value_to_select -= coin.effective_value;
    2466         447 :             } else {
    2467         531 :                 value_to_select -= coin.txout.nValue;
    2468             :             }
    2469         978 :             setPresetCoins.insert(coin);
    2470         978 :         } else {
    2471           1 :             return false; // TODO: Allow non-wallet inputs
    2472             :         }
    2473         979 :     }
    2474             : 
    2475             :     // remove preset inputs from vCoins
    2476       48788 :     for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
    2477             :     {
    2478       43400 :         if (setPresetCoins.count(it->GetInputCoin()))
    2479         152 :             it = vCoins.erase(it);
    2480             :         else
    2481       43248 :             ++it;
    2482             :     }
    2483             : 
    2484        5388 :     unsigned int limit_ancestor_count = 0;
    2485        5388 :     unsigned int limit_descendant_count = 0;
    2486        5388 :     chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
    2487        5388 :     size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
    2488        5388 :     size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
    2489        5388 :     bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
    2490             : 
    2491             :     // form groups from remaining coins; note that preset coins will not
    2492             :     // automatically have their associated (same address) coins included
    2493        5388 :     if (coin_control.m_avoid_partial_spends && vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
    2494             :         // Cases where we have 11+ outputs all pointing to the same destination may result in
    2495             :         // privacy leaks as they will potentially be deterministically sorted. We solve that by
    2496             :         // explicitly shuffling the outputs before processing
    2497        1952 :         Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
    2498        1952 :     }
    2499        5388 :     std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends, max_ancestors);
    2500             : 
    2501       15189 :     bool res = value_to_select <= 0 ||
    2502        4975 :         SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
    2503        2738 :         SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
    2504        2590 :         (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
    2505        2413 :         (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3)), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
    2506        2383 :         (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
    2507        2373 :         (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
    2508        2343 :         (m_spend_zero_conf_change && !fRejectLongChains && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
    2509             : 
    2510             :     // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
    2511        5388 :     util::insert(setCoinsRet, setPresetCoins);
    2512             : 
    2513             :     // add preset inputs to the total value selected
    2514        5388 :     nValueRet += nValueFromPresetInputs;
    2515             : 
    2516             :     return res;
    2517        5389 : }
    2518             : 
    2519        2254 : bool CWallet::SignTransaction(CMutableTransaction& tx) const
    2520             : {
    2521        2254 :     AssertLockHeld(cs_wallet);
    2522             : 
    2523             :     // Build coins map
    2524        2254 :     std::map<COutPoint, Coin> coins;
    2525       11033 :     for (auto& input : tx.vin) {
    2526        8779 :         std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
    2527        8779 :         if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
    2528           0 :             return false;
    2529             :         }
    2530        8779 :         const CWalletTx& wtx = mi->second;
    2531        8779 :         coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase());
    2532        8779 :     }
    2533        2254 :     std::map<int, std::string> input_errors;
    2534        2254 :     return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
    2535        2254 : }
    2536             : 
    2537        3893 : bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
    2538             : {
    2539             :     // Try to sign with all ScriptPubKeyMans
    2540        8957 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
    2541             :         // spk_man->SignTransaction will return true if the transaction is complete,
    2542             :         // so we can exit early and return true if that happens
    2543        5064 :         if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
    2544        3883 :             return true;
    2545             :         }
    2546        1181 :     }
    2547             : 
    2548             :     // At this point, one input was not fully signed otherwise we would have exited already
    2549          10 :     return false;
    2550        3893 : }
    2551             : 
    2552         187 : TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed) const
    2553             : {
    2554         187 :     if (n_signed) {
    2555           0 :         *n_signed = 0;
    2556           0 :     }
    2557         187 :     LOCK(cs_wallet);
    2558             :     // Get all of the previous transactions
    2559         449 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
    2560         262 :         const CTxIn& txin = psbtx.tx->vin[i];
    2561         262 :         PSBTInput& input = psbtx.inputs.at(i);
    2562             : 
    2563         262 :         if (PSBTInputSigned(input)) {
    2564           4 :             continue;
    2565             :         }
    2566             : 
    2567             :         // If we have no utxo, grab it from the wallet.
    2568         258 :         if (!input.non_witness_utxo) {
    2569         208 :             const uint256& txhash = txin.prevout.hash;
    2570         208 :             const auto it = mapWallet.find(txhash);
    2571         208 :             if (it != mapWallet.end()) {
    2572         182 :                 const CWalletTx& wtx = it->second;
    2573             :                 // We only need the non_witness_utxo, which is a superset of the witness_utxo.
    2574             :                 //   The signing code will switch to the smaller witness_utxo if this is ok.
    2575         182 :                 input.non_witness_utxo = wtx.tx;
    2576         182 :             }
    2577         208 :         }
    2578         258 :     }
    2579             : 
    2580             :     // Fill in information from ScriptPubKeyMans
    2581         591 :     for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
    2582         404 :         int n_signed_this_spkm = 0;
    2583         404 :         TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs, &n_signed_this_spkm);
    2584         404 :         if (res != TransactionError::OK) {
    2585           2 :             return res;
    2586             :         }
    2587             : 
    2588         402 :         if (n_signed) {
    2589           0 :             (*n_signed) += n_signed_this_spkm;
    2590           0 :         }
    2591         404 :     }
    2592             : 
    2593             :     // Complete if every input is now signed
    2594         185 :     complete = true;
    2595         443 :     for (const auto& input : psbtx.inputs) {
    2596         258 :         complete &= PSBTInputSigned(input);
    2597             :     }
    2598             : 
    2599         185 :     return TransactionError::OK;
    2600         187 : }
    2601             : 
    2602          12 : SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
    2603             : {
    2604          12 :     SignatureData sigdata;
    2605          12 :     CScript script_pub_key = GetScriptForDestination(pkhash);
    2606          31 :     for (const auto& spk_man_pair : m_spk_managers) {
    2607          19 :         if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
    2608          12 :             return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
    2609             :         }
    2610           7 :     }
    2611           0 :     return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
    2612          12 : }
    2613             : 
    2614         156 : bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
    2615             : {
    2616         156 :     std::vector<CRecipient> vecSend;
    2617             : 
    2618             :     // Turn the txout set into a CRecipient vector.
    2619       11929 :     for (size_t idx = 0; idx < tx.vout.size(); idx++) {
    2620       11773 :         const CTxOut& txOut = tx.vout[idx];
    2621       11773 :         CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
    2622       11773 :         vecSend.push_back(recipient);
    2623       11773 :     }
    2624             : 
    2625         156 :     coinControl.fAllowOtherInputs = true;
    2626             : 
    2627         233 :     for (const CTxIn& txin : tx.vin) {
    2628          77 :         coinControl.Select(txin.prevout);
    2629             :     }
    2630             : 
    2631             :     // Acquire the locks to prevent races to the new locked unspents between the
    2632             :     // CreateTransaction call and LockCoin calls (when lockUnspents is true).
    2633         156 :     LOCK(cs_wallet);
    2634             : 
    2635         156 :     CTransactionRef tx_new;
    2636         156 :     if (!CreateTransaction(vecSend, tx_new, nFeeRet, nChangePosInOut, error, coinControl, false)) {
    2637          28 :         return false;
    2638             :     }
    2639             : 
    2640         128 :     if (nChangePosInOut != -1) {
    2641         113 :         tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
    2642         113 :     }
    2643             : 
    2644             :     // Copy output sizes from new transaction; they may have had the fee
    2645             :     // subtracted from them.
    2646       10389 :     for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
    2647       10261 :         tx.vout[idx].nValue = tx_new->vout[idx].nValue;
    2648             :     }
    2649             : 
    2650             :     // Add new txins while keeping original txin scriptSig/order.
    2651         343 :     for (const CTxIn& txin : tx_new->vin) {
    2652         215 :         if (!coinControl.IsSelected(txin.prevout)) {
    2653         160 :             tx.vin.push_back(txin);
    2654             : 
    2655             :         }
    2656         215 :         if (lockUnspents) {
    2657           7 :             LockCoin(txin.prevout);
    2658             :         }
    2659             : 
    2660             :     }
    2661             : 
    2662         128 :     return true;
    2663         156 : }
    2664             : 
    2665        2640 : static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
    2666             : {
    2667        2640 :     if (chain.isInitialBlockDownload()) {
    2668           4 :         return false;
    2669             :     }
    2670             :     constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
    2671        2636 :     int64_t block_time;
    2672        2636 :     CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
    2673        2636 :     if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
    2674          10 :         return false;
    2675             :     }
    2676        2626 :     return true;
    2677        2640 : }
    2678             : 
    2679             : /**
    2680             :  * Return a height-based locktime for new transactions (uses the height of the
    2681             :  * current chain tip unless we are not synced with the current chain
    2682             :  */
    2683        2640 : static uint32_t GetLocktimeForNewTransaction(interfaces::Chain& chain, const uint256& block_hash, int block_height)
    2684             : {
    2685             :     uint32_t locktime;
    2686             :     // Discourage fee sniping.
    2687             :     //
    2688             :     // For a large miner the value of the transactions in the best block and
    2689             :     // the mempool can exceed the cost of deliberately attempting to mine two
    2690             :     // blocks to orphan the current best block. By setting nLockTime such that
    2691             :     // only the next block can include the transaction, we discourage this
    2692             :     // practice as the height restricted and limited blocksize gives miners
    2693             :     // considering fee sniping fewer options for pulling off this attack.
    2694             :     //
    2695             :     // A simple way to think about this is from the wallet's point of view we
    2696             :     // always want the blockchain to move forward. By setting nLockTime this
    2697             :     // way we're basically making the statement that we only want this
    2698             :     // transaction to appear in the next block; we don't want to potentially
    2699             :     // encourage reorgs by allowing transactions to appear at lower heights
    2700             :     // than the next block in forks of the best chain.
    2701             :     //
    2702             :     // Of course, the subsidy is high enough, and transaction volume low
    2703             :     // enough, that fee sniping isn't a problem yet, but by implementing a fix
    2704             :     // now we ensure code won't be written that makes assumptions about
    2705             :     // nLockTime that preclude a fix later.
    2706        2640 :     if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
    2707             :         locktime = block_height;
    2708             : 
    2709             :         // Secondly occasionally randomly pick a nLockTime even further back, so
    2710             :         // that transactions that are delayed after signing for whatever reason,
    2711             :         // e.g. high-latency mix networks and some CoinJoin implementations, have
    2712             :         // better privacy.
    2713        2626 :         if (GetRandInt(10) == 0)
    2714         266 :             locktime = std::max(0, (int)locktime - GetRandInt(100));
    2715             :     } else {
    2716             :         // If our chain is lagging behind, we can't discourage fee sniping nor help
    2717             :         // the privacy of high-latency transactions. To avoid leaking a potentially
    2718             :         // unique "nLockTime fingerprint", set nLockTime to a constant.
    2719             :         locktime = 0;
    2720             :     }
    2721        2640 :     assert(locktime < LOCKTIME_THRESHOLD);
    2722        2640 :     return locktime;
    2723             : }
    2724             : 
    2725        2640 : OutputType CWallet::TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend)
    2726             : {
    2727             :     // If -changetype is specified, always use that change type.
    2728        2640 :     if (change_type) {
    2729          18 :         return *change_type;
    2730             :     }
    2731             : 
    2732             :     // if m_default_address_type is legacy, use legacy address as change (even
    2733             :     // if some of the outputs are P2WPKH or P2WSH).
    2734        2622 :     if (m_default_address_type == OutputType::LEGACY) {
    2735          32 :         return OutputType::LEGACY;
    2736             :     }
    2737             : 
    2738             :     // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
    2739             :     // output.
    2740        5204 :     for (const auto& recipient : vecSend) {
    2741             :         // Check if any destination contains a witness program:
    2742        2614 :         int witnessversion = 0;
    2743        2614 :         std::vector<unsigned char> witnessprogram;
    2744        2614 :         if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
    2745        1979 :             return OutputType::BECH32;
    2746             :         }
    2747        2614 :     }
    2748             : 
    2749             :     // else use m_default_address_type for change
    2750         611 :     return m_default_address_type;
    2751        2640 : }
    2752             : 
    2753        2640 : bool CWallet::CreateTransactionInternal(
    2754             :         const std::vector<CRecipient>& vecSend,
    2755             :         CTransactionRef& tx,
    2756             :         CAmount& nFeeRet,
    2757             :         int& nChangePosInOut,
    2758             :         bilingual_str& error,
    2759             :         const CCoinControl& coin_control,
    2760             :         bool sign)
    2761             : {
    2762       34035 :     CAmount nValue = 0;
    2763        2640 :     const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
    2764        2640 :     ReserveDestination reservedest(this, change_type);
    2765        2640 :     int nChangePosRequest = nChangePosInOut;
    2766       34035 :     unsigned int nSubtractFeeFromAmount = 0;
    2767       31395 :     for (const auto& recipient : vecSend)
    2768             :     {
    2769       28755 :         if (nValue < 0 || recipient.nAmount < 0)
    2770             :         {
    2771           0 :             error = _("Transaction amounts must not be negative");
    2772           0 :             return false;
    2773             :         }
    2774       28755 :         nValue += recipient.nAmount;
    2775             : 
    2776       28755 :         if (recipient.fSubtractFeeFromAmount)
    2777          93 :             nSubtractFeeFromAmount++;
    2778       28755 :     }
    2779        2640 :     if (vecSend.empty())
    2780             :     {
    2781           0 :         error = _("Transaction must have at least one recipient");
    2782           0 :         return false;
    2783             :     }
    2784             : 
    2785        2640 :     CMutableTransaction txNew;
    2786        2640 :     FeeCalculation feeCalc;
    2787             :     CAmount nFeeNeeded;
    2788             :     int nBytes;
    2789             :     {
    2790        2640 :         std::set<CInputCoin> setCoins;
    2791        2640 :         LOCK(cs_wallet);
    2792        2640 :         txNew.nLockTime = GetLocktimeForNewTransaction(chain(), GetLastBlockHash(), GetLastBlockHeight());
    2793             :         {
    2794        2640 :             std::vector<COutput> vAvailableCoins;
    2795        2640 :             AvailableCoins(vAvailableCoins, true, &coin_control, 1, MAX_MONEY, MAX_MONEY, 0);
    2796        2640 :             CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
    2797             : 
    2798             :             // Create change script that will be used if we need change
    2799             :             // TODO: pass in scriptChange instead of reservedest so
    2800             :             // change transaction isn't always pay-to-bitcoin-address
    2801        2640 :             CScript scriptChange;
    2802             : 
    2803             :             // coin control: send change to custom address
    2804        2640 :             if (!boost::get<CNoDestination>(&coin_control.destChange)) {
    2805         209 :                 scriptChange = GetScriptForDestination(coin_control.destChange);
    2806         209 :             } else { // no coin control: send change to newly generated address
    2807             :                 // Note: We use a new key here to keep it from being obvious which side is the change.
    2808             :                 //  The drawback is that by not reusing a previous key, the change may be lost if a
    2809             :                 //  backup is restored, if the backup doesn't have the new private key for the change.
    2810             :                 //  If we reused the old key, it would be possible to add code to look for and
    2811             :                 //  rediscover unknown transactions that were written with keys of ours to recover
    2812             :                 //  post-backup change.
    2813             : 
    2814             :                 // Reserve a new key pair from key pool. If it fails, provide a dummy
    2815             :                 // destination in case we don't need change.
    2816        2431 :                 CTxDestination dest;
    2817        2431 :                 if (!reservedest.GetReservedDestination(dest, true)) {
    2818          26 :                     error = _("Transaction needs a change address, but we can't generate it. Please call keypoolrefill first.");
    2819          26 :                 }
    2820        2431 :                 scriptChange = GetScriptForDestination(dest);
    2821             :                 // A valid destination implies a change script (and
    2822             :                 // vice-versa). An empty change script will abort later, if the
    2823             :                 // change keypool ran out, but change is required.
    2824        2431 :                 CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
    2825        2431 :             }
    2826        2640 :             CTxOut change_prototype_txout(0, scriptChange);
    2827        2640 :             coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
    2828             : 
    2829        2640 :             CFeeRate discard_rate = GetDiscardRate(*this);
    2830             : 
    2831             :             // Get the fee rate to use effective values in coin selection
    2832        2640 :             CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control, &feeCalc);
    2833             :             // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
    2834             :             // provided one
    2835        2640 :             if (coin_control.m_feerate && nFeeRateNeeded > *coin_control.m_feerate) {
    2836           2 :                 error = strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)"), coin_control.m_feerate->ToString(), nFeeRateNeeded.ToString());
    2837           2 :                 return false;
    2838             :             }
    2839             : 
    2840        2638 :             nFeeRet = 0;
    2841        8115 :             bool pick_new_inputs = true;
    2842        2638 :             CAmount nValueIn = 0;
    2843             : 
    2844             :             // BnB selector is the only selector used when this is true.
    2845             :             // That should only happen on the first pass through the loop.
    2846        2638 :             coin_selection_params.use_bnb = true;
    2847        2638 :             coin_selection_params.m_subtract_fee_outputs = nSubtractFeeFromAmount != 0; // If we are doing subtract fee from recipient, don't use effective values
    2848             :             // Start with no fee and loop until there is enough fee
    2849        2638 :             while (true)
    2850             :             {
    2851        5477 :                 nChangePosInOut = nChangePosRequest;
    2852        5477 :                 txNew.vin.clear();
    2853        5477 :                 txNew.vout.clear();
    2854             :                 bool fFirst = true;
    2855             : 
    2856        5477 :                 CAmount nValueToSelect = nValue;
    2857        5477 :                 if (nSubtractFeeFromAmount == 0)
    2858        5281 :                     nValueToSelect += nFeeRet;
    2859             : 
    2860             :                 // vouts to the payees
    2861        5477 :                 if (!coin_selection_params.m_subtract_fee_outputs) {
    2862        5281 :                     coin_selection_params.tx_noinputs_size = 11; // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 output count, 1 witness overhead (dummy, flag, stack size)
    2863        5281 :                 }
    2864       75765 :                 for (const auto& recipient : vecSend)
    2865             :                 {
    2866       70288 :                     CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
    2867             : 
    2868       70288 :                     if (recipient.fSubtractFeeFromAmount)
    2869             :                     {
    2870         208 :                         assert(nSubtractFeeFromAmount != 0);
    2871         208 :                         txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
    2872             : 
    2873         208 :                         if (fFirst) // first receiver pays the remainder not divisible by output count
    2874             :                         {
    2875             :                             fFirst = false;
    2876         196 :                             txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
    2877         196 :                         }
    2878             :                     }
    2879             :                     // Include the fee cost for outputs. Note this is only used for BnB right now
    2880       70288 :                     if (!coin_selection_params.m_subtract_fee_outputs) {
    2881       70074 :                         coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
    2882       70074 :                     }
    2883             : 
    2884       70288 :                     if (IsDust(txout, chain().relayDustFee()))
    2885             :                     {
    2886           0 :                         if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
    2887             :                         {
    2888           0 :                             if (txout.nValue < 0)
    2889           0 :                                 error = _("The transaction amount is too small to pay the fee");
    2890             :                             else
    2891           0 :                                 error = _("The transaction amount is too small to send after the fee has been deducted");
    2892             :                         }
    2893             :                         else
    2894           0 :                             error = _("Transaction amount too small");
    2895        6282 :                         return false;
    2896             :                     }
    2897       70288 :                     txNew.vout.push_back(txout);
    2898       70288 :                 }
    2899             : 
    2900             :                 // Choose coins to use
    2901        5477 :                 bool bnb_used = false;
    2902        5477 :                 if (pick_new_inputs) {
    2903        5388 :                     nValueIn = 0;
    2904        5388 :                     setCoins.clear();
    2905        5388 :                     int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
    2906             :                     // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
    2907             :                     // as lower-bound to allow BnB to do it's thing
    2908        5388 :                     if (change_spend_size == -1) {
    2909          51 :                         coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
    2910          51 :                     } else {
    2911        5337 :                         coin_selection_params.change_spend_size = (size_t)change_spend_size;
    2912             :                     }
    2913        5388 :                     coin_selection_params.effective_fee = nFeeRateNeeded;
    2914        5388 :                     if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
    2915             :                     {
    2916             :                         // If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
    2917        2336 :                         if (bnb_used) {
    2918        2317 :                             coin_selection_params.use_bnb = false;
    2919        2317 :                             continue;
    2920             :                         }
    2921             :                         else {
    2922          19 :                             error = _("Insufficient funds");
    2923          19 :                             return false;
    2924             :                         }
    2925             :                     }
    2926        3052 :                 } else {
    2927          89 :                     bnb_used = false;
    2928             :                 }
    2929             : 
    2930        3141 :                 const CAmount nChange = nValueIn - nValueToSelect;
    2931        3141 :                 if (nChange > 0)
    2932             :                 {
    2933             :                     // Fill a vout to ourself
    2934        2739 :                     CTxOut newTxOut(nChange, scriptChange);
    2935             : 
    2936             :                     // Never create dust outputs; if we would, just
    2937             :                     // add the dust to the fee.
    2938             :                     // The nChange when BnB is used is always going to go to fees.
    2939        2739 :                     if (IsDust(newTxOut, discard_rate) || bnb_used)
    2940             :                     {
    2941          21 :                         nChangePosInOut = -1;
    2942          21 :                         nFeeRet += nChange;
    2943          21 :                     }
    2944             :                     else
    2945             :                     {
    2946        2718 :                         if (nChangePosInOut == -1)
    2947             :                         {
    2948             :                             // Insert change txn at random position:
    2949        2708 :                             nChangePosInOut = GetRandInt(txNew.vout.size()+1);
    2950        2708 :                         }
    2951          10 :                         else if ((unsigned int)nChangePosInOut > txNew.vout.size())
    2952             :                         {
    2953           0 :                             error = _("Change index out of range");
    2954           0 :                             return false;
    2955             :                         }
    2956             : 
    2957        2718 :                         std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
    2958        2718 :                         txNew.vout.insert(position, newTxOut);
    2959        2718 :                     }
    2960        2739 :                 } else {
    2961         402 :                     nChangePosInOut = -1;
    2962             :                 }
    2963             : 
    2964             :                 // Dummy fill vin for maximum size estimation
    2965             :                 //
    2966       16994 :                 for (const auto& coin : setCoins) {
    2967       13853 :                     txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
    2968             :                 }
    2969             : 
    2970        3141 :                 nBytes = CalculateMaximumSignedTxSize(CTransaction(txNew), this, coin_control.fAllowWatchOnly);
    2971        3141 :                 if (nBytes < 0) {
    2972           0 :                     error = _("Signing transaction failed");
    2973           0 :                     return false;
    2974             :                 }
    2975             : 
    2976        3141 :                 nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control, &feeCalc);
    2977        3141 :                 if (feeCalc.reason == FeeReason::FALLBACK && !m_allow_fallback_fee) {
    2978             :                     // eventually allow a fallback fee
    2979           3 :                     error = _("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
    2980           3 :                     return false;
    2981             :                 }
    2982             : 
    2983        3138 :                 if (nFeeRet >= nFeeNeeded) {
    2984             :                     // Reduce fee to only the needed amount if possible. This
    2985             :                     // prevents potential overpayment in fees if the coins
    2986             :                     // selected to meet nFeeNeeded result in a transaction that
    2987             :                     // requires less fee than the prior iteration.
    2988             : 
    2989             :                     // If we have no change and a big enough excess fee, then
    2990             :                     // try to construct transaction again only without picking
    2991             :                     // new inputs. We now know we only need the smaller fee
    2992             :                     // (because of reduced tx size) and so we should add a
    2993             :                     // change output. Only try this once.
    2994         302 :                     if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
    2995          21 :                         unsigned int tx_size_with_change = nBytes + coin_selection_params.change_output_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
    2996          21 :                         CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, nullptr);
    2997          21 :                         CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
    2998          21 :                         if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
    2999             :                             pick_new_inputs = false;
    3000           0 :                             nFeeRet = fee_needed_with_change;
    3001           0 :                             continue;
    3002             :                         }
    3003          21 :                     }
    3004             : 
    3005             :                     // If we have change output already, just increase it
    3006         302 :                     if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
    3007          26 :                         CAmount extraFeePaid = nFeeRet - nFeeNeeded;
    3008          26 :                         std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
    3009          26 :                         change_position->nValue += extraFeePaid;
    3010          26 :                         nFeeRet -= extraFeePaid;
    3011          26 :                     }
    3012         302 :                     break; // Done, enough fee included.
    3013             :                 }
    3014        2836 :                 else if (!pick_new_inputs) {
    3015             :                     // This shouldn't happen, we should have had enough excess
    3016             :                     // fee to pay for the new output and still meet nFeeNeeded
    3017             :                     // Or we should have just subtracted fee from recipients and
    3018             :                     // nFeeNeeded should not have changed
    3019           0 :                     error = _("Transaction fee and change calculation failed");
    3020           0 :                     return false;
    3021             :                 }
    3022             : 
    3023             :                 // Try to reduce change to include necessary fee
    3024        2836 :                 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
    3025        2494 :                     CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
    3026        2494 :                     std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
    3027             :                     // Only reduce change if remaining amount is still a large enough output.
    3028        2494 :                     if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
    3029        2314 :                         change_position->nValue -= additionalFeeNeeded;
    3030        2314 :                         nFeeRet += additionalFeeNeeded;
    3031        2314 :                         break; // Done, able to increase fee from change
    3032             :                     }
    3033        2494 :                 }
    3034             : 
    3035             :                 // If subtracting fee from recipients, we now know what fee we
    3036             :                 // need to subtract, we have no reason to reselect inputs
    3037         522 :                 if (nSubtractFeeFromAmount > 0) {
    3038             :                     pick_new_inputs = false;
    3039          89 :                 }
    3040             : 
    3041             :                 // Include more fee and try again.
    3042         522 :                 nFeeRet = nFeeNeeded;
    3043         522 :                 coin_selection_params.use_bnb = false;
    3044         522 :                 continue;
    3045        5477 :             }
    3046             : 
    3047             :             // Give up if change keypool ran out and change is required
    3048        2616 :             if (scriptChange.empty() && nChangePosInOut != -1) {
    3049           4 :                 return false;
    3050             :             }
    3051        2640 :         }
    3052             : 
    3053             :         // Shuffle selected coins and fill in final vin
    3054        2612 :         txNew.vin.clear();
    3055        2612 :         std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
    3056        2612 :         Shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());
    3057             : 
    3058             :         // Note how the sequence number is set to non-maxint so that
    3059             :         // the nLockTime set above actually works.
    3060             :         //
    3061             :         // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
    3062             :         // we use the highest possible value in that range (maxint-2)
    3063             :         // to avoid conflicting with other possible uses of nSequence,
    3064             :         // and in the spirit of "smallest possible change from prior
    3065             :         // behavior."
    3066        2612 :         const uint32_t nSequence = coin_control.m_signal_bip125_rbf.get_value_or(m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
    3067       12192 :         for (const auto& coin : selected_coins) {
    3068        9580 :             txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
    3069             :         }
    3070             : 
    3071        2612 :         if (sign && !SignTransaction(txNew)) {
    3072           0 :             error = _("Signing transaction failed");
    3073           0 :             return false;
    3074             :         }
    3075             : 
    3076             :         // Return the constructed transaction data.
    3077        2612 :         tx = MakeTransactionRef(std::move(txNew));
    3078             : 
    3079             :         // Limit size
    3080        2612 :         if (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT)
    3081             :         {
    3082           0 :             error = _("Transaction too large");
    3083           0 :             return false;
    3084             :         }
    3085        2640 :     }
    3086             : 
    3087        2612 :     if (nFeeRet > m_default_max_tx_fee) {
    3088          16 :         error = TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED);
    3089          16 :         return false;
    3090             :     }
    3091             : 
    3092        2596 :     if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
    3093             :         // Lastly, ensure this tx will pass the mempool's chain limits
    3094           6 :         if (!chain().checkChainLimits(tx)) {
    3095           2 :             error = _("Transaction has too long of a mempool chain");
    3096           2 :             return false;
    3097             :         }
    3098             :     }
    3099             : 
    3100             :     // Before we return success, we assume any change key will be used to prevent
    3101             :     // accidental re-use.
    3102        2594 :     reservedest.KeepDestination();
    3103             : 
    3104        5188 :     WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
    3105        2594 :               nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
    3106        2594 :               feeCalc.est.pass.start, feeCalc.est.pass.end,
    3107        2594 :               100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
    3108             :               feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
    3109        2594 :               feeCalc.est.fail.start, feeCalc.est.fail.end,
    3110        2594 :               100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
    3111             :               feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
    3112        2594 :     return true;
    3113        2640 : }
    3114             : 
    3115        1353 : bool CWallet::CreateTransaction(
    3116             :         const std::vector<CRecipient>& vecSend,
    3117             :         CTransactionRef& tx,
    3118             :         CAmount& nFeeRet,
    3119             :         int& nChangePosInOut,
    3120             :         bilingual_str& error,
    3121             :         const CCoinControl& coin_control,
    3122             :         bool sign)
    3123             : {
    3124        1353 :     int nChangePosIn = nChangePosInOut;
    3125        1353 :     CTransactionRef tx2 = tx;
    3126        1353 :     bool res = CreateTransactionInternal(vecSend, tx, nFeeRet, nChangePosInOut, error, coin_control, sign);
    3127             :     // try with avoidpartialspends unless it's enabled already
    3128        1353 :     if (res && nFeeRet > 0 /* 0 means non-functional fee rate estimation */ && m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
    3129        1287 :         CCoinControl tmp_cc = coin_control;
    3130        1287 :         tmp_cc.m_avoid_partial_spends = true;
    3131        1287 :         CAmount nFeeRet2;
    3132        1287 :         int nChangePosInOut2 = nChangePosIn;
    3133        1287 :         bilingual_str error2; // fired and forgotten; if an error occurs, we discard the results
    3134        1287 :         if (CreateTransactionInternal(vecSend, tx2, nFeeRet2, nChangePosInOut2, error2, tmp_cc, sign)) {
    3135             :             // if fee of this alternative one is within the range of the max fee, we use this one
    3136        1284 :             const bool use_aps = nFeeRet2 <= nFeeRet + m_max_aps_fee;
    3137        1284 :             WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet, nFeeRet2, use_aps ? "grouped" : "non-grouped");
    3138        1284 :             if (use_aps) {
    3139         972 :                 tx = tx2;
    3140         972 :                 nFeeRet = nFeeRet2;
    3141         972 :                 nChangePosInOut = nChangePosInOut2;
    3142         972 :             }
    3143        1284 :         }
    3144        1287 :     }
    3145             :     return res;
    3146        1353 : }
    3147             : 
    3148        1184 : void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
    3149             : {
    3150        1184 :     LOCK(cs_wallet);
    3151        1184 :     WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); /* Continued */
    3152             : 
    3153             :     // Add tx to wallet, because if it has change it's also ours,
    3154             :     // otherwise just for transaction history.
    3155        2368 :     AddToWallet(tx, {}, [&](CWalletTx& wtx, bool new_tx) {
    3156        1184 :         CHECK_NONFATAL(wtx.mapValue.empty());
    3157        1184 :         CHECK_NONFATAL(wtx.vOrderForm.empty());
    3158        1184 :         wtx.mapValue = std::move(mapValue);
    3159        1184 :         wtx.vOrderForm = std::move(orderForm);
    3160        1184 :         wtx.fTimeReceivedIsTxTime = true;
    3161        1184 :         wtx.fFromMe = true;
    3162        1184 :         return true;
    3163           0 :     });
    3164             : 
    3165             :     // Notify that old coins are spent
    3166        4683 :     for (const CTxIn& txin : tx->vin) {
    3167        3499 :         CWalletTx &coin = mapWallet.at(txin.prevout.hash);
    3168        3499 :         coin.MarkDirty();
    3169        3499 :         NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
    3170             :     }
    3171             : 
    3172             :     // Get the inserted-CWalletTx from mapWallet so that the
    3173             :     // fInMempool flag is cached properly
    3174        1184 :     CWalletTx& wtx = mapWallet.at(tx->GetHash());
    3175             : 
    3176        1184 :     if (!fBroadcastTransactions) {
    3177             :         // Don't submit tx to the mempool
    3178           5 :         return;
    3179             :     }
    3180             : 
    3181        1179 :     std::string err_string;
    3182        1179 :     if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
    3183           4 :         WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
    3184             :         // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
    3185           4 :     }
    3186        1184 : }
    3187             : 
    3188         751 : DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
    3189             : {
    3190         751 :     LOCK(cs_wallet);
    3191             : 
    3192         751 :     fFirstRunRet = false;
    3193         757 :     DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this);
    3194         745 :     if (nLoadWalletRet == DBErrors::NEED_REWRITE)
    3195             :     {
    3196           0 :         if (database->Rewrite("\x04pool"))
    3197             :         {
    3198           0 :             for (const auto& spk_man_pair : m_spk_managers) {
    3199           0 :                 spk_man_pair.second->RewriteDB();
    3200           0 :             }
    3201           0 :         }
    3202             :     }
    3203             : 
    3204             :     // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
    3205         745 :     fFirstRunRet = m_spk_managers.empty() && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
    3206         745 :     if (fFirstRunRet) {
    3207         432 :         assert(m_external_spk_managers.empty());
    3208         432 :         assert(m_internal_spk_managers.empty());
    3209             :     }
    3210             : 
    3211         745 :     if (nLoadWalletRet != DBErrors::LOAD_OK)
    3212           0 :         return nLoadWalletRet;
    3213             : 
    3214         745 :     return DBErrors::LOAD_OK;
    3215         751 : }
    3216             : 
    3217           4 : DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
    3218             : {
    3219           4 :     AssertLockHeld(cs_wallet);
    3220           4 :     DBErrors nZapSelectTxRet = WalletBatch(*database, "cr+").ZapSelectTx(vHashIn, vHashOut);
    3221           7 :     for (const uint256& hash : vHashOut) {
    3222           3 :         const auto& it = mapWallet.find(hash);
    3223           3 :         wtxOrdered.erase(it->second.m_it_wtxOrdered);
    3224           6 :         for (const auto& txin : it->second.tx->vin)
    3225           3 :             mapTxSpends.erase(txin.prevout);
    3226           3 :         mapWallet.erase(it);
    3227           3 :         NotifyTransactionChanged(this, hash, CT_DELETED);
    3228           3 :     }
    3229             : 
    3230           4 :     if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
    3231             :     {
    3232           0 :         if (database->Rewrite("\x04pool"))
    3233             :         {
    3234           0 :             for (const auto& spk_man_pair : m_spk_managers) {
    3235           0 :                 spk_man_pair.second->RewriteDB();
    3236             :             }
    3237           0 :         }
    3238             :     }
    3239             : 
    3240           4 :     if (nZapSelectTxRet != DBErrors::LOAD_OK)
    3241           0 :         return nZapSelectTxRet;
    3242             : 
    3243           4 :     MarkDirty();
    3244             : 
    3245           4 :     return DBErrors::LOAD_OK;
    3246           4 : }
    3247             : 
    3248       10186 : bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
    3249             : {
    3250             :     bool fUpdated = false;
    3251             :     bool is_mine;
    3252             :     {
    3253       10186 :         LOCK(cs_wallet);
    3254       10186 :         std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
    3255       10186 :         fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
    3256       10186 :         m_address_book[address].SetLabel(strName);
    3257       10186 :         if (!strPurpose.empty()) /* update purpose only if requested */
    3258       10186 :             m_address_book[address].purpose = strPurpose;
    3259       10186 :         is_mine = IsMine(address) != ISMINE_NO;
    3260       10186 :     }
    3261       20372 :     NotifyAddressBookChanged(this, address, strName, is_mine,
    3262       10186 :                              strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
    3263       10186 :     if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
    3264           0 :         return false;
    3265       10186 :     return batch.WriteName(EncodeDestination(address), strName);
    3266       10186 : }
    3267             : 
    3268        9812 : bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
    3269             : {
    3270        9812 :     WalletBatch batch(*database);
    3271        9812 :     return SetAddressBookWithDB(batch, address, strName, strPurpose);
    3272        9812 : }
    3273             : 
    3274           0 : bool CWallet::DelAddressBook(const CTxDestination& address)
    3275             : {
    3276             :     bool is_mine;
    3277           0 :     WalletBatch batch(*database);
    3278             :     {
    3279           0 :         LOCK(cs_wallet);
    3280             :         // 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)
    3281             :         // NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
    3282             :         // When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
    3283           0 :         if (IsMine(address)) {
    3284           0 :             WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
    3285           0 :             return false;
    3286             :         }
    3287             :         // Delete destdata tuples associated with address
    3288           0 :         std::string strAddress = EncodeDestination(address);
    3289           0 :         for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
    3290             :         {
    3291           0 :             batch.EraseDestData(strAddress, item.first);
    3292           0 :         }
    3293           0 :         m_address_book.erase(address);
    3294           0 :         is_mine = IsMine(address) != ISMINE_NO;
    3295           0 :     }
    3296             : 
    3297           0 :     NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
    3298             : 
    3299           0 :     batch.ErasePurpose(EncodeDestination(address));
    3300           0 :     return batch.EraseName(EncodeDestination(address));
    3301           0 : }
    3302             : 
    3303        1068 : size_t CWallet::KeypoolCountExternalKeys() const
    3304             : {
    3305        1068 :     AssertLockHeld(cs_wallet);
    3306             : 
    3307             :     unsigned int count = 0;
    3308        2454 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    3309        1386 :         count += spk_man->KeypoolCountExternalKeys();
    3310           0 :     }
    3311             : 
    3312        1068 :     return count;
    3313           0 : }
    3314             : 
    3315        1811 : unsigned int CWallet::GetKeyPoolSize() const
    3316             : {
    3317        1811 :     AssertLockHeld(cs_wallet);
    3318             : 
    3319             :     unsigned int count = 0;
    3320        4192 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    3321        2381 :         count += spk_man->GetKeyPoolSize();
    3322           0 :     }
    3323        1811 :     return count;
    3324           0 : }
    3325             : 
    3326         782 : bool CWallet::TopUpKeyPool(unsigned int kpSize)
    3327             : {
    3328         782 :     LOCK(cs_wallet);
    3329             :     bool res = true;
    3330        1876 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    3331        1094 :         res &= spk_man->TopUp(kpSize);
    3332           0 :     }
    3333         782 :     return res;
    3334         782 : }
    3335             : 
    3336        8642 : bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
    3337             : {
    3338        8642 :     LOCK(cs_wallet);
    3339        8642 :     error.clear();
    3340             :     bool result = false;
    3341        8642 :     auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
    3342        8642 :     if (spk_man) {
    3343        8642 :         spk_man->TopUp();
    3344        8642 :         result = spk_man->GetNewDestination(type, dest, error);
    3345        8642 :     } else {
    3346           0 :         error = strprintf("Error: No %s addresses available.", FormatOutputType(type));
    3347             :     }
    3348        8642 :     if (result) {
    3349        8634 :         SetAddressBook(dest, label, "receive");
    3350        8634 :     }
    3351             : 
    3352             :     return result;
    3353        8642 : }
    3354             : 
    3355          67 : bool CWallet::GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error)
    3356             : {
    3357          67 :     LOCK(cs_wallet);
    3358          67 :     error.clear();
    3359             : 
    3360          67 :     ReserveDestination reservedest(this, type);
    3361          67 :     if (!reservedest.GetReservedDestination(dest, true)) {
    3362           2 :         error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
    3363           2 :         return false;
    3364             :     }
    3365             : 
    3366          65 :     reservedest.KeepDestination();
    3367          65 :     return true;
    3368          67 : }
    3369             : 
    3370        1068 : int64_t CWallet::GetOldestKeyPoolTime() const
    3371             : {
    3372        1068 :     LOCK(cs_wallet);
    3373        1068 :     int64_t oldestKey = std::numeric_limits<int64_t>::max();
    3374        2694 :     for (const auto& spk_man_pair : m_spk_managers) {
    3375        1626 :         oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
    3376           0 :     }
    3377        1068 :     return oldestKey;
    3378        1068 : }
    3379             : 
    3380         291 : void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
    3381       25356 :     for (auto& entry : mapWallet) {
    3382       25065 :         CWalletTx& wtx = entry.second;
    3383       25065 :         if (wtx.m_is_cache_empty) continue;
    3384       58854 :         for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
    3385       38739 :             CTxDestination dst;
    3386       38739 :             if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
    3387         221 :                 wtx.MarkDirty();
    3388         221 :                 break;
    3389             :             }
    3390       38739 :         }
    3391       40672 :     }
    3392         291 : }
    3393             : 
    3394           4 : std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() const
    3395             : {
    3396           4 :     std::map<CTxDestination, CAmount> balances;
    3397             : 
    3398             :     {
    3399           4 :         LOCK(cs_wallet);
    3400           4 :         std::set<uint256> trusted_parents;
    3401         414 :         for (const auto& walletEntry : mapWallet)
    3402             :         {
    3403         410 :             const CWalletTx& wtx = walletEntry.second;
    3404             : 
    3405         410 :             if (!IsTrusted(wtx, trusted_parents))
    3406           0 :                 continue;
    3407             : 
    3408         410 :             if (wtx.IsImmatureCoinBase())
    3409         400 :                 continue;
    3410             : 
    3411          10 :             int nDepth = wtx.GetDepthInMainChain();
    3412          10 :             if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
    3413           0 :                 continue;
    3414             : 
    3415          28 :             for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
    3416             :             {
    3417          18 :                 CTxDestination addr;
    3418          18 :                 if (!IsMine(wtx.tx->vout[i]))
    3419          10 :                     continue;
    3420           8 :                 if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
    3421           0 :                     continue;
    3422             : 
    3423           8 :                 CAmount n = IsSpent(walletEntry.first, i) ? 0 : wtx.tx->vout[i].nValue;
    3424           8 :                 balances[addr] += n;
    3425          18 :             }
    3426          20 :         }
    3427           4 :     }
    3428             : 
    3429             :     return balances;
    3430           4 : }
    3431             : 
    3432           4 : std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() const
    3433             : {
    3434           4 :     AssertLockHeld(cs_wallet);
    3435           4 :     std::set< std::set<CTxDestination> > groupings;
    3436           4 :     std::set<CTxDestination> grouping;
    3437             : 
    3438         414 :     for (const auto& walletEntry : mapWallet)
    3439             :     {
    3440         410 :         const CWalletTx& wtx = walletEntry.second;
    3441             : 
    3442         410 :         if (wtx.tx->vin.size() > 0)
    3443             :         {
    3444             :             bool any_mine = false;
    3445             :             // group all input addresses with each other
    3446         822 :             for (const CTxIn& txin : wtx.tx->vin)
    3447             :             {
    3448         412 :                 CTxDestination address;
    3449         412 :                 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
    3450         408 :                     continue;
    3451           4 :                 if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
    3452           0 :                     continue;
    3453           4 :                 grouping.insert(address);
    3454             :                 any_mine = true;
    3455         412 :             }
    3456             : 
    3457             :             // group change with input addresses
    3458         410 :             if (any_mine)
    3459             :             {
    3460           4 :                for (const CTxOut& txout : wtx.tx->vout)
    3461           2 :                    if (IsChange(txout))
    3462             :                    {
    3463           0 :                        CTxDestination txoutAddr;
    3464           0 :                        if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
    3465           0 :                            continue;
    3466           0 :                        grouping.insert(txoutAddr);
    3467           2 :                    }
    3468           2 :             }
    3469         410 :             if (grouping.size() > 0)
    3470             :             {
    3471           2 :                 groupings.insert(grouping);
    3472           2 :                 grouping.clear();
    3473           2 :             }
    3474         410 :         }
    3475             : 
    3476             :         // group lone addrs by themselves
    3477        1228 :         for (const auto& txout : wtx.tx->vout)
    3478         818 :             if (IsMine(txout))
    3479             :             {
    3480         408 :                 CTxDestination address;
    3481         408 :                 if(!ExtractDestination(txout.scriptPubKey, address))
    3482           0 :                     continue;
    3483         408 :                 grouping.insert(address);
    3484         408 :                 groupings.insert(grouping);
    3485         408 :                 grouping.clear();
    3486         818 :             }
    3487           0 :     }
    3488             : 
    3489           4 :     std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
    3490           4 :     std::map< CTxDestination, std::set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
    3491          14 :     for (std::set<CTxDestination> _grouping : groupings)
    3492             :     {
    3493             :         // make a set of all the groups hit by this new group
    3494          10 :         std::set< std::set<CTxDestination>* > hits;
    3495          10 :         std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
    3496          22 :         for (const CTxDestination& address : _grouping)
    3497          12 :             if ((it = setmap.find(address)) != setmap.end())
    3498           4 :                 hits.insert((*it).second);
    3499             : 
    3500             :         // merge all hit groups into a new single group and delete old groups
    3501          10 :         std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
    3502          14 :         for (std::set<CTxDestination>* hit : hits)
    3503             :         {
    3504           4 :             merged->insert(hit->begin(), hit->end());
    3505           4 :             uniqueGroupings.erase(hit);
    3506           4 :             delete hit;
    3507           4 :         }
    3508          10 :         uniqueGroupings.insert(merged);
    3509             : 
    3510             :         // update setmap
    3511          24 :         for (const CTxDestination& element : *merged)
    3512          14 :             setmap[element] = merged;
    3513          10 :     }
    3514             : 
    3515           4 :     std::set< std::set<CTxDestination> > ret;
    3516          10 :     for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
    3517             :     {
    3518           6 :         ret.insert(*uniqueGrouping);
    3519           6 :         delete uniqueGrouping;
    3520           0 :     }
    3521             : 
    3522             :     return ret;
    3523           4 : }
    3524             : 
    3525          30 : std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
    3526             : {
    3527          30 :     LOCK(cs_wallet);
    3528          30 :     std::set<CTxDestination> result;
    3529         285 :     for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
    3530             :     {
    3531         255 :         if (item.second.IsChange()) continue;
    3532         255 :         const CTxDestination& address = item.first;
    3533         255 :         const std::string& strName = item.second.GetLabel();
    3534         255 :         if (strName == label)
    3535          52 :             result.insert(address);
    3536         255 :     }
    3537             :     return result;
    3538          30 : }
    3539             : 
    3540        2498 : bool ReserveDestination::GetReservedDestination(CTxDestination& dest, bool internal)
    3541             : {
    3542        2498 :     m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
    3543        2498 :     if (!m_spk_man) {
    3544          11 :         return false;
    3545             :     }
    3546             : 
    3547             : 
    3548        2487 :     if (nIndex == -1)
    3549             :     {
    3550        2487 :         m_spk_man->TopUp();
    3551             : 
    3552        2487 :         CKeyPool keypool;
    3553        2487 :         if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
    3554          17 :             return false;
    3555             :         }
    3556        2470 :         fInternal = keypool.fInternal;
    3557        2487 :     }
    3558        2470 :     dest = address;
    3559        2470 :     return true;
    3560        2498 : }
    3561             : 
    3562        2659 : void ReserveDestination::KeepDestination()
    3563             : {
    3564        2659 :     if (nIndex != -1) {
    3565        2433 :         m_spk_man->KeepDestination(nIndex, type);
    3566        2433 :     }
    3567        2659 :     nIndex = -1;
    3568        2659 :     address = CNoDestination();
    3569        2659 : }
    3570             : 
    3571        2707 : void ReserveDestination::ReturnDestination()
    3572             : {
    3573        2707 :     if (nIndex != -1) {
    3574          38 :         m_spk_man->ReturnDestination(nIndex, fInternal, address);
    3575          38 :     }
    3576        2707 :     nIndex = -1;
    3577        2707 :     address = CNoDestination();
    3578        2707 : }
    3579             : 
    3580          14 : void CWallet::LockCoin(const COutPoint& output)
    3581             : {
    3582          14 :     AssertLockHeld(cs_wallet);
    3583          14 :     setLockedCoins.insert(output);
    3584          14 : }
    3585             : 
    3586           4 : void CWallet::UnlockCoin(const COutPoint& output)
    3587             : {
    3588           4 :     AssertLockHeld(cs_wallet);
    3589           4 :     setLockedCoins.erase(output);
    3590           4 : }
    3591             : 
    3592           0 : void CWallet::UnlockAllCoins()
    3593             : {
    3594           0 :     AssertLockHeld(cs_wallet);
    3595           0 :     setLockedCoins.clear();
    3596           0 : }
    3597             : 
    3598      767327 : bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
    3599             : {
    3600      767327 :     AssertLockHeld(cs_wallet);
    3601      767327 :     COutPoint outpt(hash, n);
    3602             : 
    3603     1534654 :     return (setLockedCoins.count(outpt) > 0);
    3604      767327 : }
    3605             : 
    3606          18 : void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
    3607             : {
    3608          18 :     AssertLockHeld(cs_wallet);
    3609          27 :     for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
    3610          27 :          it != setLockedCoins.end(); it++) {
    3611           9 :         COutPoint outpt = (*it);
    3612           9 :         vOutpts.push_back(outpt);
    3613           9 :     }
    3614          18 : }
    3615             : 
    3616             : /** @} */ // end of Actions
    3617             : 
    3618           6 : void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
    3619           6 :     AssertLockHeld(cs_wallet);
    3620           6 :     mapKeyBirth.clear();
    3621             : 
    3622           6 :     LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
    3623           6 :     assert(spk_man != nullptr);
    3624           6 :     LOCK(spk_man->cs_KeyStore);
    3625             : 
    3626             :     // get birth times for keys with metadata
    3627        1256 :     for (const auto& entry : spk_man->mapKeyMetadata) {
    3628        1250 :         if (entry.second.nCreateTime) {
    3629        1250 :             mapKeyBirth[entry.first] = entry.second.nCreateTime;
    3630        1250 :         }
    3631           0 :     }
    3632             : 
    3633             :     // map in which we'll infer heights of other keys
    3634           6 :     std::map<CKeyID, const CWalletTx::Confirmation*> mapKeyFirstBlock;
    3635           6 :     CWalletTx::Confirmation max_confirm;
    3636           6 :     max_confirm.block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
    3637           6 :     CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.block_height, FoundBlock().hash(max_confirm.hashBlock)));
    3638        1256 :     for (const CKeyID &keyid : spk_man->GetKeys()) {
    3639        1250 :         if (mapKeyBirth.count(keyid) == 0)
    3640           0 :             mapKeyFirstBlock[keyid] = &max_confirm;
    3641           0 :     }
    3642             : 
    3643             :     // if there are no such keys, we're done
    3644           6 :     if (mapKeyFirstBlock.empty())
    3645           6 :         return;
    3646             : 
    3647             :     // find first block that affects those keys, if there are any left
    3648           0 :     for (const auto& entry : mapWallet) {
    3649             :         // iterate over all wallet transactions...
    3650           0 :         const CWalletTx &wtx = entry.second;
    3651           0 :         if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
    3652             :             // ... which are already in a block
    3653           0 :             for (const CTxOut &txout : wtx.tx->vout) {
    3654             :                 // iterate over all their outputs
    3655           0 :                 for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
    3656             :                     // ... and all their affected keys
    3657           0 :                     auto rit = mapKeyFirstBlock.find(keyid);
    3658           0 :                     if (rit != mapKeyFirstBlock.end() && wtx.m_confirm.block_height < rit->second->block_height) {
    3659           0 :                         rit->second = &wtx.m_confirm;
    3660           0 :                     }
    3661           0 :                 }
    3662             :             }
    3663           0 :         }
    3664           0 :     }
    3665             : 
    3666             :     // Extract block timestamps for those keys
    3667           0 :     for (const auto& entry : mapKeyFirstBlock) {
    3668           0 :         int64_t block_time;
    3669           0 :         CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock, FoundBlock().time(block_time)));
    3670           0 :         mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
    3671           0 :     }
    3672           6 : }
    3673             : 
    3674             : /**
    3675             :  * Compute smart timestamp for a transaction being added to the wallet.
    3676             :  *
    3677             :  * Logic:
    3678             :  * - If sending a transaction, assign its timestamp to the current time.
    3679             :  * - If receiving a transaction outside a block, assign its timestamp to the
    3680             :  *   current time.
    3681             :  * - If receiving a block with a future timestamp, assign all its (not already
    3682             :  *   known) transactions' timestamps to the current time.
    3683             :  * - If receiving a block with a past timestamp, before the most recent known
    3684             :  *   transaction (that we care about), assign all its (not already known)
    3685             :  *   transactions' timestamps to the same timestamp as that most-recent-known
    3686             :  *   transaction.
    3687             :  * - If receiving a block with a past timestamp, but after the most recent known
    3688             :  *   transaction, assign all its (not already known) transactions' timestamps to
    3689             :  *   the block time.
    3690             :  *
    3691             :  * For more information see CWalletTx::nTimeSmart,
    3692             :  * https://bitcointalk.org/?topic=54527, or
    3693             :  * https://github.com/bitcoin/bitcoin/pull/1393.
    3694             :  */
    3695      136216 : unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
    3696             : {
    3697      136216 :     unsigned int nTimeSmart = wtx.nTimeReceived;
    3698      136216 :     if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
    3699       23826 :         int64_t blocktime;
    3700       23826 :         if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
    3701       23826 :             int64_t latestNow = wtx.nTimeReceived;
    3702       23826 :             int64_t latestEntry = 0;
    3703             : 
    3704             :             // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
    3705       23826 :             int64_t latestTolerated = latestNow + 300;
    3706       23826 :             const TxItems& txOrdered = wtxOrdered;
    3707       71297 :             for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
    3708       47471 :                 CWalletTx* const pwtx = it->second;
    3709       47471 :                 if (pwtx == &wtx) {
    3710       23826 :                     continue;
    3711             :                 }
    3712             :                 int64_t nSmartTime;
    3713       23645 :                 nSmartTime = pwtx->nTimeSmart;
    3714       23645 :                 if (!nSmartTime) {
    3715           0 :                     nSmartTime = pwtx->nTimeReceived;
    3716           0 :                 }
    3717       23645 :                 if (nSmartTime <= latestTolerated) {
    3718       23548 :                     latestEntry = nSmartTime;
    3719       23548 :                     if (nSmartTime > latestNow) {
    3720           1 :                         latestNow = nSmartTime;
    3721           1 :                     }
    3722       23548 :                     break;
    3723             :                 }
    3724          97 :             }
    3725             : 
    3726       23826 :             nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
    3727       23826 :         } else {
    3728           0 :             WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
    3729             :         }
    3730       23826 :     }
    3731      136216 :     return nTimeSmart;
    3732           0 : }
    3733             : 
    3734          46 : bool CWallet::AddDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key, const std::string &value)
    3735             : {
    3736          46 :     if (boost::get<CNoDestination>(&dest))
    3737           0 :         return false;
    3738             : 
    3739          46 :     m_address_book[dest].destdata.insert(std::make_pair(key, value));
    3740          46 :     return batch.WriteDestData(EncodeDestination(dest), key, value);
    3741          46 : }
    3742             : 
    3743           0 : bool CWallet::EraseDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key)
    3744             : {
    3745           0 :     if (!m_address_book[dest].destdata.erase(key))
    3746           0 :         return false;
    3747           0 :     return batch.EraseDestData(EncodeDestination(dest), key);
    3748           0 : }
    3749             : 
    3750           0 : void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
    3751             : {
    3752           0 :     m_address_book[dest].destdata.insert(std::make_pair(key, value));
    3753           0 : }
    3754             : 
    3755        1907 : bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
    3756             : {
    3757        1907 :     std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
    3758        1907 :     if(i != m_address_book.end())
    3759             :     {
    3760        1225 :         CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
    3761        1225 :         if(j != i->second.destdata.end())
    3762             :         {
    3763         621 :             if(value)
    3764           0 :                 *value = j->second;
    3765         621 :             return true;
    3766             :         }
    3767        1225 :     }
    3768        1286 :     return false;
    3769        1907 : }
    3770             : 
    3771           1 : std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
    3772             : {
    3773           1 :     std::vector<std::string> values;
    3774           2 :     for (const auto& address : m_address_book) {
    3775           4 :         for (const auto& data : address.second.destdata) {
    3776           3 :             if (!data.first.compare(0, prefix.size(), prefix)) {
    3777           2 :                 values.emplace_back(data.second);
    3778             :             }
    3779           0 :         }
    3780           0 :     }
    3781             :     return values;
    3782           1 : }
    3783             : 
    3784        1022 : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
    3785             : {
    3786             :     // Do some checking on wallet path. It should be either a:
    3787             :     //
    3788             :     // 1. Path where a directory can be created.
    3789             :     // 2. Path to an existing directory.
    3790             :     // 3. Path to a symlink to a directory.
    3791             :     // 4. For backwards compatibility, the name of a data file in -walletdir.
    3792        1022 :     const fs::path& wallet_path = fs::absolute(name, GetWalletDir());
    3793        1022 :     fs::file_type path_type = fs::symlink_status(wallet_path).type();
    3794        1073 :     if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
    3795          51 :           (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
    3796          35 :           (path_type == fs::regular_file && fs::path(name).filename() == name))) {
    3797           4 :         error_string = Untranslated(strprintf(
    3798             :               "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
    3799             :               "database/log.?????????? files can be stored, a location where such a directory could be created, "
    3800             :               "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
    3801           4 :               name, GetWalletDir()));
    3802           4 :         status = DatabaseStatus::FAILED_BAD_PATH;
    3803           4 :         return nullptr;
    3804             :     }
    3805        1018 :     return MakeDatabase(wallet_path, options, status, error_string);
    3806        1022 : }
    3807             : 
    3808         733 : 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)
    3809             : {
    3810         733 :     const std::string& walletFile = database->Filename();
    3811             : 
    3812         733 :     chain.initMessage(_("Loading wallet...").translated);
    3813             : 
    3814         733 :     int64_t nStart = GetTimeMillis();
    3815         733 :     bool fFirstRun = true;
    3816             :     // TODO: Can't use std::make_shared because we need a custom deleter but
    3817             :     // should be possible to use std::allocate_shared.
    3818         733 :     std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, name, std::move(database)), ReleaseWallet);
    3819         733 :     DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
    3820         727 :     if (nLoadWalletRet != DBErrors::LOAD_OK) {
    3821           0 :         if (nLoadWalletRet == DBErrors::CORRUPT) {
    3822           0 :             error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
    3823           0 :             return nullptr;
    3824             :         }
    3825           0 :         else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
    3826             :         {
    3827           0 :             warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
    3828             :                                            " or address book entries might be missing or incorrect."),
    3829             :                 walletFile));
    3830             :         }
    3831           0 :         else if (nLoadWalletRet == DBErrors::TOO_NEW) {
    3832           0 :             error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
    3833           0 :             return nullptr;
    3834             :         }
    3835           0 :         else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
    3836             :         {
    3837           0 :             error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
    3838           0 :             return nullptr;
    3839             :         }
    3840             :         else {
    3841           0 :             error = strprintf(_("Error loading %s"), walletFile);
    3842           0 :             return nullptr;
    3843             :         }
    3844           0 :     }
    3845             : 
    3846         727 :     if (fFirstRun)
    3847             :     {
    3848             :         // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
    3849         420 :         walletInstance->SetMinVersion(FEATURE_LATEST);
    3850             : 
    3851         420 :         walletInstance->AddWalletFlags(wallet_creation_flags);
    3852             : 
    3853             :         // Only create LegacyScriptPubKeyMan when not descriptor wallet
    3854         420 :         if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    3855         377 :             walletInstance->SetupLegacyScriptPubKeyMan();
    3856             :         }
    3857             : 
    3858         420 :         if (!(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
    3859         373 :             LOCK(walletInstance->cs_wallet);
    3860         373 :             if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    3861          30 :                 walletInstance->SetupDescriptorScriptPubKeyMans();
    3862             :                 // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
    3863             :             } else {
    3864             :                 // Legacy wallets need SetupGeneration here.
    3865         686 :                 for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
    3866         343 :                     if (!spk_man->SetupGeneration()) {
    3867           0 :                         error = _("Unable to generate initial keys");
    3868           0 :                         return nullptr;
    3869             :                     }
    3870         343 :                 }
    3871             :             }
    3872         373 :         }
    3873             : 
    3874         420 :         walletInstance->chainStateFlushed(chain.getTipLocator());
    3875         727 :     } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
    3876             :         // Make it impossible to disable private keys after creation
    3877           0 :         error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
    3878           0 :         return NULL;
    3879         307 :     } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
    3880          37 :         for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
    3881          13 :             if (spk_man->HavePrivateKeys()) {
    3882           0 :                 warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
    3883           0 :                 break;
    3884             :             }
    3885          13 :         }
    3886          24 :     }
    3887             : 
    3888         727 :     if (!gArgs.GetArg("-addresstype", "").empty()) {
    3889          47 :         if (!ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
    3890           0 :             error = strprintf(_("Unknown address type '%s'"), gArgs.GetArg("-addresstype", ""));
    3891           0 :             return nullptr;
    3892             :         }
    3893             :     }
    3894             : 
    3895         727 :     if (!gArgs.GetArg("-changetype", "").empty()) {
    3896           2 :         OutputType out_type;
    3897           2 :         if (!ParseOutputType(gArgs.GetArg("-changetype", ""), out_type)) {
    3898           0 :             error = strprintf(_("Unknown change type '%s'"), gArgs.GetArg("-changetype", ""));
    3899           0 :             return nullptr;
    3900             :         }
    3901           2 :         walletInstance->m_default_change_type = out_type;
    3902           2 :     }
    3903             : 
    3904         727 :     if (gArgs.IsArgSet("-mintxfee")) {
    3905          12 :         CAmount n = 0;
    3906          12 :         if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
    3907           0 :             error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
    3908           0 :             return nullptr;
    3909             :         }
    3910          12 :         if (n > HIGH_TX_FEE_PER_KB) {
    3911           0 :             warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
    3912           0 :                                _("This is the minimum transaction fee you pay on every transaction."));
    3913           0 :         }
    3914          12 :         walletInstance->m_min_fee = CFeeRate(n);
    3915          12 :     }
    3916             : 
    3917         727 :     if (gArgs.IsArgSet("-maxapsfee")) {
    3918           2 :         const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
    3919           2 :         CAmount n = 0;
    3920           2 :         if (max_aps_fee == "-1") {
    3921           0 :             n = -1;
    3922           2 :         } else if (!ParseMoney(max_aps_fee, n)) {
    3923           0 :             error = AmountErrMsg("maxapsfee", max_aps_fee);
    3924           0 :             return nullptr;
    3925             :         }
    3926           2 :         if (n > HIGH_APS_FEE) {
    3927           0 :             warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
    3928           0 :                               _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
    3929           0 :         }
    3930           2 :         walletInstance->m_max_aps_fee = n;
    3931           2 :     }
    3932             : 
    3933         727 :     if (gArgs.IsArgSet("-fallbackfee")) {
    3934         723 :         CAmount nFeePerK = 0;
    3935         723 :         if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
    3936           0 :             error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""));
    3937           0 :             return nullptr;
    3938             :         }
    3939         723 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
    3940           0 :             warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
    3941           0 :                                _("This is the transaction fee you may pay when fee estimates are not available."));
    3942           0 :         }
    3943         723 :         walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
    3944         723 :     }
    3945             :     // Disable fallback fee in case value was set to 0, enable if non-null value
    3946         727 :     walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
    3947             : 
    3948         727 :     if (gArgs.IsArgSet("-discardfee")) {
    3949           0 :         CAmount nFeePerK = 0;
    3950           0 :         if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
    3951           0 :             error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""));
    3952           0 :             return nullptr;
    3953             :         }
    3954           0 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
    3955           0 :             warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
    3956           0 :                                _("This is the transaction fee you may discard if change is smaller than dust at this level"));
    3957           0 :         }
    3958           0 :         walletInstance->m_discard_rate = CFeeRate(nFeePerK);
    3959           0 :     }
    3960         727 :     if (gArgs.IsArgSet("-paytxfee")) {
    3961           1 :         CAmount nFeePerK = 0;
    3962           1 :         if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
    3963           0 :             error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
    3964           0 :             return nullptr;
    3965             :         }
    3966           1 :         if (nFeePerK > HIGH_TX_FEE_PER_KB) {
    3967           0 :             warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
    3968           0 :                                _("This is the transaction fee you will pay if you send a transaction."));
    3969           0 :         }
    3970           1 :         walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
    3971           1 :         if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
    3972           0 :             error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
    3973           0 :                 gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString());
    3974           0 :             return nullptr;
    3975             :         }
    3976           1 :     }
    3977             : 
    3978         727 :     if (gArgs.IsArgSet("-maxtxfee")) {
    3979           2 :         CAmount nMaxFee = 0;
    3980           2 :         if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
    3981           0 :             error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
    3982           0 :             return nullptr;
    3983             :         }
    3984           2 :         if (nMaxFee > HIGH_MAX_TX_FEE) {
    3985           0 :             warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
    3986           0 :         }
    3987           2 :         if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
    3988           0 :             error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
    3989           0 :                 gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
    3990           0 :             return nullptr;
    3991             :         }
    3992           2 :         walletInstance->m_default_max_tx_fee = nMaxFee;
    3993           2 :     }
    3994             : 
    3995         727 :     if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
    3996           0 :         warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
    3997           0 :                            _("The wallet will avoid paying less than the minimum relay fee."));
    3998           0 :     }
    3999             : 
    4000         727 :     walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
    4001         727 :     walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
    4002         727 :     walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
    4003             : 
    4004         727 :     walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
    4005             : 
    4006             :     // Try to top up keypool. No-op if the wallet is locked.
    4007         727 :     walletInstance->TopUpKeyPool();
    4008             : 
    4009         727 :     LOCK(walletInstance->cs_wallet);
    4010             : 
    4011             :     // Register wallet with validationinterface. It's done before rescan to avoid
    4012             :     // missing block connections between end of rescan and validation subscribing.
    4013             :     // Because of wallet lock being hold, block connection notifications are going to
    4014             :     // be pending on the validation-side until lock release. It's likely to have
    4015             :     // block processing duplicata (if rescan block range overlaps with notification one)
    4016             :     // but we guarantee at least than wallet state is correct after notifications delivery.
    4017             :     // This is temporary until rescan and notifications delivery are unified under same
    4018             :     // interface.
    4019         727 :     walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    4020             : 
    4021             :     int rescan_height = 0;
    4022         727 :     if (!gArgs.GetBoolArg("-rescan", false))
    4023             :     {
    4024         717 :         WalletBatch batch(*walletInstance->database);
    4025         717 :         CBlockLocator locator;
    4026         717 :         if (batch.ReadBestBlock(locator)) {
    4027        1399 :             if (const Optional<int> fork_height = chain.findLocatorFork(locator)) {
    4028         683 :                 rescan_height = *fork_height;
    4029         683 :             }
    4030         716 :         }
    4031         717 :     }
    4032             : 
    4033         727 :     const Optional<int> tip_height = chain.getHeight();
    4034         727 :     if (tip_height) {
    4035         694 :         walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
    4036         694 :         walletInstance->m_last_block_processed_height = *tip_height;
    4037         694 :     } else {
    4038          33 :         walletInstance->m_last_block_processed.SetNull();
    4039          33 :         walletInstance->m_last_block_processed_height = -1;
    4040             :     }
    4041             : 
    4042         727 :     if (tip_height && *tip_height != rescan_height)
    4043             :     {
    4044             :         // We can't rescan beyond non-pruned blocks, stop and throw an error.
    4045             :         // This might happen if a user uses an old wallet within a pruned node
    4046             :         // or if they ran -disablewallet for a longer time, then decided to re-enable
    4047          80 :         if (chain.havePruned()) {
    4048             :             // Exit early and print an error.
    4049             :             // If a block is pruned after this check, we will load the wallet,
    4050             :             // but fail the rescan with a generic error.
    4051           0 :             int block_height = *tip_height;
    4052           0 :             while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
    4053           0 :                 --block_height;
    4054             :             }
    4055             : 
    4056           0 :             if (rescan_height != block_height) {
    4057           0 :                 error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
    4058           0 :                 return nullptr;
    4059             :             }
    4060           0 :         }
    4061             : 
    4062          80 :         chain.initMessage(_("Rescanning...").translated);
    4063          80 :         walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
    4064             : 
    4065             :         // No need to read and scan block if block was created before
    4066             :         // our wallet birthday (as adjusted for block time variability)
    4067             :         // The way the 'time_first_key' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
    4068          80 :         Optional<int64_t> time_first_key = MakeOptional(false, int64_t());;
    4069         248 :         for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
    4070         168 :             int64_t time = spk_man->GetTimeFirstKey();
    4071         168 :             if (!time_first_key || time < *time_first_key) time_first_key = time;
    4072         168 :         }
    4073          80 :         if (time_first_key) {
    4074         160 :             if (Optional<int> first_block = chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, nullptr)) {
    4075          80 :                 rescan_height = *first_block;
    4076          80 :             }
    4077          80 :         }
    4078             : 
    4079             :         {
    4080          80 :             WalletRescanReserver reserver(*walletInstance);
    4081          80 :             if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
    4082           0 :                 error = _("Failed to rescan the wallet during initialization");
    4083           0 :                 return nullptr;
    4084             :             }
    4085          80 :         }
    4086          80 :         walletInstance->chainStateFlushed(chain.getTipLocator());
    4087          80 :         walletInstance->database->IncrementUpdateCounter();
    4088          80 :     }
    4089             : 
    4090             :     {
    4091         727 :         LOCK(cs_wallets);
    4092         728 :         for (auto& load_wallet : g_load_wallet_fns) {
    4093           1 :             load_wallet(interfaces::MakeWallet(walletInstance));
    4094           0 :         }
    4095         727 :     }
    4096             : 
    4097         727 :     walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
    4098             : 
    4099             :     {
    4100         727 :         walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n",      walletInstance->GetKeyPoolSize());
    4101         727 :         walletInstance->WalletLogPrintf("mapWallet.size() = %u\n",       walletInstance->mapWallet.size());
    4102         727 :         walletInstance->WalletLogPrintf("m_address_book.size() = %u\n",  walletInstance->m_address_book.size());
    4103             :     }
    4104             : 
    4105         727 :     return walletInstance;
    4106         733 : }
    4107             : 
    4108       54842 : const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
    4109             : {
    4110       54842 :     const auto& address_book_it = m_address_book.find(dest);
    4111       54842 :     if (address_book_it == m_address_book.end()) return nullptr;
    4112       49263 :     if ((!allow_change) && address_book_it->second.IsChange()) {
    4113          16 :         return nullptr;
    4114             :     }
    4115       49247 :     return &address_book_it->second;
    4116       54842 : }
    4117             : 
    4118           2 : bool CWallet::UpgradeWallet(int version, bilingual_str& error, std::vector<bilingual_str>& warnings)
    4119             : {
    4120           2 :     int prev_version = GetVersion();
    4121             :     int nMaxVersion = version;
    4122           2 :     if (nMaxVersion == 0) // the -upgradewallet without argument case
    4123             :     {
    4124           1 :         WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
    4125             :         nMaxVersion = FEATURE_LATEST;
    4126           1 :         SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
    4127           1 :     } else {
    4128           1 :         WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
    4129             :     }
    4130           2 :     if (nMaxVersion < GetVersion())
    4131             :     {
    4132           0 :         error = _("Cannot downgrade wallet");
    4133           0 :         return false;
    4134             :     }
    4135           2 :     SetMaxVersion(nMaxVersion);
    4136             : 
    4137           2 :     LOCK(cs_wallet);
    4138             : 
    4139             :     // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
    4140           2 :     int max_version = GetVersion();
    4141           2 :     if (!CanSupportFeature(FEATURE_HD_SPLIT) && max_version >= FEATURE_HD_SPLIT && max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
    4142           0 :         error = _("Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use version 169900 or no version specified.");
    4143           0 :         return false;
    4144             :     }
    4145             : 
    4146           4 :     for (auto spk_man : GetActiveScriptPubKeyMans()) {
    4147           2 :         if (!spk_man->Upgrade(prev_version, error)) {
    4148           0 :             return false;
    4149             :         }
    4150           2 :     }
    4151           2 :     return true;
    4152           2 : }
    4153             : 
    4154         722 : void CWallet::postInitProcess()
    4155             : {
    4156         722 :     LOCK(cs_wallet);
    4157             : 
    4158             :     // Add wallet transactions that aren't already in a block to mempool
    4159             :     // Do this here as mempool requires genesis block to be loaded
    4160         722 :     ReacceptWalletTransactions();
    4161             : 
    4162             :     // Update wallet transactions with current mempool transactions.
    4163         722 :     chain().requestMempoolTransactions(*this);
    4164         722 : }
    4165             : 
    4166          28 : bool CWallet::BackupWallet(const std::string& strDest) const
    4167             : {
    4168          28 :     return database->Backup(strDest);
    4169             : }
    4170             : 
    4171       39120 : CKeyPool::CKeyPool()
    4172       19560 : {
    4173       19560 :     nTime = GetTime();
    4174       19560 :     fInternal = false;
    4175       19560 :     m_pre_split = false;
    4176       39120 : }
    4177             : 
    4178       49898 : CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
    4179       24949 : {
    4180       24949 :     nTime = GetTime();
    4181       24949 :     vchPubKey = vchPubKeyIn;
    4182       24949 :     fInternal = internalIn;
    4183       24949 :     m_pre_split = false;
    4184       49898 : }
    4185             : 
    4186     2110762 : int CWalletTx::GetDepthInMainChain() const
    4187             : {
    4188     2110762 :     assert(pwallet != nullptr);
    4189     2110762 :     AssertLockHeld(pwallet->cs_wallet);
    4190     2110762 :     if (isUnconfirmed() || isAbandoned()) return 0;
    4191             : 
    4192     2065846 :     return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
    4193     2110762 : }
    4194             : 
    4195      928510 : int CWalletTx::GetBlocksToMaturity() const
    4196             : {
    4197      928510 :     if (!IsCoinBase())
    4198      206566 :         return 0;
    4199      721944 :     int chain_depth = GetDepthInMainChain();
    4200      721944 :     assert(chain_depth >= 0); // coinbase tx should not be conflicted
    4201      721944 :     return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
    4202      928510 : }
    4203             : 
    4204      928510 : bool CWalletTx::IsImmatureCoinBase() const
    4205             : {
    4206             :     // note GetBlocksToMaturity is 0 for non-coinbase tx
    4207      928510 :     return GetBlocksToMaturity() > 0;
    4208             : }
    4209             : 
    4210        5388 : std::vector<OutputGroup> CWallet::GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const {
    4211        5388 :     std::vector<OutputGroup> groups;
    4212        5388 :     std::map<CTxDestination, OutputGroup> gmap;
    4213        5388 :     std::set<CTxDestination> full_groups;
    4214             : 
    4215      432315 :     for (const auto& output : outputs) {
    4216      426927 :         if (output.fSpendable) {
    4217      426805 :             CTxDestination dst;
    4218      426805 :             CInputCoin input_coin = output.GetInputCoin();
    4219             : 
    4220      426805 :             size_t ancestors, descendants;
    4221      426805 :             chain().getTransactionAncestry(output.tx->GetHash(), ancestors, descendants);
    4222      426805 :             if (!single_coin && ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) {
    4223      225689 :                 auto it = gmap.find(dst);
    4224      225689 :                 if (it != gmap.end()) {
    4225             :                     // Limit output groups to no more than OUTPUT_GROUP_MAX_ENTRIES
    4226             :                     // number of entries, to protect against inadvertently creating
    4227             :                     // a too-large transaction when using -avoidpartialspends to
    4228             :                     // prevent breaking consensus or surprising users with a very
    4229             :                     // high amount of fees.
    4230      199425 :                     if (it->second.m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
    4231       17988 :                         groups.push_back(it->second);
    4232       17988 :                         it->second = OutputGroup{};
    4233       17988 :                         full_groups.insert(dst);
    4234       17988 :                     }
    4235      199425 :                     it->second.Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
    4236      199425 :                 } else {
    4237       26264 :                     gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
    4238             :                 }
    4239      225689 :             } else {
    4240      201116 :                 groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
    4241             :             }
    4242      426805 :         }
    4243             :     }
    4244        5388 :     if (!single_coin) {
    4245       28931 :         for (auto& it : gmap) {
    4246       26264 :             auto& group = it.second;
    4247       26264 :             if (full_groups.count(it.first) > 0) {
    4248             :                 // Make this unattractive as we want coin selection to avoid it if possible
    4249        2170 :                 group.m_ancestors = max_ancestors - 1;
    4250        2170 :             }
    4251       26264 :             groups.push_back(group);
    4252           0 :         }
    4253        2667 :     }
    4254             :     return groups;
    4255        5388 : }
    4256             : 
    4257       20316 : bool CWallet::IsCrypted() const
    4258             : {
    4259       20316 :     return HasEncryptionKeys();
    4260             : }
    4261             : 
    4262       18870 : bool CWallet::IsLocked() const
    4263             : {
    4264       18870 :     if (!IsCrypted()) {
    4265       16285 :         return false;
    4266             :     }
    4267        2585 :     LOCK(cs_wallet);
    4268        2585 :     return vMasterKey.empty();
    4269       18870 : }
    4270             : 
    4271          62 : bool CWallet::Lock()
    4272             : {
    4273          62 :     if (!IsCrypted())
    4274           0 :         return false;
    4275             : 
    4276             :     {
    4277          62 :         LOCK(cs_wallet);
    4278          62 :         vMasterKey.clear();
    4279          62 :     }
    4280             : 
    4281          62 :     NotifyStatusChanged(this);
    4282          62 :     return true;
    4283          62 : }
    4284             : 
    4285          64 : bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
    4286             : {
    4287             :     {
    4288          64 :         LOCK(cs_wallet);
    4289         321 :         for (const auto& spk_man_pair : m_spk_managers) {
    4290         257 :             if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
    4291           0 :                 return false;
    4292             :             }
    4293         257 :         }
    4294          64 :         vMasterKey = vMasterKeyIn;
    4295          64 :     }
    4296          64 :     NotifyStatusChanged(this);
    4297          64 :     return true;
    4298          64 : }
    4299             : 
    4300        4860 : std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
    4301             : {
    4302        4860 :     std::set<ScriptPubKeyMan*> spk_mans;
    4303       14580 :     for (bool internal : {false, true}) {
    4304       38880 :         for (OutputType t : OUTPUT_TYPES) {
    4305       29160 :             auto spk_man = GetScriptPubKeyMan(t, internal);
    4306       29160 :             if (spk_man) {
    4307       27692 :                 spk_mans.insert(spk_man);
    4308       27692 :             }
    4309       29160 :         }
    4310             :     }
    4311             :     return spk_mans;
    4312        4860 : }
    4313             : 
    4314        4160 : std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
    4315             : {
    4316        4160 :     std::set<ScriptPubKeyMan*> spk_mans;
    4317       10405 :     for (const auto& spk_man_pair : m_spk_managers) {
    4318        6245 :         spk_mans.insert(spk_man_pair.second.get());
    4319           0 :     }
    4320             :     return spk_mans;
    4321        4160 : }
    4322             : 
    4323       49209 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
    4324             : {
    4325       49209 :     const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
    4326       49209 :     std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
    4327       49209 :     if (it == spk_managers.end()) {
    4328        1580 :         WalletLogPrintf("%s scriptPubKey Manager for output type %d does not exist\n", internal ? "Internal" : "External", static_cast<int>(type));
    4329        1580 :         return nullptr;
    4330             :     }
    4331       47629 :     return it->second;
    4332       49209 : }
    4333             : 
    4334           0 : std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const
    4335             : {
    4336           0 :     std::set<ScriptPubKeyMan*> spk_mans;
    4337           0 :     for (const auto& spk_man_pair : m_spk_managers) {
    4338           0 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
    4339           0 :             spk_mans.insert(spk_man_pair.second.get());
    4340           0 :         }
    4341           0 :     }
    4342             :     return spk_mans;
    4343           0 : }
    4344             : 
    4345         949 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const CScript& script) const
    4346             : {
    4347         949 :     SignatureData sigdata;
    4348        2593 :     for (const auto& spk_man_pair : m_spk_managers) {
    4349        1644 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
    4350         871 :             return spk_man_pair.second.get();
    4351             :         }
    4352         773 :     }
    4353          78 :     return nullptr;
    4354         949 : }
    4355             : 
    4356         384 : ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const uint256& id) const
    4357             : {
    4358         384 :     if (m_spk_managers.count(id) > 0) {
    4359         384 :         return m_spk_managers.at(id).get();
    4360             :     }
    4361           0 :     return nullptr;
    4362         384 : }
    4363             : 
    4364      636935 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
    4365             : {
    4366      636935 :     SignatureData sigdata;
    4367      636935 :     return GetSolvingProvider(script, sigdata);
    4368      636935 : }
    4369             : 
    4370      636935 : std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
    4371             : {
    4372     1332514 :     for (const auto& spk_man_pair : m_spk_managers) {
    4373      695579 :         if (spk_man_pair.second->CanProvide(script, sigdata)) {
    4374      525365 :             return spk_man_pair.second->GetSolvingProvider(script);
    4375             :         }
    4376      170214 :     }
    4377      111570 :     return nullptr;
    4378      636935 : }
    4379             : 
    4380       40051 : LegacyScriptPubKeyMan* CWallet::GetLegacyScriptPubKeyMan() const
    4381             : {
    4382       40051 :     if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    4383         199 :         return nullptr;
    4384             :     }
    4385             :     // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
    4386             :     // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
    4387       39852 :     auto it = m_internal_spk_managers.find(OutputType::LEGACY);
    4388       39852 :     if (it == m_internal_spk_managers.end()) return nullptr;
    4389       39418 :     return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
    4390       40051 : }
    4391             : 
    4392       32583 : LegacyScriptPubKeyMan* CWallet::GetOrCreateLegacyScriptPubKeyMan()
    4393             : {
    4394       32583 :     SetupLegacyScriptPubKeyMan();
    4395       32583 :     return GetLegacyScriptPubKeyMan();
    4396             : }
    4397             : 
    4398       32994 : void CWallet::SetupLegacyScriptPubKeyMan()
    4399             : {
    4400       32994 :     if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    4401             :         return;
    4402             :     }
    4403             : 
    4404         694 :     auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
    4405        2776 :     for (const auto& type : OUTPUT_TYPES) {
    4406        2082 :         m_internal_spk_managers[type] = spk_manager.get();
    4407        2082 :         m_external_spk_managers[type] = spk_manager.get();
    4408             :     }
    4409         694 :     m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
    4410       32994 : }
    4411             : 
    4412        2665 : const CKeyingMaterial& CWallet::GetEncryptionKey() const
    4413             : {
    4414        2665 :     return vMasterKey;
    4415             : }
    4416             : 
    4417     2783241 : bool CWallet::HasEncryptionKeys() const
    4418             : {
    4419     2783241 :     return !mapMasterKeys.empty();
    4420             : }
    4421             : 
    4422         825 : void CWallet::ConnectScriptPubKeyManNotifiers()
    4423             : {
    4424        2028 :     for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
    4425        1203 :         spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
    4426        1203 :         spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
    4427           0 :     }
    4428         825 : }
    4429             : 
    4430         227 : void CWallet::LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc)
    4431             : {
    4432         227 :     auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
    4433         227 :     m_spk_managers[id] = std::move(spk_manager);
    4434         227 : }
    4435             : 
    4436          34 : void CWallet::SetupDescriptorScriptPubKeyMans()
    4437             : {
    4438          34 :     AssertLockHeld(cs_wallet);
    4439             : 
    4440             :     // Make a seed
    4441          34 :     CKey seed_key;
    4442          34 :     seed_key.MakeNewKey(true);
    4443          34 :     CPubKey seed = seed_key.GetPubKey();
    4444          34 :     assert(seed_key.VerifyPubKey(seed));
    4445             : 
    4446             :     // Get the extended key
    4447          34 :     CExtKey master_key;
    4448          34 :     master_key.SetSeed(seed_key.begin(), seed_key.size());
    4449             : 
    4450         102 :     for (bool internal : {false, true}) {
    4451         272 :         for (OutputType t : OUTPUT_TYPES) {
    4452         204 :             auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, internal));
    4453         204 :             if (IsCrypted()) {
    4454          24 :                 if (IsLocked()) {
    4455           0 :                     throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
    4456             :                 }
    4457          24 :                 if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
    4458           0 :                     throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
    4459             :                 }
    4460             :             }
    4461         204 :             spk_manager->SetupDescriptorGeneration(master_key, t);
    4462         204 :             uint256 id = spk_manager->GetID();
    4463         204 :             m_spk_managers[id] = std::move(spk_manager);
    4464         204 :             AddActiveScriptPubKeyMan(id, t, internal);
    4465         204 :         }
    4466             :     }
    4467          34 : }
    4468             : 
    4469         222 : void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
    4470             : {
    4471         222 :     WalletBatch batch(*database);
    4472         222 :     if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
    4473           0 :         throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
    4474             :     }
    4475         222 :     LoadActiveScriptPubKeyMan(id, type, internal);
    4476         222 : }
    4477             : 
    4478         356 : void CWallet::LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
    4479             : {
    4480         356 :     WalletLogPrintf("Setting spkMan to active: id = %s, type = %d, internal = %d\n", id.ToString(), static_cast<int>(type), static_cast<int>(internal));
    4481         356 :     auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
    4482         356 :     auto spk_man = m_spk_managers.at(id).get();
    4483         356 :     spk_man->SetInternal(internal);
    4484         356 :     spk_mans[type] = spk_man;
    4485             : 
    4486         356 :     NotifyCanGetAddressesChanged();
    4487         356 : }
    4488             : 
    4489        1357 : bool CWallet::IsLegacy() const
    4490             : {
    4491        1357 :     if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
    4492         447 :         return false;
    4493             :     }
    4494         910 :     auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
    4495         910 :     return spk_man != nullptr;
    4496        1357 : }
    4497             : 
    4498         184 : DescriptorScriptPubKeyMan* CWallet::GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const
    4499             : {
    4500        1144 :     for (auto& spk_man_pair : m_spk_managers) {
    4501             :         // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
    4502         960 :         DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
    4503         960 :         if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
    4504          26 :             return spk_manager;
    4505             :         }
    4506        1868 :     }
    4507             : 
    4508         158 :     return nullptr;
    4509         184 : }
    4510             : 
    4511          92 : ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label)
    4512             : {
    4513          92 :     if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
    4514           0 :         WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
    4515           0 :         return nullptr;
    4516             :     }
    4517             : 
    4518          92 :     LOCK(cs_wallet);
    4519          92 :     auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
    4520             : 
    4521             :     // If we already have this descriptor, remove it from the maps but add the existing cache to desc
    4522          92 :     auto old_spk_man = GetDescriptorScriptPubKeyMan(desc);
    4523          92 :     if (old_spk_man) {
    4524          13 :         WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
    4525             : 
    4526             :         {
    4527          13 :             LOCK(old_spk_man->cs_desc_man);
    4528          13 :             new_spk_man->SetCache(old_spk_man->GetWalletDescriptor().cache);
    4529          13 :         }
    4530             : 
    4531             :         // Remove from maps of active spkMans
    4532          13 :         auto old_spk_man_id = old_spk_man->GetID();
    4533          39 :         for (bool internal : {false, true}) {
    4534         101 :             for (OutputType t : OUTPUT_TYPES) {
    4535          76 :                 auto active_spk_man = GetScriptPubKeyMan(t, internal);
    4536          76 :                 if (active_spk_man && active_spk_man->GetID() == old_spk_man_id) {
    4537           1 :                     if (internal) {
    4538           0 :                         m_internal_spk_managers.erase(t);
    4539             :                     } else {
    4540           1 :                         m_external_spk_managers.erase(t);
    4541             :                     }
    4542           1 :                     break;
    4543             :                 }
    4544         151 :             }
    4545             :         }
    4546          13 :         m_spk_managers.erase(old_spk_man_id);
    4547          13 :     }
    4548             : 
    4549             :     // Add the private keys to the descriptor
    4550         143 :     for (const auto& entry : signing_provider.keys) {
    4551          51 :         const CKey& key = entry.second;
    4552          51 :         new_spk_man->AddDescriptorKey(key, key.GetPubKey());
    4553           0 :     }
    4554             : 
    4555             :     // Top up key pool, the manager will generate new scriptPubKeys internally
    4556          92 :     new_spk_man->TopUp();
    4557             : 
    4558             :     // Apply the label if necessary
    4559             :     // Note: we disable labels for ranged descriptors
    4560          92 :     if (!desc.descriptor->IsRange()) {
    4561          71 :         auto script_pub_keys = new_spk_man->GetScriptPubKeys();
    4562          71 :         if (script_pub_keys.empty()) {
    4563           0 :             WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
    4564           0 :             return nullptr;
    4565             :         }
    4566             : 
    4567          71 :         CTxDestination dest;
    4568          71 :         if (ExtractDestination(script_pub_keys.at(0), dest)) {
    4569          70 :             SetAddressBook(dest, label, "receive");
    4570          70 :         }
    4571          71 :     }
    4572             : 
    4573             :     // Save the descriptor to memory
    4574          92 :     auto ret = new_spk_man.get();
    4575          92 :     m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
    4576             : 
    4577             :     // Save the descriptor to DB
    4578          92 :     ret->WriteDescriptor();
    4579             : 
    4580          92 :     return ret;
    4581          92 : }

Generated by: LCOV version 1.15