0
0
Fork 0
mirror of https://github.com/bitcoin/bitcoin.git synced 2025-03-05 14:06:27 -05:00

Merge #19980: refactor: Some wallet cleanups

9b74461fa2 refactor: Assert before dereference in CWallet::GetDatabase (João Barbosa)
021feb3187 refactor: Drop redudant CWallet::GetDBHandle (João Barbosa)

Pull request description:

ACKs for top commit:
  achow101:
    Code Review ACK 9b74461fa2
  meshcollider:
    utACK 9b74461fa2
  ryanofsky:
    Code review ACK 9b74461fa2. Changes since last review: rebasing due to conflict, dropping wallet path commit c6a5cd7a64c78b162f545a3467d0fea7dcaadfcc as suggested in discussion, making GetDatabase() const in the earlier commit. Giving more descriptive title like

Tree-SHA512: 68cf3b5e9fe0acb3a5cd081086629989f213f1904cc344e5775767b56759a7d905b1e1c303afbe40f172ff81bf07f3719b59d8f6ec2de3fdd53cd0e2d220fb25
This commit is contained in:
fanquake 2020-12-02 07:42:34 +08:00
commit 80d4231e16
No known key found for this signature in database
GPG key ID: 2EEB9F5CC09526C1
3 changed files with 34 additions and 37 deletions

View file

