29 const std::string &filename, Db &
db,
35 int ret =
db.get_mpf()->get_fileid(fileid.
value);
37 throw std::runtime_error(
38 strprintf(
"BerkeleyDatabase: Can't open database %s (get_fileid "
44 if (fileid == item.second && &fileid != &item.second) {
45 throw std::runtime_error(
46 strprintf(
"BerkeleyDatabase: Can't open database %s "
47 "(duplicates fileid %s "
49 filename,
HexStr(item.second.value), item.first));
57 std::map<std::string, std::weak_ptr<BerkeleyEnvironment>>
77 std::shared_ptr<BerkeleyEnvironment>
83 std::weak_ptr<BerkeleyEnvironment>());
84 if (inserted.second) {
85 auto env = std::make_shared<BerkeleyEnvironment>(env_directory);
86 inserted.first->second = env;
89 return inserted.first->second.lock();
107 database.
m_db->close(0);
108 database.
m_db.reset();
112 FILE *error_file =
nullptr;
113 dbenv->get_errfile(&error_file);
115 int ret =
dbenv->close(0);
117 LogPrintf(
"BerkeleyEnvironment::Close: Error %d closing database "
119 ret, DbEnv::strerror(ret));
122 DbEnv(uint32_t(0)).remove(
strPath.c_str(), 0);
133 dbenv.reset(
new DbEnv(DB_CXX_NO_EXCEPTIONS));
157 LogPrintf(
"Cannot obtain a lock on wallet directory %s. Another "
158 "instance of bitcoin may be using it.\n",
160 err =
strprintf(
_(
"Error initializing wallet database environment %s!"),
165 fs::path pathLogDir = pathIn /
"database";
167 fs::path pathErrorFile = pathIn /
"db.log";
168 LogPrintf(
"BerkeleyEnvironment::Open: LogDir=%s ErrorFile=%s\n",
171 unsigned int nEnvFlags = 0;
173 nEnvFlags |= DB_PRIVATE;
178 dbenv->set_cachesize(0, 0x100000, 1);
179 dbenv->set_lg_bsize(0x10000);
180 dbenv->set_lg_max(1048576);
181 dbenv->set_lk_max_locks(40000);
182 dbenv->set_lk_max_objects(40000);
185 dbenv->set_flags(DB_AUTO_COMMIT, 1);
186 dbenv->set_flags(DB_TXN_WRITE_NOSYNC, 1);
187 dbenv->log_set_config(DB_LOG_AUTO_REMOVE, 1);
190 DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL |
191 DB_INIT_TXN | DB_THREAD | DB_RECOVER | nEnvFlags,
194 LogPrintf(
"BerkeleyEnvironment::Open: Error %d opening database "
196 ret, DbEnv::strerror(ret));
197 int ret2 =
dbenv->close(0);
199 LogPrintf(
"BerkeleyEnvironment::Open: Error %d closing failed "
200 "database environment: %s\n",
201 ret2, DbEnv::strerror(ret2));
204 err =
strprintf(
_(
"Error initializing wallet database environment %s!"),
206 if (ret == DB_RUNRECOVERY) {
208 _(
"This error could occur if this wallet was not shutdown "
209 "cleanly and was last loaded using a build with a newer "
210 "version of Berkeley DB. If so, please use the software "
211 "that last loaded this wallet");
227 dbenv->set_cachesize(1, 0, 1);
228 dbenv->set_lg_bsize(10485760 * 4);
229 dbenv->set_lg_max(10485760);
230 dbenv->set_lk_max_locks(10000);
231 dbenv->set_lk_max_objects(10000);
232 dbenv->set_flags(DB_AUTO_COMMIT, 1);
233 dbenv->log_set_config(DB_LOG_IN_MEMORY, 1);
236 DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL |
237 DB_INIT_TXN | DB_THREAD | DB_PRIVATE,
240 throw std::runtime_error(
241 strprintf(
"BerkeleyEnvironment::MakeMock: Error %d opening "
242 "database environment.",
251 m_dbt.set_flags(DB_DBT_MALLOC);
257 if (m_dbt.get_data() !=
nullptr) {
263 if (m_dbt.get_flags() & DB_DBT_MALLOC) {
264 free(m_dbt.get_data());
270 return m_dbt.get_data();
274 return m_dbt.get_size();
277 BerkeleyBatch::SafeDbt::operator Dbt *() {
296 int result =
db.verify(
strFile.c_str(),
nullptr,
nullptr, 0);
299 strprintf(
_(
"%s corrupt. Try using the wallet tool "
300 "bitcoin-wallet to salvage or restoring a backup."),
310 dbenv->txn_checkpoint(0, 0, 0);
314 dbenv->lsn_reset(
strFile.c_str(), 0);
329 bool fFlushOnCloseIn)
339 if (!
Exists(std::string(
"version"))) {
348 unsigned int nFlags = DB_THREAD | DB_CREATE;
353 if (!
env->Open(open_err)) {
354 throw std::runtime_error(
355 "BerkeleyDatabase: Failed to open database environment.");
358 if (
m_db ==
nullptr) {
360 std::unique_ptr<Db> pdb_temp =
361 std::make_unique<Db>(
env->dbenv.get(), 0);
363 bool fMockDb =
env->IsMock();
365 DbMpoolFile *mpf = pdb_temp->get_mpf();
366 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
369 "BerkeleyDatabase: Failed to configure for no "
370 "temp file backing for database %s",
375 ret = pdb_temp->open(
377 fMockDb ?
nullptr :
strFile.c_str(),
378 fMockDb ?
strFile.c_str() :
"main",
385 "BerkeleyDatabase: Error %d, can't open database %s", ret,
395 m_db.reset(pdb_temp.release());
406 unsigned int nMinutes = 0;
454 database.
m_db->close(0);
455 database.
m_db.reset();
462 std::unique_lock<RecursiveMutex> lock(cs_db);
465 if (
db.second.get().m_refcount > 0) {
477 for (
const std::string &filename :
filenames) {
498 bool fSuccess =
true;
500 std::string strFileRes =
strFile +
".rewrite";
503 std::unique_ptr<Db> pdbCopy =
504 std::make_unique<Db>(
env->dbenv.get(), 0);
506 int ret = pdbCopy->open(
nullptr,
513 LogPrintf(
"BerkeleyBatch::Rewrite: Can't create "
514 "database file %s\n",
519 if (
db.StartCursor()) {
525 db.ReadAtCursor(ssKey, ssValue, complete);
534 strncmp((
const char *)ssKey.
data(), pszSkip,
535 std::min(ssKey.
size(),
536 strlen(pszSkip))) == 0) {
539 if (strncmp((
const char *)ssKey.
data(),
540 "\x07version", 8) == 0) {
545 Dbt datKey(ssKey.
data(), ssKey.
size());
546 Dbt datValue(ssValue.
data(), ssValue.
size());
547 int ret2 = pdbCopy->put(
nullptr, &datKey, &datValue,
558 if (pdbCopy->close(0)) {
566 Db dbA(
env->dbenv.get(), 0);
567 if (dbA.remove(
strFile.c_str(),
nullptr, 0)) {
570 Db dbB(
env->dbenv.get(), 0);
571 if (dbB.rename(strFileRes.c_str(),
nullptr,
strFile.c_str(),
577 LogPrintf(
"BerkeleyBatch::Rewrite: Failed to rewrite "
578 "database file %s\n",
592 strPath, fShutdown ?
"true" :
"false",
599 bool no_dbs_accessed =
true;
601 std::string strFile = db_it.first;
602 int nRefCount = db_it.second.get().m_refcount;
608 "BerkeleyEnvironment::Flush: Flushing %s (refcount = %d)...\n",
610 if (nRefCount == 0) {
614 "BerkeleyEnvironment::Flush: %s checkpoint\n",
616 dbenv->txn_checkpoint(0, 0, 0);
618 "BerkeleyEnvironment::Flush: %s detach\n", strFile);
620 dbenv->lsn_reset(strFile.c_str(), 0);
623 "BerkeleyEnvironment::Flush: %s closed\n", strFile);
626 no_dbs_accessed =
false;
630 "BerkeleyEnvironment::Flush: Flush(%s)%s took %15dms\n",
631 fShutdown ?
"true" :
"false",
636 if (no_dbs_accessed) {
637 dbenv->log_archive(&listp, DB_ARCH_REMOVE);
655 for (
auto &it :
env->m_databases) {
656 if (it.second.get().m_refcount > 0) {
692 if (fs::is_directory(pathDest)) {
698 fs::equivalent(pathSrc, pathDest)) {
699 LogPrintf(
"cannot backup to wallet source file %s\n",
705 fs::copy_options::overwrite_existing);
709 }
catch (
const fs::filesystem_error &e) {
751 int ret =
m_cursor->get(datKey, datValue, DB_NEXT);
752 if (ret == DB_NOTFOUND) {
757 }
else if (datKey.
get_data() ==
nullptr || datValue.
get_data() ==
nullptr) {
810 return DbEnv::version(
nullptr,
nullptr,
nullptr);
818 SafeDbt datKey(key.data(), key.size());
822 if (ret == 0 && datValue.
get_data() !=
nullptr) {
836 assert(!
"Write called on database in read-only mode");
839 SafeDbt datKey(key.data(), key.size());
841 SafeDbt datValue(value.data(), value.size());
844 pdb->put(
activeTxn, datKey, datValue, (overwrite ? 0 : DB_NOOVERWRITE));
853 assert(!
"Erase called on database in read-only mode");
856 SafeDbt datKey(key.data(), key.size());
859 return (ret == 0 || ret == DB_NOTFOUND);
867 SafeDbt datKey(key.data(), key.size());
886 env->m_db_in_use.notify_all();
890 std::unique_ptr<DatabaseBatch>
892 return std::make_unique<BerkeleyBatch>(*
this,
false, flush_on_close);
897 std::string data_filename;
902 std::unique_ptr<BerkeleyDatabase>
905 std::unique_ptr<BerkeleyDatabase>
db;
909 std::string data_filename;
910 std::shared_ptr<BerkeleyEnvironment> env =
912 if (env->m_databases.count(data_filename)) {
914 "Refusing to load database. Data file '%s' is already loaded.",
919 db = std::make_unique<BerkeleyDatabase>(std::move(env),
920 std::move(data_filename));
std::unique_ptr< BerkeleyDatabase > MakeBerkeleyDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Return object giving access to Berkeley database at specified path.
bool ExistsBerkeleyDatabase(const fs::path &path)
Check if Berkeley database exists at specified path.
std::string BerkeleyDatabaseVersion()
std::shared_ptr< BerkeleyEnvironment > GetWalletEnv(const fs::path &wallet_path, std::string &database_filename)
Get BerkeleyEnvironment and database filename given a wallet path.
static const unsigned int DEFAULT_WALLET_DBLOGSIZE
static const bool DEFAULT_WALLET_PRIVDB
bool IsBerkeleyBtree(const fs::path &path)
Check format of database file.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
RAII class that automatically cleanses its data on destruction.
uint32_t get_size() const
const void * get_data() const
RAII class that provides access to a Berkeley database.
bool TxnCommit() override
bool WriteKey(CDataStream &&key, CDataStream &&value, bool overwrite=true) override
bool ReadKey(CDataStream &&key, CDataStream &value) override
bool StartCursor() override
void CloseCursor() override
BerkeleyBatch(BerkeleyDatabase &database, const bool fReadOnly, bool fFlushOnCloseIn=true)
BerkeleyEnvironment * env
bool EraseKey(CDataStream &&key) override
~BerkeleyBatch() override
BerkeleyDatabase & m_database
bool HasKey(CDataStream &&key) override
bool ReadAtCursor(CDataStream &ssKey, CDataStream &ssValue, bool &complete) override
An instance of this class represents one database.
std::shared_ptr< BerkeleyEnvironment > env
Pointer to shared database environment.
void IncrementUpdateCounter() override
void ReloadDbEnv() override
std::unique_ptr< DatabaseBatch > MakeBatch(bool flush_on_close=true) override
Make a BerkeleyBatch connected to this database.
~BerkeleyDatabase() override
bool Rewrite(const char *pszSkip=nullptr) override
Rewrite the entire database on disk, with the exception of key pszSkip if non-zero.
void AddRef() override
Indicate the a new database user has began using the database.
void Flush() override
Make sure all changes are flushed to database file.
void Open() override
Open the database if it is not already opened.
bool PeriodicFlush() override
flush the wallet passively (TRY_LOCK) ideal to be called periodically
void RemoveRef() override
Indicate that database user has stopped using the database and that it could be flushed or closed.
void Close() override
Flush to the database file and close the database.
std::unique_ptr< Db > m_db
Database pointer.
bool Verify(bilingual_str &error)
Verifies the environment and database file.
bool Backup(const std::string &strDest) const override
Back up the entire database to a file.
std::unordered_map< std::string, WalletDatabaseFileId > m_fileids
fs::path Directory() const
std::map< std::string, std::reference_wrapper< BerkeleyDatabase > > m_databases
bool Open(bilingual_str &error)
DbTxn * TxnBegin(int flags=DB_TXN_WRITE_NOSYNC)
std::unique_ptr< DbEnv > dbenv
std::condition_variable_any m_db_in_use
void CheckpointLSN(const std::string &strFile)
void Flush(bool fShutdown)
BerkeleyEnvironment()
Construct an in-memory mock Berkeley environment for testing.
void CloseDb(const std::string &strFile)
Double ended buffer combining vector and stream-like interfaces.
void write(Span< const value_type > src)
bool Write(const K &key, const T &value, bool fOverwrite=true)
bool Exists(const K &key)
std::atomic< unsigned int > nUpdateCounter
std::atomic< int > m_refcount
Counts the number of active database users to be sure that the database is not closed while someone i...
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
#define LogPrint(category,...)
Filesystem operations and types.
static auto quoted(const std::string &s)
static bool exists(const path &p)
static bool copy_file(const path &from, const path &to, copy_options options)
static std::string PathToString(const path &path)
Convert path object to byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
FILE * fopen(const fs::path &p, const char *mode)
std::string get_filesystem_error_message(const fs::filesystem_error &e)
const std::byte * BytePtr(const void *data)
Convert a data pointer to a std::byte data pointer.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool operator==(const WalletDatabaseFileId &rhs) const
uint8_t value[DB_FILE_ID_LEN]
#define AssertLockNotHeld(cs)
#define TRY_LOCK(cs, name)
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
bool error(const char *fmt, const Args &...args)
int64_t GetTimeMillis()
Returns the system time (not mockable)
void UninterruptibleSleep(const std::chrono::microseconds &n)
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
static const char * filenames[]
void SplitWalletPath(const fs::path &wallet_path, fs::path &env_directory, std::string &database_filename)