From 7770a7da959dfd4c06c6e4b32fb70c0c7bb59085 Mon Sep 17 00:00:00 2001 From: Pasta Date: Tue, 14 Apr 2020 17:13:51 -0500 Subject: [PATCH] scripted-diff: Rename wallet database classes (begin bitcoin#11851) -BEGIN VERIFY SCRIPT- sed -i 's/\/BerkeleyDatabase/g' src/wallet/db.h src/wallet/db.cpp sed -i '/statuses/i/** Backend-agnostic database type. */\nusing WalletDatabase = BerkeleyDatabase\;\n' src/wallet/walletdb.h ren() { git grep -l "\<$1\>" 'src/*.cpp' 'src/*.h' ':(exclude)*dbwrapper*' test | xargs sed -i "s:\<$1\>:$2:g"; } ren CDBEnv BerkeleyEnvironment ren CDB BerkeleyBatch ren CWalletDBWrapper WalletDatabase ren CWalletDB WalletBatch ren dbw database ren m_dbw m_database ren walletdb batch ren pwalletdb batch ren pwalletdbIn batch_in ren wallet/batch.h wallet/walletdb.h ren pwalletdbEncryption encrypted_batch -END VERIFY SCRIPT- Signed-off-by: Pasta --- src/bench/coin_selection.cpp | 2 +- src/qt/test/wallettests.cpp | 2 +- src/test/util_tests.cpp | 2 +- src/wallet/db.cpp | 144 ++++++------- src/wallet/db.h | 50 ++--- src/wallet/test/wallet_test_fixture.cpp | 2 +- src/wallet/test/wallet_tests.cpp | 16 +- src/wallet/wallet.cpp | 270 ++++++++++++------------ src/wallet/wallet.h | 34 +-- src/wallet/walletdb.cpp | 104 ++++----- src/wallet/walletdb.h | 38 ++-- 11 files changed, 335 insertions(+), 329 deletions(-) diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp index ab3ee34bc112b5..ca91b0b1d6e60f 100644 --- a/src/bench/coin_selection.cpp +++ b/src/bench/coin_selection.cpp @@ -32,7 +32,7 @@ static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector vCoins; LOCK(wallet.cs_wallet); diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp index 967eb3f3ba94df..6b115ebddaac14 100644 --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -115,7 +115,7 @@ void TestGUI() for (int i = 0; i < 5; ++i) { test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); } - CWallet wallet("mock", CWalletDBWrapper::CreateMock()); + CWallet wallet("mock", WalletDatabase::CreateMock()); bool firstRun; wallet.LoadWallet(firstRun); { diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index f7726420e2ee46..a0acfa01f4222d 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -62,7 +62,7 @@ BOOST_AUTO_TEST_CASE(util_ParseHex) result = ParseHex("12 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); - // Leading space must be supported (used in CDBEnv::Salvage) + // Leading space must be supported (used in BerkeleyEnvironment::Salvage) result = ParseHex(" 89 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp index 429eef58e1d173..d44b41fac87d47 100644 --- a/src/wallet/db.cpp +++ b/src/wallet/db.cpp @@ -30,14 +30,14 @@ namespace { //! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html), //! so bitcoin should never create different databases with the same fileid, but //! this error can be triggered if users manually copy database files. -void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db) +void CheckUniqueFileid(const BerkeleyEnvironment& env, const std::string& filename, Db& db) { if (env.IsMock()) return; u_int8_t fileid[DB_FILE_ID_LEN]; int ret = db.get_mpf()->get_fileid(fileid); if (ret != 0) { - throw std::runtime_error(strprintf("CDB: Can't open database %s (get_fileid failed with %d)", filename, ret)); + throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (get_fileid failed with %d)", filename, ret)); } for (const auto& item : env.mapDb) { @@ -46,7 +46,7 @@ void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db) memcmp(fileid, item_fileid, sizeof(fileid)) == 0) { const char* item_filename = nullptr; item.second->get_dbname(&item_filename, nullptr); - throw std::runtime_error(strprintf("CDB: Can't open database %s (duplicates fileid %s from %s)", filename, + throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (duplicates fileid %s from %s)", filename, HexStr(std::begin(item_fileid), std::end(item_fileid)), item_filename ? item_filename : "(unknown database)")); } @@ -54,10 +54,10 @@ void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db) } CCriticalSection cs_db; -std::map g_dbenvs; //!< Map from directory name to open db environment. +std::map g_dbenvs; //!< Map from directory name to open db environment. } // namespace -CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename) +BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename) { fs::path env_directory; if (fs::is_regular_file(wallet_path)) { @@ -73,7 +73,7 @@ CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename database_filename = "wallet.dat"; } LOCK(cs_db); - // Note: An ununsed temporary CDBEnv object may be created inside the + // Note: An ununsed temporary BerkeleyEnvironment object may be created inside the // emplace function if the key already exists. This is a little inefficient, // but not a big concern since the map will be changed in the future to hold // pointers instead of objects, anyway. @@ -81,10 +81,10 @@ CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename } // -// CDB +// BerkeleyBatch // -void CDBEnv::Close() +void BerkeleyEnvironment::Close() { if (!fDbEnvInit) return; @@ -103,29 +103,29 @@ void CDBEnv::Close() int ret = dbenv->close(0); if (ret != 0) - LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret)); + LogPrintf("BerkeleyEnvironment::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret)); if (!fMockDb) DbEnv((u_int32_t)0).remove(strPath.c_str(), 0); } -void CDBEnv::Reset() +void BerkeleyEnvironment::Reset() { dbenv.reset(new DbEnv(DB_CXX_NO_EXCEPTIONS)); fDbEnvInit = false; fMockDb = false; } -CDBEnv::CDBEnv(const fs::path& dir_path) : strPath(dir_path.string()) +BerkeleyEnvironment::BerkeleyEnvironment(const fs::path& dir_path) : strPath(dir_path.string()) { Reset(); } -CDBEnv::~CDBEnv() +BerkeleyEnvironment::~BerkeleyEnvironment() { Close(); } -bool CDBEnv::Open(bool retry) +bool BerkeleyEnvironment::Open(bool retry) { if (fDbEnvInit) return true; @@ -142,7 +142,7 @@ bool CDBEnv::Open(bool retry) fs::path pathLogDir = pathIn / "database"; TryCreateDirectories(pathLogDir); fs::path pathErrorFile = pathIn / "db.log"; - LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string()); + LogPrintf("BerkeleyEnvironment::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string()); unsigned int nEnvFlags = 0; if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB)) @@ -170,7 +170,7 @@ bool CDBEnv::Open(bool retry) S_IRUSR | S_IWUSR); if (ret != 0) { dbenv->close(0); - LogPrintf("CDBEnv::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret)); + LogPrintf("BerkeleyEnvironment::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret)); if (retry) { // try moving the database env out of the way fs::path pathDatabaseBak = pathIn / strprintf("database.%d.bak", GetTime()); @@ -195,14 +195,14 @@ bool CDBEnv::Open(bool retry) return true; } -void CDBEnv::MakeMock() +void BerkeleyEnvironment::MakeMock() { if (fDbEnvInit) - throw std::runtime_error("CDBEnv::MakeMock: Already initialized"); + throw std::runtime_error("BerkeleyEnvironment::MakeMock: Already initialized"); boost::this_thread::interruption_point(); - LogPrint(BCLog::DB, "CDBEnv::MakeMock\n"); + LogPrint(BCLog::DB, "BerkeleyEnvironment::MakeMock\n"); dbenv->set_cachesize(1, 0, 1); dbenv->set_lg_bsize(10485760 * 4); @@ -221,13 +221,13 @@ void CDBEnv::MakeMock() DB_PRIVATE, S_IRUSR | S_IWUSR); if (ret > 0) - throw std::runtime_error(strprintf("CDBEnv::MakeMock: Error %d opening database environment.", ret)); + throw std::runtime_error(strprintf("BerkeleyEnvironment::MakeMock: Error %d opening database environment.", ret)); fDbEnvInit = true; fMockDb = true; } -CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename) +BerkeleyEnvironment::VerifyResult BerkeleyEnvironment::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename) { LOCK(cs_db); assert(mapFileUseCount.count(strFile) == 0); @@ -244,10 +244,10 @@ CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type return (fRecovered ? RECOVER_OK : RECOVER_FAIL); } -bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename) +bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename) { std::string filename; - CDBEnv* env = GetWalletEnv(file_path, filename); + BerkeleyEnvironment* env = GetWalletEnv(file_path, filename); // Recovery procedure: // move wallet file to walletfilename.timestamp.bak @@ -269,7 +269,7 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove return false; } - std::vector salvagedData; + std::vector salvagedData; bool fSuccess = env->Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { @@ -292,7 +292,7 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove } DbTxn* ptxn = env->TxnBegin(); - for (CDBEnv::KeyValPair& row : salvagedData) + for (BerkeleyEnvironment::KeyValPair& row : salvagedData) { if (recoverKVcallback) { @@ -313,10 +313,10 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove return fSuccess; } -bool CDB::VerifyEnvironment(const fs::path& file_path, std::string& errorStr) +bool BerkeleyBatch::VerifyEnvironment(const fs::path& file_path, std::string& errorStr) { std::string walletFile; - CDBEnv* env = GetWalletEnv(file_path, walletFile); + BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile); fs::path walletDir = env->Directory(); LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0)); @@ -337,17 +337,17 @@ bool CDB::VerifyEnvironment(const fs::path& file_path, std::string& errorStr) return true; } -bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc) +bool BerkeleyBatch::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc) { std::string walletFile; - CDBEnv* env = GetWalletEnv(file_path, walletFile); + BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile); fs::path walletDir = env->Directory(); if (fs::exists(walletDir / walletFile)) { std::string backup_filename; - CDBEnv::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename); - if (r == CDBEnv::RECOVER_OK) + BerkeleyEnvironment::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename); + if (r == BerkeleyEnvironment::RECOVER_OK) { warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!" " Original %s saved as %s in %s; if" @@ -355,7 +355,7 @@ bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, " restore from a backup."), walletFile, backup_filename, walletDir); } - if (r == CDBEnv::RECOVER_FAIL) + if (r == BerkeleyEnvironment::RECOVER_FAIL) { errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile); return false; @@ -370,7 +370,7 @@ static const char *HEADER_END = "HEADER=END"; /* End of key/value data */ static const char *DATA_END = "DATA=END"; -bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector& vResult) +bool BerkeleyEnvironment::Salvage(const std::string& strFile, bool fAggressive, std::vector& vResult) { LOCK(cs_db); assert(mapFileUseCount.count(strFile) == 0); @@ -384,14 +384,14 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vectortxn_checkpoint(0, 0, 0); if (fMockDb) @@ -440,15 +440,15 @@ void CDBEnv::CheckpointLSN(const std::string& strFile) } -CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr) +BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr) { fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w')); fFlushOnClose = fFlushOnCloseIn; - env = dbw.env; - if (dbw.IsDummy()) { + env = database.env; + if (database.IsDummy()) { return; } - const std::string &strFilename = dbw.strFile; + const std::string &strFilename = database.strFile; bool fCreate = strchr(pszMode, 'c') != nullptr; unsigned int nFlags = DB_THREAD; @@ -458,7 +458,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb { LOCK(cs_db); if (!env->Open(false /* retry */)) - throw std::runtime_error("CDB: Failed to open database environment."); + throw std::runtime_error("BerkeleyBatch: Failed to open database environment."); pdb = env->mapDb[strFilename]; if (pdb == nullptr) { @@ -470,7 +470,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb DbMpoolFile* mpf = pdb_temp->get_mpf(); ret = mpf->set_flags(DB_MPOOL_NOFILE, 1); if (ret != 0) { - throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFilename)); + throw std::runtime_error(strprintf("BerkeleyBatch: Failed to configure for no temp file backing for database %s", strFilename)); } } @@ -482,7 +482,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb 0); if (ret != 0) { - throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename)); + throw std::runtime_error(strprintf("BerkeleyBatch: Error %d, can't open database %s", ret, strFilename)); } // Call CheckUniqueFileid on the containing BDB environment to @@ -519,7 +519,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb } } -void CDB::Flush() +void BerkeleyBatch::Flush() { if (activeTxn) return; @@ -532,12 +532,12 @@ void CDB::Flush() env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0); } -void CWalletDBWrapper::IncrementUpdateCounter() +void BerkeleyDatabase::IncrementUpdateCounter() { ++nUpdateCounter; } -void CDB::Close() +void BerkeleyBatch::Close() { if (!pdb) return; @@ -555,7 +555,7 @@ void CDB::Close() } } -void CDBEnv::CloseDb(const std::string& strFile) +void BerkeleyEnvironment::CloseDb(const std::string& strFile) { { LOCK(cs_db); @@ -569,13 +569,13 @@ void CDBEnv::CloseDb(const std::string& strFile) } } -bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip) +bool BerkeleyBatch::Rewrite(BerkeleyDatabase& database, const char* pszSkip) { - if (dbw.IsDummy()) { + if (database.IsDummy()) { return true; } - CDBEnv *env = dbw.env; - const std::string& strFile = dbw.strFile; + BerkeleyEnvironment *env = database.env; + const std::string& strFile = database.strFile; while (true) { { LOCK(cs_db); @@ -586,10 +586,10 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip) env->mapFileUseCount.erase(strFile); bool fSuccess = true; - LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile); + LogPrintf("BerkeleyBatch::Rewrite: Rewriting %s...\n", strFile); std::string strFileRes = strFile + ".rewrite"; { // surround usage of db with extra {} - CDB db(dbw, "r"); + BerkeleyBatch db(database, "r"); std::unique_ptr pdbCopy = MakeUnique(env->dbenv.get(), 0); int ret = pdbCopy->open(nullptr, // Txn pointer @@ -599,7 +599,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip) DB_CREATE, // Flags 0); if (ret > 0) { - LogPrintf("CDB::Rewrite: Can't create database file %s\n", strFileRes); + LogPrintf("BerkeleyBatch::Rewrite: Can't create database file %s\n", strFileRes); fSuccess = false; } @@ -649,7 +649,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip) fSuccess = false; } if (!fSuccess) - LogPrintf("CDB::Rewrite: Failed to rewrite database file %s\n", strFileRes); + LogPrintf("BerkeleyBatch::Rewrite: Failed to rewrite database file %s\n", strFileRes); return fSuccess; } } @@ -658,11 +658,11 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip) } -void CDBEnv::Flush(bool fShutdown) +void BerkeleyEnvironment::Flush(bool fShutdown) { int64_t nStart = GetTimeMillis(); // Flush log data to the actual data file on all files that are not in use - LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started"); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started"); if (!fDbEnvInit) return; { @@ -671,21 +671,21 @@ void CDBEnv::Flush(bool fShutdown) while (mi != mapFileUseCount.end()) { std::string strFile = (*mi).first; int nRefCount = (*mi).second; - LogPrint(BCLog::DB, "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount); if (nRefCount == 0) { // Move log data to the dat file CloseDb(strFile); - LogPrint(BCLog::DB, "CDBEnv::Flush: %s checkpoint\n", strFile); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s checkpoint\n", strFile); dbenv->txn_checkpoint(0, 0, 0); - LogPrint(BCLog::DB, "CDBEnv::Flush: %s detach\n", strFile); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s detach\n", strFile); if (!fMockDb) dbenv->lsn_reset(strFile.c_str(), 0); - LogPrint(BCLog::DB, "CDBEnv::Flush: %s closed\n", strFile); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s closed\n", strFile); mapFileUseCount.erase(mi++); } else mi++; } - LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart); + LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart); if (fShutdown) { char** listp; if (mapFileUseCount.empty()) { @@ -698,14 +698,14 @@ void CDBEnv::Flush(bool fShutdown) } } -bool CDB::PeriodicFlush(CWalletDBWrapper& dbw) +bool BerkeleyBatch::PeriodicFlush(BerkeleyDatabase& database) { - if (dbw.IsDummy()) { + if (database.IsDummy()) { return true; } bool ret = false; - CDBEnv *env = dbw.env; - const std::string& strFile = dbw.strFile; + BerkeleyEnvironment *env = database.env; + const std::string& strFile = database.strFile; TRY_LOCK(cs_db, lockDb); if (lockDb) { @@ -741,12 +741,12 @@ bool CDB::PeriodicFlush(CWalletDBWrapper& dbw) return ret; } -bool CWalletDBWrapper::Rewrite(const char* pszSkip) +bool BerkeleyDatabase::Rewrite(const char* pszSkip) { - return CDB::Rewrite(*this, pszSkip); + return BerkeleyBatch::Rewrite(*this, pszSkip); } -bool CWalletDBWrapper::Backup(const std::string& strDest) +bool BerkeleyDatabase::Backup(const std::string& strDest) { if (IsDummy()) { return false; @@ -787,7 +787,7 @@ bool CWalletDBWrapper::Backup(const std::string& strDest) } } -void CWalletDBWrapper::Flush(bool shutdown) +void BerkeleyDatabase::Flush(bool shutdown) { if (!IsDummy()) { env->Flush(shutdown); diff --git a/src/wallet/db.h b/src/wallet/db.h index c32be74621ef09..3d0addb0e7a021 100644 --- a/src/wallet/db.h +++ b/src/wallet/db.h @@ -25,7 +25,7 @@ static const unsigned int DEFAULT_WALLET_DBLOGSIZE = 100; static const bool DEFAULT_WALLET_PRIVDB = true; -class CDBEnv +class BerkeleyEnvironment { private: bool fDbEnvInit; @@ -39,8 +39,8 @@ class CDBEnv std::map mapFileUseCount; std::map mapDb; - CDBEnv(const fs::path& env_directory); - ~CDBEnv(); + BerkeleyEnvironment(const fs::path& env_directory); + ~BerkeleyEnvironment(); void Reset(); void MakeMock(); @@ -86,23 +86,23 @@ class CDBEnv } }; -/** Get CDBEnv and database filename given a wallet path. */ -CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename); +/** Get BerkeleyEnvironment and database filename given a wallet path. */ +BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename); /** An instance of this class represents one database. * For BerkeleyDB this is just a (env, strFile) tuple. **/ -class CWalletDBWrapper +class BerkeleyDatabase { - friend class CDB; + friend class BerkeleyBatch; public: /** Create dummy DB handle */ - CWalletDBWrapper() : nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0), env(nullptr) + BerkeleyDatabase() : nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0), env(nullptr) { } /** Create DB handle to real database */ - CWalletDBWrapper(const fs::path& wallet_path, bool mock = false) : + BerkeleyDatabase(const fs::path& wallet_path, bool mock = false) : nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0) { env = GetWalletEnv(wallet_path, strFile); @@ -114,21 +114,21 @@ class CWalletDBWrapper } /** Return object for accessing database at specified path. */ - static std::unique_ptr Create(const fs::path& path) + static std::unique_ptr Create(const fs::path& path) { - return MakeUnique(path); + return MakeUnique(path); } /** Return object for accessing dummy database with no read/write capabilities. */ - static std::unique_ptr CreateDummy() + static std::unique_ptr CreateDummy() { - return MakeUnique(); + return MakeUnique(); } /** Return object for accessing temporary in-memory database. */ - static std::unique_ptr CreateMock() + static std::unique_ptr CreateMock() { - return MakeUnique("", true /* mock */); + return MakeUnique("", true /* mock */); } /** Rewrite the entire database on disk, with the exception of key pszSkip if non-zero @@ -152,7 +152,7 @@ class CWalletDBWrapper private: /** BerkeleyDB specific */ - CDBEnv *env; + BerkeleyEnvironment *env; std::string strFile; /** Return whether this database handle is a dummy for testing. @@ -164,7 +164,7 @@ class CWalletDBWrapper /** RAII class that provides access to a Berkeley database */ -class CDB +class BerkeleyBatch { protected: Db* pdb; @@ -172,14 +172,14 @@ class CDB DbTxn* activeTxn; bool fReadOnly; bool fFlushOnClose; - CDBEnv *env; + BerkeleyEnvironment *env; public: - explicit CDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool fFlushOnCloseIn=true); - ~CDB() { Close(); } + explicit BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode = "r+", bool fFlushOnCloseIn=true); + ~BerkeleyBatch() { Close(); } - CDB(const CDB&) = delete; - CDB& operator=(const CDB&) = delete; + BerkeleyBatch(const BerkeleyBatch&) = delete; + BerkeleyBatch& operator=(const BerkeleyBatch&) = delete; void Flush(); void Close(); @@ -187,11 +187,11 @@ class CDB /* flush the wallet passively (TRY_LOCK) ideal to be called periodically */ - static bool PeriodicFlush(CWalletDBWrapper& dbw); + static bool PeriodicFlush(BerkeleyDatabase& database); /* verifies the database environment */ static bool VerifyEnvironment(const fs::path& file_path, std::string& errorStr); /* verifies the database file */ - static bool VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc); + static bool VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc); public: template @@ -387,7 +387,7 @@ class CDB return Write(std::string("version"), nVersion); } - bool static Rewrite(CWalletDBWrapper& dbw, const char* pszSkip = nullptr); + bool static Rewrite(BerkeleyDatabase& database, const char* pszSkip = nullptr); }; #endif // BITCOIN_WALLET_DB_H diff --git a/src/wallet/test/wallet_test_fixture.cpp b/src/wallet/test/wallet_test_fixture.cpp index c19e40e290b94c..795f879cfb503c 100644 --- a/src/wallet/test/wallet_test_fixture.cpp +++ b/src/wallet/test/wallet_test_fixture.cpp @@ -9,7 +9,7 @@ #include WalletTestingSetup::WalletTestingSetup(const std::string& chainName): - TestingSetup(chainName), m_wallet("mock", CWalletDBWrapper::CreateMock()) + TestingSetup(chainName), m_wallet("mock", WalletDatabase::CreateMock()) { bool fFirstRun; m_wallet.LoadWallet(fFirstRun); diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index 51c1ca0838de40..6892132ba8dd65 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -37,7 +37,7 @@ typedef std::set CoinSet; BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) -static const CWallet testWallet("dummy", CWalletDBWrapper::CreateDummy()); +static const CWallet testWallet("dummy", WalletDatabase::CreateDummy()); static std::vector vCoins; static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) @@ -383,7 +383,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); @@ -398,7 +398,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) // Verify ScanForWalletTransactions only picks transactions in the new block // file. { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); @@ -410,7 +410,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) // before the missing block, and success for a key whose creation time is // after. { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); AddWallet(&wallet); UniValue keys; keys.setArray(); @@ -469,7 +469,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Import key into wallet and call dumpwallet to create backup file. { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); LOCK(wallet.cs_wallet); wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME; wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); @@ -484,7 +484,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); JSONRPCRequest request; request.params.setArray(); @@ -514,7 +514,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // debit functions. BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) { - CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); + CWallet wallet("dummy", WalletDatabase::CreateDummy()); CWalletTx wtx(&wallet, MakeTransactionRef(coinbaseTxns.back())); LOCK2(cs_main, wallet.cs_wallet); wtx.hashBlock = chainActive.Tip()->GetBlockHash(); @@ -604,7 +604,7 @@ class ListCoinsTestingSetup : public TestChain100Setup ListCoinsTestingSetup() { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - wallet = MakeUnique("mock", CWalletDBWrapper::CreateMock()); + wallet = MakeUnique("mock", WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); AddKey(*wallet, coinbaseKey); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 6989a7d7c89c4d..e915c1c767a25d 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -185,7 +185,7 @@ const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const return &(it->second); } -CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, uint32_t nAccountIndex, bool fInternal) +CPubKey CWallet::GenerateNewKey(WalletBatch &batch, uint32_t nAccountIndex, bool fInternal) { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets @@ -199,7 +199,7 @@ CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, uint32_t nAccountIndex, boo CPubKey pubkey; // use HD key derivation if HD was enabled during wallet creation if (IsHDEnabled()) { - DeriveNewChildKey(walletdb, metadata, secret, nAccountIndex, fInternal); + DeriveNewChildKey(batch, metadata, secret, nAccountIndex, fInternal); pubkey = secret.GetPubKey(); } else { secret.MakeNewKey(fCompressed); @@ -216,14 +216,14 @@ CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, uint32_t nAccountIndex, boo mapKeyMetadata[pubkey.GetID()] = metadata; UpdateTimeFirstKey(nCreationTime); - if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) { + if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) { throw std::runtime_error(std::string(__func__) + ": AddKey failed"); } } return pubkey; } -void CWallet::DeriveNewChildKey(CWalletDB &walletdb, const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal) +void CWallet::DeriveNewChildKey(WalletBatch &batch, const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal) { CHDChain hdChainTmp; if (!GetHDChain(hdChainTmp)) { @@ -272,15 +272,15 @@ void CWallet::DeriveNewChildKey(CWalletDB &walletdb, const CKeyMetadata& metadat throw std::runtime_error(std::string(__func__) + ": SetAccount failed"); if (IsCrypted()) { - if (!SetCryptedHDChain(walletdb, hdChainCurrent, false)) + if (!SetCryptedHDChain(batch, hdChainCurrent, false)) throw std::runtime_error(std::string(__func__) + ": SetCryptedHDChain failed"); } else { - if (!SetHDChain(walletdb, hdChainCurrent, false)) + if (!SetHDChain(batch, hdChainCurrent, false)) throw std::runtime_error(std::string(__func__) + ": SetHDChain failed"); } - if (!AddHDPubKey(walletdb, childKey.Neuter(), fInternal)) + if (!AddHDPubKey(batch, childKey.Neuter(), fInternal)) throw std::runtime_error(std::string(__func__) + ": AddHDPubKey failed"); } @@ -342,7 +342,7 @@ bool CWallet::LoadHDPubKey(const CHDPubKey &hdPubKey) return true; } -bool CWallet::AddHDPubKey(CWalletDB &walletdb, const CExtPubKey &extPubKey, bool fInternal) +bool CWallet::AddHDPubKey(WalletBatch &batch, const CExtPubKey &extPubKey, bool fInternal) { AssertLockHeld(cs_wallet); @@ -364,25 +364,25 @@ bool CWallet::AddHDPubKey(CWalletDB &walletdb, const CExtPubKey &extPubKey, bool if (HaveWatchOnly(script)) RemoveWatchOnly(script); - return walletdb.WriteHDPubKey(hdPubKey, mapKeyMetadata[extPubKey.pubkey.GetID()]); + return batch.WriteHDPubKey(hdPubKey, mapKeyMetadata[extPubKey.pubkey.GetID()]); } -bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey) +bool CWallet::AddKeyPubKeyWithDB(WalletBatch &batch, const CKey& secret, const CPubKey &pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey // which is overridden below. To avoid flushes, the database handle is // tunneled through to it. - bool needsDB = !pwalletdbEncryption; + bool needsDB = !encrypted_batch; if (needsDB) { - pwalletdbEncryption = &walletdb; + encrypted_batch = &batch; } if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) { - if (needsDB) pwalletdbEncryption = nullptr; + if (needsDB) encrypted_batch = nullptr; return false; } - if (needsDB) pwalletdbEncryption = nullptr; + if (needsDB) encrypted_batch = nullptr; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); @@ -395,7 +395,7 @@ bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const } if (!IsCrypted()) { - return walletdb.WriteKey(pubkey, + return batch.WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } @@ -405,9 +405,9 @@ bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); - return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey); + return CWallet::AddKeyPubKeyWithDB(batch, secret, pubkey); } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, @@ -417,12 +417,12 @@ bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, return false; { LOCK(cs_wallet); - if (pwalletdbEncryption) - return pwalletdbEncryption->WriteCryptedKey(vchPubKey, + if (encrypted_batch) + return encrypted_batch->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else - return CWalletDB(*dbw).WriteCryptedKey(vchPubKey, + return WalletBatch(*database).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } @@ -469,7 +469,7 @@ bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; - return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript); + return WalletBatch(*database).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) @@ -495,7 +495,7 @@ bool CWallet::AddWatchOnly(const CScript& dest) const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)]; UpdateTimeFirstKey(meta.nCreateTime); NotifyWatchonlyChanged(true); - return CWalletDB(*dbw).WriteWatchOnly(dest, meta); + return WalletBatch(*database).WriteWatchOnly(dest, meta); } bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime) @@ -511,7 +511,7 @@ bool CWallet::RemoveWatchOnly(const CScript &dest) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); - if (!CWalletDB(*dbw).EraseWatchOnly(dest)) + if (!WalletBatch(*database).EraseWatchOnly(dest)) return false; return true; @@ -616,7 +616,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, return false; if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey)) return false; - CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second); + WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); @@ -641,11 +641,11 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, void CWallet::SetBestChain(const CBlockLocator& loc) { - CWalletDB walletdb(*dbw); - walletdb.WriteBestBlock(loc); + WalletBatch batch(*database); + batch.WriteBestBlock(loc); } -bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) +bool CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) @@ -661,11 +661,11 @@ bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, nWalletMaxVersion = nVersion; { - CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw); + WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database); if (nWalletVersion > 40000) - pwalletdb->WriteMinVersion(nWalletVersion); - if (!pwalletdbIn) - delete pwalletdb; + batch->WriteMinVersion(nWalletVersion); + if (!batch_in) + delete batch; } return true; @@ -708,7 +708,7 @@ std::set CWallet::GetConflicts(const uint256& txid) const void CWallet::Flush(bool shutdown) { - dbw->Flush(shutdown); + database->Flush(shutdown); } void CWallet::SyncMetaData(std::pair range) @@ -832,14 +832,14 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; - assert(!pwalletdbEncryption); - pwalletdbEncryption = new CWalletDB(*dbw); - if (!pwalletdbEncryption->TxnBegin()) { - delete pwalletdbEncryption; - pwalletdbEncryption = nullptr; + assert(!encrypted_batch); + encrypted_batch = new WalletBatch(*database); + if (!encrypted_batch->TxnBegin()) { + delete encrypted_batch; + encrypted_batch = nullptr; return false; } - pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); + encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey); // must get current HD chain before EncryptKeys CHDChain hdChainCurrent; @@ -847,8 +847,8 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) if (!EncryptKeys(_vMasterKey)) { - pwalletdbEncryption->TxnAbort(); - delete pwalletdbEncryption; + encrypted_batch->TxnAbort(); + delete encrypted_batch; // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload the unencrypted wallet. assert(false); @@ -869,21 +869,21 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) assert(hdChainCurrent.GetID() == hdChainCrypted.GetID()); assert(hdChainCurrent.GetSeedHash() != hdChainCrypted.GetSeedHash()); - assert(SetCryptedHDChain(*pwalletdbEncryption, hdChainCrypted, false)); + assert(SetCryptedHDChain(*encrypted_batch, hdChainCrypted, false)); } // Encryption was introduced in version 0.4.0 - SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); + SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true); - if (!pwalletdbEncryption->TxnCommit()) { - delete pwalletdbEncryption; + if (!encrypted_batch->TxnCommit()) { + delete encrypted_batch; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload the unencrypted wallet. assert(false); } - delete pwalletdbEncryption; - pwalletdbEncryption = nullptr; + delete encrypted_batch; + encrypted_batch = nullptr; Lock(); Unlock(strWalletPassphrase); @@ -900,7 +900,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) // 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. - dbw->Rewrite(); + database->Rewrite(); // Update KeePass if necessary if(gArgs.GetBoolArg("-keepass", false)) { @@ -921,7 +921,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) DBErrors CWallet::ReorderTransactions() { LOCK(cs_wallet); - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this @@ -937,7 +937,7 @@ DBErrors CWallet::ReorderTransactions() txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr))); } std::list acentries; - walletdb.ListAccountCreditDebit("", acentries); + batch.ListAccountCreditDebit("", acentries); for (CAccountingEntry& entry : acentries) { txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry))); @@ -958,11 +958,11 @@ DBErrors CWallet::ReorderTransactions() if (pwtx) { - if (!walletdb.WriteTx(*pwtx)) + if (!batch.WriteTx(*pwtx)) return DB_LOAD_FAIL; } else - if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) + if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else @@ -982,60 +982,60 @@ DBErrors CWallet::ReorderTransactions() // Since we're changing the order, write it back if (pwtx) { - if (!walletdb.WriteTx(*pwtx)) + if (!batch.WriteTx(*pwtx)) return DB_LOAD_FAIL; } else - if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) + if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } - walletdb.WriteOrderPosNext(nOrderPosNext); + batch.WriteOrderPosNext(nOrderPosNext); return DB_LOAD_OK; } -int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) +int64_t CWallet::IncOrderPosNext(WalletBatch *batch) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; - if (pwalletdb) { - pwalletdb->WriteOrderPosNext(nOrderPosNext); + if (batch) { + batch->WriteOrderPosNext(nOrderPosNext); } else { - CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext); + WalletBatch(*database).WriteOrderPosNext(nOrderPosNext); } return nRet; } bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment) { - CWalletDB walletdb(*dbw); - if (!walletdb.TxnBegin()) + WalletBatch batch(*database); + if (!batch.TxnBegin()) return false; int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; - debit.nOrderPos = IncOrderPosNext(&walletdb); + debit.nOrderPos = IncOrderPosNext(&batch); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; - AddAccountingEntry(debit, &walletdb); + AddAccountingEntry(debit, &batch); // Credit CAccountingEntry credit; - credit.nOrderPos = IncOrderPosNext(&walletdb); + credit.nOrderPos = IncOrderPosNext(&batch); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; - AddAccountingEntry(credit, &walletdb); + AddAccountingEntry(credit, &batch); - if (!walletdb.TxnCommit()) + if (!batch.TxnCommit()) return false; return true; @@ -1043,10 +1043,10 @@ bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmoun bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew) { - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); CAccount account; - walletdb.ReadAccount(strAccount, account); + batch.ReadAccount(strAccount, account); if (!bForceNew) { if (!account.vchPubKey.IsValid()) @@ -1072,7 +1072,7 @@ bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount dest = account.vchPubKey.GetID(); SetAddressBook(dest, strAccount, "receive"); - walletdb.WriteAccount(strAccount, account); + batch.WriteAccount(strAccount, account); } else { dest = account.vchPubKey.GetID(); } @@ -1096,7 +1096,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose) { LOCK(cs_wallet); - CWalletDB walletdb(*dbw, "r+", fFlushOnClose); + WalletBatch batch(*database, "r+", fFlushOnClose); uint256 hash = wtxIn.GetHash(); @@ -1107,7 +1107,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose) bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); - wtx.nOrderPos = IncOrderPosNext(&walletdb); + wtx.nOrderPos = IncOrderPosNext(&batch); wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr))); wtx.nTimeSmart = ComputeTimeSmart(wtx); AddToSpends(hash); @@ -1155,7 +1155,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose) // Write to disk if (fInsertedNew || fUpdated) - if (!walletdb.WriteTx(wtx)) + if (!batch.WriteTx(wtx)) return false; // Break debit/credit balance caches: @@ -1285,7 +1285,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx) { LOCK2(cs_main, cs_wallet); - CWalletDB walletdb(*dbw, "r+"); + WalletBatch batch(*database, "r+"); std::set todo; std::set done; @@ -1317,7 +1317,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx) wtx.nIndex = -1; wtx.setAbandoned(); wtx.MarkDirty(); - walletdb.WriteTx(wtx); + batch.WriteTx(wtx); NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED); // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0)); @@ -1347,7 +1347,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx) void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx) { - LOCK2(cs_main, cs_wallet); // check "LOCK2(cs_main, pwallet->cs_wallet);" in CWalletDB::LoadWallet() + LOCK2(cs_main, cs_wallet); // check "LOCK2(cs_main, pwallet->cs_wallet);" in WalletBatch::LoadWallet() int conflictconfirms = 0; if (mapBlockIndex.count(hashBlock)) { @@ -1364,7 +1364,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx) return; // Do not flush the wallet here for performance reasons - CWalletDB walletdb(*dbw, "r+", false); + WalletBatch batch(*database, "r+", false); std::set todo; std::set done; @@ -1385,7 +1385,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx) wtx.nIndex = -1; wtx.hashBlock = hashBlock; wtx.MarkDirty(); - walletdb.WriteTx(wtx); + batch.WriteTx(wtx); // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0)); while (iter != mapTxSpends.end() && iter->first.hash == now) { @@ -1758,20 +1758,20 @@ void CWallet::GenerateNewHDChain() gArgs.ForceRemoveArg("-mnemonicpassphrase"); } -bool CWallet::SetHDChain(CWalletDB &walletdb, const CHDChain& chain, bool memonly) +bool CWallet::SetHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly) { LOCK(cs_wallet); if (!CCryptoKeyStore::SetHDChain(chain)) return false; - if (!memonly && !walletdb.WriteHDChain(chain)) + if (!memonly && !batch.WriteHDChain(chain)) throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed"); return true; } -bool CWallet::SetCryptedHDChain(CWalletDB &walletdb, const CHDChain& chain, bool memonly) +bool CWallet::SetCryptedHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly) { LOCK(cs_wallet); @@ -1779,11 +1779,11 @@ bool CWallet::SetCryptedHDChain(CWalletDB &walletdb, const CHDChain& chain, bool return false; if (!memonly) { - if (pwalletdbEncryption) { - if (!pwalletdbEncryption->WriteCryptedHDChain(chain)) + if (encrypted_batch) { + if (!encrypted_batch->WriteCryptedHDChain(chain)) throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed"); } else { - if (!walletdb.WriteCryptedHDChain(chain)) + if (!batch.WriteCryptedHDChain(chain)) throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed"); } } @@ -1793,14 +1793,14 @@ bool CWallet::SetCryptedHDChain(CWalletDB &walletdb, const CHDChain& chain, bool bool CWallet::SetHDChainSingle(const CHDChain& chain, bool memonly) { - CWalletDB walletdb(*dbw); - return SetHDChain(walletdb, chain, memonly); + WalletBatch batch(*database); + return SetHDChain(batch, chain, memonly); } bool CWallet::SetCryptedHDChainSingle(const CHDChain& chain, bool memonly) { - CWalletDB walletdb(*dbw); - return SetCryptedHDChain(walletdb, chain, memonly); + WalletBatch batch(*database); + return SetCryptedHDChain(batch, chain, memonly); } bool CWallet::GetDecryptedHDChain(CHDChain& hdChainRet) @@ -2763,7 +2763,7 @@ CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, cons } if (account) { - balance += CWalletDB(*dbw).GetAccountCreditDebit(*account); + balance += WalletBatch(*database).GetAccountCreditDebit(*account); } return balance; @@ -4128,20 +4128,20 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CCon } void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list& entries) { - CWalletDB walletdb(*dbw); - return walletdb.ListAccountCreditDebit(strAccount, entries); + WalletBatch batch(*database); + return batch.ListAccountCreditDebit(strAccount, entries); } bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry) { - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); - return AddAccountingEntry(acentry, &walletdb); + return AddAccountingEntry(acentry, &batch); } -bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb) +bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, WalletBatch *batch) { - if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) { + if (!batch->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) { return false; } @@ -4157,10 +4157,10 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) LOCK2(cs_main, cs_wallet); fFirstRunRet = false; - DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this); + DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { - if (dbw->Rewrite("\x04pool")) + if (database->Rewrite("\x04pool")) { setInternalKeyPool.clear(); setExternalKeyPool.clear(); @@ -4215,7 +4215,7 @@ void CWallet::AutoLockMasternodeCollaterals() DBErrors CWallet::ZapSelectTx(std::vector& vHashIn, std::vector& vHashOut) { AssertLockHeld(cs_wallet); // mapWallet - DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut); + DBErrors nZapSelectTxRet = WalletBatch(*database,"cr+").ZapSelectTx(vHashIn, vHashOut); for (uint256 hash : vHashOut) { const auto& it = mapWallet.find(hash); wtxOrdered.erase(it->second.m_it_wtxOrdered); @@ -4224,7 +4224,7 @@ DBErrors CWallet::ZapSelectTx(std::vector& vHashIn, std::vectorRewrite("\x04pool")) + if (database->Rewrite("\x04pool")) { setInternalKeyPool.clear(); setExternalKeyPool.clear(); @@ -4246,10 +4246,10 @@ DBErrors CWallet::ZapSelectTx(std::vector& vHashIn, std::vector& vWtx) { - DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx); + DBErrors nZapWalletTxRet = WalletBatch(*database,"cr+").ZapWalletTx(vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { - if (dbw->Rewrite("\x04pool")) + if (database->Rewrite("\x04pool")) { LOCK(cs_wallet); setInternalKeyPool.clear(); @@ -4282,9 +4282,9 @@ bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& s } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) ); - if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose)) + if (!strPurpose.empty() && !WalletBatch(*database).WritePurpose(EncodeDestination(address), strPurpose)) return false; - return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName); + return WalletBatch(*database).WriteName(EncodeDestination(address), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) @@ -4296,15 +4296,15 @@ bool CWallet::DelAddressBook(const CTxDestination& address) std::string strAddress = EncodeDestination(address); for (const std::pair &item : mapAddressBook[address].destdata) { - CWalletDB(*dbw).EraseDestData(strAddress, item.first); + WalletBatch(*database).EraseDestData(strAddress, item.first); } mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); - CWalletDB(*dbw).ErasePurpose(EncodeDestination(address)); - return CWalletDB(*dbw).EraseName(EncodeDestination(address)); + WalletBatch(*database).ErasePurpose(EncodeDestination(address)); + return WalletBatch(*database).EraseName(EncodeDestination(address)); } const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const @@ -4330,13 +4330,13 @@ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); for (int64_t nIndex : setInternalKeyPool) { - walletdb.ErasePool(nIndex); + batch.ErasePool(nIndex); } setInternalKeyPool.clear(); for (int64_t nIndex : setExternalKeyPool) { - walletdb.ErasePool(nIndex); + batch.ErasePool(nIndex); } setExternalKeyPool.clear(); privateSendClient.fPrivateSendRunning = false; @@ -4413,7 +4413,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize) nTargetSize *= 2; } bool fInternal = false; - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); for (int64_t i = missingInternal + missingExternal; i--;) { if (i < missingInternal) { @@ -4424,8 +4424,8 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize) int64_t index = ++m_max_keypool_index; // TODO: implement keypools for all accounts? - CPubKey pubkey(GenerateNewKey(walletdb, 0, fInternal)); - if (!walletdb.WritePool(index, CKeyPool(pubkey, fInternal))) { + CPubKey pubkey(GenerateNewKey(batch, 0, fInternal)); + if (!batch.WritePool(index, CKeyPool(pubkey, fInternal))) { throw std::runtime_error(std::string(__func__) + ": writing generated key failed"); } @@ -4467,11 +4467,11 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fIn if(setKeyPool.empty()) return; - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); nIndex = *setKeyPool.begin(); setKeyPool.erase(nIndex); - if (!walletdb.ReadPool(nIndex, keypool)) { + if (!batch.ReadPool(nIndex, keypool)) { throw std::runtime_error(std::string(__func__) + ": read failed"); } if (!HaveKey(keypool.vchPubKey.GetID())) { @@ -4490,8 +4490,8 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fIn void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool - CWalletDB walletdb(*dbw); - if (walletdb.ErasePool(nIndex)) + WalletBatch batch(*database); + if (batch.ErasePool(nIndex)) --nKeysLeftSinceAutoBackup; if (!nWalletBackups) nKeysLeftSinceAutoBackup = 0; @@ -4525,8 +4525,8 @@ bool CWallet::GetKeyFromPool(CPubKey& result, bool internal) if (IsLocked(true)) return false; // TODO: implement keypool for all accouts? - CWalletDB walletdb(*dbw); - result = GenerateNewKey(walletdb, 0, internal); + WalletBatch batch(*database); + result = GenerateNewKey(batch, 0, internal); return true; } KeepKey(nIndex); @@ -4535,10 +4535,10 @@ bool CWallet::GetKeyFromPool(CPubKey& result, bool internal) return true; } -static int64_t GetOldestKeyInPool(const std::set& setKeyPool, CWalletDB& walletdb) { +static int64_t GetOldestKeyInPool(const std::set& setKeyPool, WalletBatch& batch) { CKeyPool keypool; int64_t nIndex = *(setKeyPool.begin()); - if (!walletdb.ReadPool(nIndex, keypool)) { + if (!batch.ReadPool(nIndex, keypool)) { throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed"); } assert(keypool.vchPubKey.IsValid()); @@ -4553,15 +4553,15 @@ int64_t CWallet::GetOldestKeyPoolTime() if (setExternalKeyPool.empty() && setInternalKeyPool.empty()) return GetTime(); - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); int64_t oldestKey = -1; // load oldest key from keypool, get time and return if (!setInternalKeyPool.empty()) { - oldestKey = std::max(GetOldestKeyInPool(setInternalKeyPool, walletdb), oldestKey); + oldestKey = std::max(GetOldestKeyInPool(setInternalKeyPool, batch), oldestKey); } if (!setExternalKeyPool.empty()) { - oldestKey = std::max(GetOldestKeyInPool(setExternalKeyPool, walletdb), oldestKey); + oldestKey = std::max(GetOldestKeyInPool(setExternalKeyPool, batch), oldestKey); } return oldestKey; } @@ -4758,16 +4758,16 @@ void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id) std::set *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool; auto it = setKeyPool->begin(); - CWalletDB walletdb(*dbw); + WalletBatch batch(*database); while (it != std::end(*setKeyPool)) { const int64_t& index = *(it); if (index > keypool_id) break; // set*KeyPool is ordered CKeyPool keypool; - if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary + if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary m_pool_key_to_index.erase(keypool.vchPubKey.GetID()); } - walletdb.ErasePool(index); + batch.ErasePool(index); LogPrintf("keypool index %d removed\n", index); it = setKeyPool->erase(it); } @@ -4970,14 +4970,14 @@ bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, co return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); - return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value); + return WalletBatch(*database).WriteDestData(EncodeDestination(dest), key, value); } bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; - return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key); + return WalletBatch(*database).EraseDestData(EncodeDestination(dest), key); } bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) @@ -5072,7 +5072,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& if (gArgs.GetBoolArg("-zapwallettxes", false)) { uiInterface.InitMessage(_("Zapping all transactions from wallet...")); - std::unique_ptr tempWallet = MakeUnique(name, CWalletDBWrapper::Create(path)); + std::unique_ptr tempWallet = MakeUnique(name, WalletDatabase::Create(path)); DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx); if (nZapWalletRet != DB_LOAD_OK) { InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile)); @@ -5086,7 +5086,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& bool fFirstRun = true; // Make a temporary wallet unique pointer so memory doesn't get leaked if // wallet creation fails. - auto temp_wallet = MakeUnique(name, CWalletDBWrapper::Create(path)); + auto temp_wallet = MakeUnique(name, WalletDatabase::Create(path)); CWallet *walletInstance = temp_wallet.get(); DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) @@ -5199,9 +5199,9 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& CBlockIndex *pindexRescan = chainActive.Genesis(); if (!gArgs.GetBoolArg("-rescan", false)) { - CWalletDB walletdb(*walletInstance->dbw); + WalletBatch batch(*walletInstance->database); CBlockLocator locator; - if (walletdb.ReadBestBlock(locator)) + if (batch.ReadBestBlock(locator)) pindexRescan = FindForkInGlobalIndex(chainActive, locator); } @@ -5244,12 +5244,12 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& } LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); walletInstance->SetBestChain(chainActive.GetLocator()); - walletInstance->dbw->IncrementUpdateCounter(); + walletInstance->database->IncrementUpdateCounter(); // Restore wallet transaction metadata after -zapwallettxes=1 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2") { - CWalletDB walletdb(*walletInstance->dbw); + WalletBatch batch(*walletInstance->database); for (const CWalletTx& wtxOld : vWtx) { @@ -5266,7 +5266,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; copyTo->nOrderPos = copyFrom->nOrderPos; - walletdb.WriteTx(*copyTo); + batch.WriteTx(*copyTo); } } } @@ -5308,7 +5308,7 @@ bool CWallet::InitAutoBackup() bool CWallet::BackupWallet(const std::string& strDest) { - return dbw->Backup(strDest); + return database->Backup(strDest); } // This should be called carefully: @@ -5371,7 +5371,7 @@ bool CWallet::AutoBackupWallet(const fs::path& wallet_path, std::string& strBack } else { // ... strWalletName file std::string strSourceFile; - CDBEnv* env = GetWalletEnv(wallet_path, strSourceFile); + BerkeleyEnvironment* env = GetWalletEnv(wallet_path, strSourceFile); fs::path sourceFile = env->Directory() / strSourceFile; fs::path backupFile = backupsDir / (strWalletName + dateTimeStr); sourceFile.make_preferred(); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index c7737142d9d3c5..5ade92223a9cf4 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -719,7 +719,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface */ bool SelectCoins(const std::vector& vAvailableCoins, const CAmount& nTargetValue, std::set& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = nullptr) const; - CWalletDB *pwalletdbEncryption; + WalletBatch *encrypted_batch; //! the current wallet version: clients below this version are not able to load the wallet int nWalletVersion; @@ -758,7 +758,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = nullptr, int posInBlock = 0); /* HD derive new child key (on internal or external chain) */ - void DeriveNewChildKey(CWalletDB &walletdb, const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/); + void DeriveNewChildKey(WalletBatch &batch, const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/); std::set setInternalKeyPool; std::set setExternalKeyPool; @@ -786,7 +786,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface std::string m_name; /** Internal database handle. */ - std::unique_ptr dbw; + std::unique_ptr database; // Used to NotifyTransactionChanged of the previous block's coinbase when // the next block comes in @@ -817,9 +817,9 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface /** Get database handle used by this wallet. Ideally this function would * not be necessary. */ - CWalletDBWrapper& GetDBHandle() + WalletDatabase& GetDBHandle() { - return *dbw; + return *database; } /** Get a name for this wallet for logging/debugging purposes. @@ -839,15 +839,15 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface unsigned int nMasterKeyMaxID; /** Construct wallet with specified name and database implementation. */ - CWallet(std::string name, std::unique_ptr dbw) : m_name(std::move(name)), dbw(std::move(dbw)) + CWallet(std::string name, std::unique_ptr database) : m_name(std::move(name)), database(std::move(database)) { SetNull(); } ~CWallet() { - delete pwalletdbEncryption; - pwalletdbEncryption = nullptr; + delete encrypted_batch; + encrypted_batch = nullptr; } void SetNull() @@ -855,7 +855,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface nWalletVersion = FEATURE_BASE; nWalletMaxVersion = FEATURE_BASE; nMasterKeyMaxID = 0; - pwalletdbEncryption = nullptr; + encrypted_batch = nullptr; nOrderPosNext = 0; nAccountingEntryNumber = 0; nNextResend = 0; @@ -961,7 +961,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface * keystore implementation * Generate a new key */ - CPubKey GenerateNewKey(CWalletDB& walletdb, uint32_t nAccountIndex, bool fInternal /*= false*/); + CPubKey GenerateNewKey(WalletBatch& batch, uint32_t nAccountIndex, bool fInternal /*= false*/); //! HaveKey implementation that also checks the mapHdPubKeys bool HaveKey(const CKeyID &address) const override; //! GetPubKey implementation that also checks the mapHdPubKeys @@ -969,12 +969,12 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface //! GetKey implementation that can derive a HD private key on the fly bool GetKey(const CKeyID &address, CKey& keyOut) const override; //! Adds a HDPubKey into the wallet(database) - bool AddHDPubKey(CWalletDB &walletdb, const CExtPubKey &extPubKey, bool fInternal); + bool AddHDPubKey(WalletBatch &batch, const CExtPubKey &extPubKey, bool fInternal); //! loads a HDPubKey into the wallets memory bool LoadHDPubKey(const CHDPubKey &hdPubKey); //! Adds a key to the store, and saves it to disk. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override; - bool AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& key, const CPubKey &pubkey); + bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey& key, const CPubKey &pubkey); //! Adds a key to the store, without saving it to disk (used by LoadWallet) bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); } //! Load metadata (used by LoadWallet) @@ -1023,7 +1023,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface * Increment the next transaction order id * @return next transaction order id */ - int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr); + int64_t IncOrderPosNext(WalletBatch *batch = nullptr); DBErrors ReorderTransactions(); bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = ""); bool GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew = false); @@ -1079,7 +1079,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface void ListAccountCreditDebit(const std::string& strAccount, std::list& entries); bool AddAccountingEntry(const CAccountingEntry&); - bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb); + bool AddAccountingEntry(const CAccountingEntry&, WalletBatch *batch); static CFeeRate minTxFee; static CFeeRate fallbackFee; @@ -1155,7 +1155,7 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface } //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower - bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false); + bool SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false); //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format) bool SetMaxVersion(int nVersion); @@ -1235,8 +1235,8 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface /* Generates a new HD chain */ void GenerateNewHDChain(); /* Set the HD chain model (chain child index counters) */ - bool SetHDChain(CWalletDB &walletdb, const CHDChain& chain, bool memonly); - bool SetCryptedHDChain(CWalletDB &walletdb, const CHDChain& chain, bool memonly); + bool SetHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly); + bool SetCryptedHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly); /** * Set the HD chain model (chain child index counters) using temporary wallet db object * which causes db flush every time these methods are used diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 7e6b7c1cf7e694..30789dc43650e9 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -23,42 +23,42 @@ #include // -// CWalletDB +// WalletBatch // -bool CWalletDB::WriteName(const std::string& strAddress, const std::string& strName) +bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName) { return WriteIC(std::make_pair(std::string("name"), strAddress), strName); } -bool CWalletDB::EraseName(const std::string& strAddress) +bool WalletBatch::EraseName(const std::string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. return EraseIC(std::make_pair(std::string("name"), strAddress)); } -bool CWalletDB::WritePurpose(const std::string& strAddress, const std::string& strPurpose) +bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose) { return WriteIC(std::make_pair(std::string("purpose"), strAddress), strPurpose); } -bool CWalletDB::ErasePurpose(const std::string& strAddress) +bool WalletBatch::ErasePurpose(const std::string& strAddress) { return EraseIC(std::make_pair(std::string("purpose"), strAddress)); } -bool CWalletDB::WriteTx(const CWalletTx& wtx) +bool WalletBatch::WriteTx(const CWalletTx& wtx) { return WriteIC(std::make_pair(std::string("tx"), wtx.GetHash()), wtx); } -bool CWalletDB::EraseTx(uint256 hash) +bool WalletBatch::EraseTx(uint256 hash) { return EraseIC(std::make_pair(std::string("tx"), hash)); } -bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) +bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) { if (!WriteIC(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) { return false; @@ -73,7 +73,7 @@ bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, c return WriteIC(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false); } -bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey, +bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey, const std::vector& vchCryptedSecret, const CKeyMetadata &keyMeta) { @@ -89,17 +89,17 @@ bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey, return true; } -bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey) +bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey) { return WriteIC(std::make_pair(std::string("mkey"), nID), kMasterKey, true); } -bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript) +bool WalletBatch::WriteCScript(const uint160& hash, const CScript& redeemScript) { return WriteIC(std::make_pair(std::string("cscript"), hash), redeemScript, false); } -bool CWalletDB::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta) +bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta) { if (!WriteIC(std::make_pair(std::string("watchmeta"), dest), keyMeta)) { return false; @@ -107,7 +107,7 @@ bool CWalletDB::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta) return WriteIC(std::make_pair(std::string("watchs"), dest), '1'); } -bool CWalletDB::EraseWatchOnly(const CScript &dest) +bool WalletBatch::EraseWatchOnly(const CScript &dest) { if (!EraseIC(std::make_pair(std::string("watchmeta"), dest))) { return false; @@ -115,60 +115,60 @@ bool CWalletDB::EraseWatchOnly(const CScript &dest) return EraseIC(std::make_pair(std::string("watchs"), dest)); } -bool CWalletDB::WriteBestBlock(const CBlockLocator& locator) +bool WalletBatch::WriteBestBlock(const CBlockLocator& locator) { WriteIC(std::string("bestblock"), CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan return WriteIC(std::string("bestblock_nomerkle"), locator); } -bool CWalletDB::ReadBestBlock(CBlockLocator& locator) +bool WalletBatch::ReadBestBlock(CBlockLocator& locator) { if (batch.Read(std::string("bestblock"), locator) && !locator.vHave.empty()) return true; return batch.Read(std::string("bestblock_nomerkle"), locator); } -bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext) +bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext) { return WriteIC(std::string("orderposnext"), nOrderPosNext); } -bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool) +bool WalletBatch::ReadPool(int64_t nPool, CKeyPool& keypool) { return batch.Read(std::make_pair(std::string("pool"), nPool), keypool); } -bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool) +bool WalletBatch::WritePool(int64_t nPool, const CKeyPool& keypool) { return WriteIC(std::make_pair(std::string("pool"), nPool), keypool); } -bool CWalletDB::ErasePool(int64_t nPool) +bool WalletBatch::ErasePool(int64_t nPool) { return EraseIC(std::make_pair(std::string("pool"), nPool)); } -bool CWalletDB::WriteMinVersion(int nVersion) +bool WalletBatch::WriteMinVersion(int nVersion) { return WriteIC(std::string("minversion"), nVersion); } -bool CWalletDB::ReadAccount(const std::string& strAccount, CAccount& account) +bool WalletBatch::ReadAccount(const std::string& strAccount, CAccount& account) { account.SetNull(); return batch.Read(std::make_pair(std::string("acc"), strAccount), account); } -bool CWalletDB::WriteAccount(const std::string& strAccount, const CAccount& account) +bool WalletBatch::WriteAccount(const std::string& strAccount, const CAccount& account) { return WriteIC(std::make_pair(std::string("acc"), strAccount), account); } -bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) +bool WalletBatch::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return WriteIC(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry); } -CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount) +CAmount WalletBatch::GetAccountCreditDebit(const std::string& strAccount) { std::list entries; ListAccountCreditDebit(strAccount, entries); @@ -180,7 +180,7 @@ CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount) return nCreditDebit; } -void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list& entries) +void WalletBatch::ListAccountCreditDebit(const std::string& strAccount, std::list& entries) { bool fAllAccounts = (strAccount == "*"); @@ -542,14 +542,14 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, return true; } -bool CWalletDB::IsKeyType(const std::string& strType) +bool WalletBatch::IsKeyType(const std::string& strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey" || strType == "hdchain" || strType == "chdchain"); } -DBErrors CWalletDB::LoadWallet(CWallet* pwallet) +DBErrors WalletBatch::LoadWallet(CWallet* pwallet) { CWalletScanState wss; bool fNoncriticalErrors = false; @@ -659,7 +659,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) return result; } -DBErrors CWalletDB::FindWalletTx(std::vector& vTxHash, std::vector& vWtx) +DBErrors WalletBatch::FindWalletTx(std::vector& vTxHash, std::vector& vWtx) { DBErrors result = DB_LOAD_OK; @@ -718,7 +718,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector& vTxHash, std::vector& vTxHashIn, std::vector& vTxHashOut) +DBErrors WalletBatch::ZapSelectTx(std::vector& vTxHashIn, std::vector& vTxHashOut) { // build list of wallet TXs and hashes std::vector vTxHash; @@ -756,7 +756,7 @@ DBErrors CWalletDB::ZapSelectTx(std::vector& vTxHashIn, std::vector& vWtx) +DBErrors WalletBatch::ZapWalletTx(std::vector& vWtx) { // build list of wallet TXs std::vector vTxHash; @@ -784,7 +784,7 @@ void MaybeCompactWalletDB() } for (CWallet* pwallet : GetWallets()) { - CWalletDBWrapper& dbh = pwallet->GetDBHandle(); + WalletDatabase& dbh = pwallet->GetDBHandle(); unsigned int nUpdateCounter = dbh.nUpdateCounter; @@ -794,7 +794,7 @@ void MaybeCompactWalletDB() } if (dbh.nLastFlushed != nUpdateCounter && GetTime() - dbh.nLastWalletUpdate >= 2) { - if (CDB::PeriodicFlush(dbh)) { + if (BerkeleyBatch::PeriodicFlush(dbh)) { dbh.nLastFlushed = nUpdateCounter; } } @@ -806,19 +806,19 @@ void MaybeCompactWalletDB() // // Try to (very carefully!) recover wallet file if there is a problem. // -bool CWalletDB::Recover(const fs::path& wallet_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& out_backup_filename) +bool WalletBatch::Recover(const fs::path& wallet_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& out_backup_filename) { - return CDB::Recover(wallet_path, callbackDataIn, recoverKVcallback, out_backup_filename); + return BerkeleyBatch::Recover(wallet_path, callbackDataIn, recoverKVcallback, out_backup_filename); } -bool CWalletDB::Recover(const fs::path& wallet_path, std::string& out_backup_filename) +bool WalletBatch::Recover(const fs::path& wallet_path, std::string& out_backup_filename) { // recover without a key filter callback // results in recovering all record types - return CWalletDB::Recover(wallet_path, nullptr, nullptr, out_backup_filename); + return WalletBatch::Recover(wallet_path, nullptr, nullptr, out_backup_filename); } -bool CWalletDB::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue) +bool WalletBatch::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue) { CWallet *dummyWallet = reinterpret_cast(callbackData); CWalletScanState dummyWss; @@ -834,39 +834,39 @@ bool CWalletDB::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDa return false; if (!fReadOK) { - LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); + LogPrintf("WARNING: WalletBatch::Recover skipping %s: %s\n", strType, strErr); return false; } return true; } -bool CWalletDB::VerifyEnvironment(const fs::path& wallet_path, std::string& errorStr) +bool WalletBatch::VerifyEnvironment(const fs::path& wallet_path, std::string& errorStr) { - return CDB::VerifyEnvironment(wallet_path, errorStr); + return BerkeleyBatch::VerifyEnvironment(wallet_path, errorStr); } -bool CWalletDB::VerifyDatabaseFile(const fs::path& wallet_path, std::string& warningStr, std::string& errorStr) +bool WalletBatch::VerifyDatabaseFile(const fs::path& wallet_path, std::string& warningStr, std::string& errorStr) { - return CDB::VerifyDatabaseFile(wallet_path, warningStr, errorStr, CWalletDB::Recover); + return BerkeleyBatch::VerifyDatabaseFile(wallet_path, warningStr, errorStr, WalletBatch::Recover); } -bool CWalletDB::WriteDestData(const std::string &address, const std::string &key, const std::string &value) +bool WalletBatch::WriteDestData(const std::string &address, const std::string &key, const std::string &value) { return WriteIC(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value); } -bool CWalletDB::EraseDestData(const std::string &address, const std::string &key) +bool WalletBatch::EraseDestData(const std::string &address, const std::string &key) { return EraseIC(std::make_pair(std::string("destdata"), std::make_pair(address, key))); } -bool CWalletDB::WriteHDChain(const CHDChain& chain) +bool WalletBatch::WriteHDChain(const CHDChain& chain) { return WriteIC(std::string("hdchain"), chain); } -bool CWalletDB::WriteCryptedHDChain(const CHDChain& chain) +bool WalletBatch::WriteCryptedHDChain(const CHDChain& chain) { if (!WriteIC(std::string("chdchain"), chain)) return false; @@ -876,7 +876,7 @@ bool CWalletDB::WriteCryptedHDChain(const CHDChain& chain) return true; } -bool CWalletDB::WriteHDPubKey(const CHDPubKey& hdPubKey, const CKeyMetadata& keyMeta) +bool WalletBatch::WriteHDPubKey(const CHDPubKey& hdPubKey, const CKeyMetadata& keyMeta) { if (!WriteIC(std::make_pair(std::string("keymeta"), hdPubKey.extPubKey.pubkey), keyMeta, false)) return false; @@ -884,27 +884,27 @@ bool CWalletDB::WriteHDPubKey(const CHDPubKey& hdPubKey, const CKeyMetadata& key return WriteIC(std::make_pair(std::string("hdpubkey"), hdPubKey.extPubKey.pubkey), hdPubKey, false); } -bool CWalletDB::TxnBegin() +bool WalletBatch::TxnBegin() { return batch.TxnBegin(); } -bool CWalletDB::TxnCommit() +bool WalletBatch::TxnCommit() { return batch.TxnCommit(); } -bool CWalletDB::TxnAbort() +bool WalletBatch::TxnAbort() { return batch.TxnAbort(); } -bool CWalletDB::ReadVersion(int& nVersion) +bool WalletBatch::ReadVersion(int& nVersion) { return batch.ReadVersion(nVersion); } -bool CWalletDB::WriteVersion(int nVersion) +bool WalletBatch::WriteVersion(int nVersion) { return batch.WriteVersion(nVersion); } diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h index 2de59847ae387f..695cf78c2a7f19 100644 --- a/src/wallet/walletdb.h +++ b/src/wallet/walletdb.h @@ -20,15 +20,15 @@ /** * Overview of wallet database classes: * - * - CDBEnv is an environment in which the database exists (has no analog in dbwrapper.h) - * - CWalletDBWrapper represents a wallet database (similar to CDBWrapper in dbwrapper.h) - * - CDB is a low-level database transaction (similar to CDBBatch in dbwrapper.h) - * - CWalletDB is a modifier object for the wallet, and encapsulates a database + * - BerkeleyEnvironment is an environment in which the database exists (has no analog in dbwrapper.h) + * - WalletDatabase represents a wallet database (similar to CDBWrapper in dbwrapper.h) + * - BerkeleyBatch is a low-level database transaction (similar to CDBBatch in dbwrapper.h) + * - WalletBatch is a modifier object for the wallet, and encapsulates a database * transaction as well as methods to act on the database (no analog in * dbwrapper.h) * - * The latter two are named confusingly, in contrast to what the names CDB - * and CWalletDB suggest they are transient transaction objects and don't + * The latter two are named confusingly, in contrast to what the names BerkeleyBatch + * and WalletBatch suggest they are transient transaction objects and don't * represent the database itself. */ @@ -45,6 +45,12 @@ class CWalletTx; class uint160; class uint256; +/** Backend-agnostic database type. */ +using WalletDatabase = BerkeleyDatabase; + +/** Backend-agnostic database type. */ +using WalletDatabase = BerkeleyDatabase; + /** Error statuses for the wallet database */ enum DBErrors { @@ -93,7 +99,7 @@ class CKeyMetadata * database. It will be committed when the object goes out of scope. * Optionally (on by default) it will flush to disk as well. */ -class CWalletDB +class WalletBatch { private: template @@ -102,7 +108,7 @@ class CWalletDB if (!batch.Write(key, value, fOverwrite)) { return false; } - m_dbw.IncrementUpdateCounter(); + m_database.IncrementUpdateCounter(); return true; } @@ -112,18 +118,18 @@ class CWalletDB if (!batch.Erase(key)) { return false; } - m_dbw.IncrementUpdateCounter(); + m_database.IncrementUpdateCounter(); return true; } public: - explicit CWalletDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool _fFlushOnClose = true) : - batch(dbw, pszMode, _fFlushOnClose), - m_dbw(dbw) + explicit WalletBatch(WalletDatabase& database, const char* pszMode = "r+", bool _fFlushOnClose = true) : + batch(database, pszMode, _fFlushOnClose), + m_database(database) { } - CWalletDB(const CWalletDB&) = delete; - CWalletDB& operator=(const CWalletDB&) = delete; + WalletBatch(const WalletBatch&) = delete; + WalletBatch& operator=(const WalletBatch&) = delete; bool WriteName(const std::string& strAddress, const std::string& strName); bool EraseName(const std::string& strAddress); @@ -201,8 +207,8 @@ class CWalletDB //! Write wallet version bool WriteVersion(int nVersion); private: - CDB batch; - CWalletDBWrapper& m_dbw; + BerkeleyBatch batch; + WalletDatabase& m_database; }; //! Compacts BDB state so that wallet.dat is self-contained (if there are changes)