@ -419,7 +419,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase,
return false; return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey)) if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false; return false;
WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second); WalletBatch(GetDatabase()).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked) if (fWasLocked)
Lock(); Lock();
return true; return true;
@ -432,7 +432,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase,
void CWallet::chainStateFlushed(const CBlockLocator& loc) void CWallet::chainStateFlushed(const CBlockLocator& loc)
{ {
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
batch.WriteBestBlock(loc); batch.WriteBestBlock(loc);
} }
@ -444,7 +444,7 @@ void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in)
nWalletVersion = nVersion; nWalletVersion = nVersion;
{ {
WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database); WalletBatch* batch = batch_in ? batch_in : new WalletBatch(GetDatabase());
if (nWalletVersion > 40000) if (nWalletVersion > 40000)
batch->WriteMinVersion(nWalletVersion); batch->WriteMinVersion(nWalletVersion);
if (!batch_in) if (!batch_in)
@ -484,12 +484,12 @@ bool CWallet::HasWalletSpend(const uint256& txid) const
void CWallet::Flush() void CWallet::Flush()
{ {
database->Flush(); GetDatabase().Flush();
} }
void CWallet::Close() void CWallet::Close()
{ {
database->Close(); GetDatabase().Close();
} }
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range) void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
@ -615,7 +615,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
WalletBatch* encrypted_batch = new WalletBatch(*database); WalletBatch* encrypted_batch = new WalletBatch(GetDatabase());
if (!encrypted_batch->TxnBegin()) { if (!encrypted_batch->TxnBegin()) {
delete encrypted_batch; delete encrypted_batch;
encrypted_batch = nullptr; encrypted_batch = nullptr;
@ -667,12 +667,12 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
// Need to completely rewrite the wallet file; if we don't, bdb might keep // Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file. // bits of the unencrypted private key in slack space in the database file.
database->Rewrite(); GetDatabase().Rewrite();
// BDB seems to have a bad habit of writing old data into // BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is // slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So: // unencrypted private keys. So:
database->ReloadDbEnv(); GetDatabase().ReloadDbEnv();
} }
NotifyStatusChanged(this); NotifyStatusChanged(this);
@ -683,7 +683,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
DBErrors CWallet::ReorderTransactions() DBErrors CWallet::ReorderTransactions()
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
// Old wallets didn't have any defined order for transactions // Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this // Probably a bad idea to change the output of this
@ -744,7 +744,7 @@ int64_t CWallet::IncOrderPosNext(WalletBatch* batch)
if (batch) { if (batch) {
batch->WriteOrderPosNext(nOrderPosNext); batch->WriteOrderPosNext(nOrderPosNext);
} else { } else {
WalletBatch(*database).WriteOrderPosNext(nOrderPosNext); WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
} }
return nRet; return nRet;
} }
@ -774,7 +774,7 @@ bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
wtx.mapValue["replaced_by_txid"] = newHash.ToString(); wtx.mapValue["replaced_by_txid"] = newHash.ToString();
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
bool success = true; bool success = true;
if (!batch.WriteTx(wtx)) { if (!batch.WriteTx(wtx)) {
@ -846,7 +846,7 @@ CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmatio
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
WalletBatch batch(*database, fFlushOnClose); WalletBatch batch(GetDatabase(), fFlushOnClose);
uint256 hash = tx->GetHash(); uint256 hash = tx->GetHash();
@ -1045,7 +1045,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
std::set<uint256> todo; std::set<uint256> todo;
std::set<uint256> done; std::set<uint256> done;
@ -1108,7 +1108,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, c
return; return;
// Do not flush the wallet here for performance reasons // Do not flush the wallet here for performance reasons
WalletBatch batch(*database, false); WalletBatch batch(GetDatabase(), false);
std::set<uint256> todo; std::set<uint256> todo;
std::set<uint256> done; std::set<uint256> done;
@ -1446,13 +1446,13 @@ void CWallet::SetWalletFlag(uint64_t flags)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
m_wallet_flags |= flags; m_wallet_flags |= flags;
if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) if (!WalletBatch(GetDatabase()).WriteWalletFlags(m_wallet_flags))
throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed"); throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
} }
void CWallet::UnsetWalletFlag(uint64_t flag) void CWallet::UnsetWalletFlag(uint64_t flag)
{ {
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
UnsetWalletFlagWithDB(batch, flag); UnsetWalletFlagWithDB(batch, flag);
} }
@ -1491,7 +1491,7 @@ bool CWallet::AddWalletFlags(uint64_t flags)
LOCK(cs_wallet); LOCK(cs_wallet);
// We should never be writing unknown non-tolerable wallet flags // We should never be writing unknown non-tolerable wallet flags
assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32)); assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
if (!WalletBatch(*database).WriteWalletFlags(flags)) { if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed"); throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
} }
@ -1582,7 +1582,7 @@ bool CWallet::ImportScriptPubKeys(const std::string& label, const std::set<CScri
return false; return false;
} }
if (apply_label) { if (apply_label) {
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
for (const CScript& script : script_pub_keys) { for (const CScript& script : script_pub_keys) {
CTxDestination dest; CTxDestination dest;
ExtractDestination(script, dest); ExtractDestination(script, dest);
@ -3177,10 +3177,10 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
LOCK(cs_wallet); LOCK(cs_wallet);
fFirstRunRet = false; fFirstRunRet = false;
DBErrors nLoadWalletRet = WalletBatch(*database).LoadWallet(this); DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
if (nLoadWalletRet == DBErrors::NEED_REWRITE) if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{ {
if (database->Rewrite("\x04pool")) if (GetDatabase().Rewrite("\x04pool"))
{ {
for (const auto& spk_man_pair : m_spk_managers) { for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->RewriteDB(); spk_man_pair.second->RewriteDB();
@ -3204,7 +3204,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{ {
AssertLockHeld(cs_wallet); AssertLockHeld(cs_wallet);
DBErrors nZapSelectTxRet = WalletBatch(*database).ZapSelectTx(vHashIn, vHashOut); DBErrors nZapSelectTxRet = WalletBatch(GetDatabase()).ZapSelectTx(vHashIn, vHashOut);
for (const uint256& hash : vHashOut) { for (const uint256& hash : vHashOut) {
const auto& it = mapWallet.find(hash); const auto& it = mapWallet.find(hash);
wtxOrdered.erase(it->second.m_it_wtxOrdered); wtxOrdered.erase(it->second.m_it_wtxOrdered);
@ -3216,7 +3216,7 @@ DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256
if (nZapSelectTxRet == DBErrors::NEED_REWRITE) if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
{ {
if (database->Rewrite("\x04pool")) if (GetDatabase().Rewrite("\x04pool"))
{ {
for (const auto& spk_man_pair : m_spk_managers) { for (const auto& spk_man_pair : m_spk_managers) {
spk_man_pair.second->RewriteDB(); spk_man_pair.second->RewriteDB();
@ -3254,14 +3254,14 @@ bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& add
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose) bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{ {
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
return SetAddressBookWithDB(batch, address, strName, strPurpose); return SetAddressBookWithDB(batch, address, strName, strPurpose);
} }
bool CWallet::DelAddressBook(const CTxDestination& address) bool CWallet::DelAddressBook(const CTxDestination& address)
{ {
bool is_mine; bool is_mine;
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
// 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) // 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)
@ -4008,7 +4008,7 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
int rescan_height = 0; int rescan_height = 0;
if (!gArgs.GetBoolArg("-rescan", false)) if (!gArgs.GetBoolArg("-rescan", false))
{ {
WalletBatch batch(*walletInstance->database); WalletBatch batch(walletInstance->GetDatabase());
CBlockLocator locator; CBlockLocator locator;
if (batch.ReadBestBlock(locator)) { if (batch.ReadBestBlock(locator)) {
if (const Optional<int> fork_height = chain.findLocatorFork(locator)) { if (const Optional<int> fork_height = chain.findLocatorFork(locator)) {
@ -4071,7 +4071,7 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
} }
} }
walletInstance->chainStateFlushed(chain.getTipLocator()); walletInstance->chainStateFlushed(chain.getTipLocator());
walletInstance->database->IncrementUpdateCounter(); walletInstance->GetDatabase().IncrementUpdateCounter();
} }
{ {
@ -4149,7 +4149,7 @@ void CWallet::postInitProcess()
bool CWallet::BackupWallet(const std::string& strDest) const bool CWallet::BackupWallet(const std::string& strDest) const
{ {
return database->Backup(strDest); return GetDatabase().Backup(strDest);
} }
CKeyPool::CKeyPool() CKeyPool::CKeyPool()
@ -4452,7 +4452,7 @@ void CWallet::SetupDescriptorScriptPubKeyMans()
void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal) void CWallet::AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
{ {
WalletBatch batch(*database); WalletBatch batch(GetDatabase());
if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) { if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed"); throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
} }

View file

@ -695,7 +695,7 @@ private:
std::string m_name; std::string m_name;
/** Internal database handle. */ /** Internal database handle. */
std::unique_ptr<WalletDatabase> database; std::unique_ptr<WalletDatabase> const m_database;
/** /**
* The following is used to keep track of how far behind the wallet is * The following is used to keep track of how far behind the wallet is
@ -729,14 +729,11 @@ public:
*/ */
mutable RecursiveMutex cs_wallet; mutable RecursiveMutex cs_wallet;
/** Get database handle used by this wallet. Ideally this function would WalletDatabase& GetDatabase() const override
* not be necessary.
*/
WalletDatabase& GetDBHandle()
{ {
return *database; assert(static_cast<bool>(m_database));
return *m_database;
} }
WalletDatabase& GetDatabase() const override { return *database; }
/** /**
* Select a set of coins such that nValueRet >= nTargetValue and at least * Select a set of coins such that nValueRet >= nTargetValue and at least
@ -758,7 +755,7 @@ public:
CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database) CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
: m_chain(chain), : m_chain(chain),
m_name(name), m_name(name),
database(std::move(database)) m_database(std::move(database))
{ {
} }

View file

@ -945,7 +945,7 @@ void MaybeCompactWalletDB()
} }
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
WalletDatabase& dbh = pwallet->GetDBHandle(); WalletDatabase& dbh = pwallet->GetDatabase();
unsigned int nUpdateCounter = dbh.nUpdateCounter; unsigned int nUpdateCounter = dbh.nUpdateCounter;