// Copyright (c) 2016-2024 The Hush developers // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html #include #include #include "wallet/db.h" namespace { // A fresh environment in a temp dir with one committed record in "wallet.dat", so database/ holds a log file. class WalletDbEnv : public ::testing::Test { protected: boost::filesystem::path dir; CDBEnv env; void SetUp() override { dir = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("dbenv-%%%%%%%%"); boost::filesystem::create_directories(dir); ASSERT_TRUE(env.Open(dir)); Db db(env.dbenv, DB_CXX_NO_EXCEPTIONS); ASSERT_EQ(0, db.open(NULL, "wallet.dat", "main", DB_BTREE, DB_CREATE | DB_AUTO_COMMIT, 0)); char k[] = "key", v[] = "value"; Dbt key(k, sizeof k), value(v, sizeof v); ASSERT_EQ(0, db.put(NULL, &key, &value, 0)); ASSERT_EQ(0, db.close(0)); ASSERT_TRUE(boost::filesystem::exists(Log())); } void TearDown() override { env.Close(); boost::system::error_code ec; boost::filesystem::remove_all(dir, ec); } boost::filesystem::path Log() const { return dir / "database" / "log.0000000001"; } }; } // namespace TEST_F(WalletDbEnv, CleanShutdownRemovesTheLogs) { env.Flush(true); EXPECT_FALSE(boost::filesystem::exists(dir / "database")); } // BDB0060 PANIC (a page write failed, e.g. through an fd closed behind BDB's back): the logs may hold committed // changes wallet.dat never got, and the next start's DB_RECOVER needs them. TEST_F(WalletDbEnv, PanickedEnvironmentKeepsTheLogs) { ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1)); env.Flush(true); EXPECT_TRUE(boost::filesystem::exists(Log())); } TEST_F(WalletDbEnv, FailedCheckpointKeepsTheLogs) { env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails env.Flush(true); EXPECT_TRUE(boost::filesystem::exists(Log())); } // The shutdown wallet save asks before writing: a failed flush or a panicked environment means the logs are what // recovery needs, and a large write into it would fail or make things worse. TEST_F(WalletDbEnv, HealthyUntilAFlushFailsOrTheEnvironmentPanics) { EXPECT_TRUE(env.IsHealthy()); env.Flush(false); EXPECT_TRUE(env.IsHealthy()); ASSERT_EQ(0, env.dbenv->set_flags(DB_PANIC_ENVIRONMENT, 1)); EXPECT_FALSE(env.IsHealthy()); } TEST_F(WalletDbEnv, UnhealthyAfterAFailedCheckpoint) { env.CheckpointLSN("no-such-file.dat"); // lsn_reset fails EXPECT_FALSE(env.IsHealthy()); } TEST(WalletDbEnvNotOpen, NotOpenIsHealthy) { CDBEnv env; EXPECT_TRUE(env.IsHealthy()); }