Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2014 The LevelDB Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file. See the AUTHORS file for names of contributors.5#include "db/db_impl.h"6#include "db/filename.h"7#include "db/version_set.h"8#include "db/write_batch_internal.h"9#include "leveldb/db.h"10#include "leveldb/env.h"11#include "leveldb/write_batch.h"12#include "util/logging.h"13#include "util/testharness.h"14#include "util/testutil.h"16namespace leveldb {18class RecoveryTest {19public:20RecoveryTest() : env_(Env::Default()), db_(nullptr) {21dbname_ = test::TmpDir() + "/recovery_test";22DestroyDB(dbname_, Options());23Open();24}26~RecoveryTest() {27Close();28DestroyDB(dbname_, Options());29}31DBImpl* dbfull() const { return reinterpret_cast<DBImpl*>(db_); }32Env* env() const { return env_; }34bool CanAppend() {35WritableFile* tmp;36Status s = env_->NewAppendableFile(CurrentFileName(dbname_), &tmp);37delete tmp;38if (s.IsNotSupportedError()) {39return false;40} else {41return true;42}43}45void Close() {46delete db_;47db_ = nullptr;48}50Status OpenWithStatus(Options* options = nullptr) {51Close();52Options opts;53if (options != nullptr) {54opts = *options;55} else {56opts.reuse_logs = true; // TODO(sanjay): test both ways57opts.create_if_missing = true;58}59if (opts.env == nullptr) {60opts.env = env_;61}62return DB::Open(opts, dbname_, &db_);63}65void Open(Options* options = nullptr) {66ASSERT_OK(OpenWithStatus(options));67ASSERT_EQ(1, NumLogs());68}70Status Put(const std::string& k, const std::string& v) {71return db_->Put(WriteOptions(), k, v);72}74std::string Get(const std::string& k, const Snapshot* snapshot = nullptr) {75std::string result;76Status s = db_->Get(ReadOptions(), k, &result);77if (s.IsNotFound()) {78result = "NOT_FOUND";79} else if (!s.ok()) {80result = s.ToString();81}82return result;83}85std::string ManifestFileName() {86std::string current;87ASSERT_OK(ReadFileToString(env_, CurrentFileName(dbname_), ¤t));88size_t len = current.size();89if (len > 0 && current[len - 1] == '\n') {90current.resize(len - 1);91}92return dbname_ + "/" + current;93}95std::string LogName(uint64_t number) { return LogFileName(dbname_, number); }97size_t DeleteLogFiles() {98// Linux allows unlinking open files, but Windows does not.99// Closing the db allows for file deletion.100Close();101std::vector<uint64_t> logs = GetFiles(kLogFile);102for (size_t i = 0; i < logs.size(); i++) {103ASSERT_OK(env_->DeleteFile(LogName(logs[i]))) << LogName(logs[i]);104}105return logs.size();106}108void DeleteManifestFile() { ASSERT_OK(env_->DeleteFile(ManifestFileName())); }110uint64_t FirstLogFile() { return GetFiles(kLogFile)[0]; }112std::vector<uint64_t> GetFiles(FileType t) {113std::vector<std::string> filenames;114ASSERT_OK(env_->GetChildren(dbname_, &filenames));115std::vector<uint64_t> result;116for (size_t i = 0; i < filenames.size(); i++) {117uint64_t number;118FileType type;119if (ParseFileName(filenames[i], &number, &type) && type == t) {120result.push_back(number);121}122}123return result;124}126int NumLogs() { return GetFiles(kLogFile).size(); }128int NumTables() { return GetFiles(kTableFile).size(); }130uint64_t FileSize(const std::string& fname) {131uint64_t result;132ASSERT_OK(env_->GetFileSize(fname, &result)) << fname;133return result;134}136void CompactMemTable() { dbfull()->TEST_CompactMemTable(); }138// Directly construct a log file that sets key to val.139void MakeLogFile(uint64_t lognum, SequenceNumber seq, Slice key, Slice val) {140std::string fname = LogFileName(dbname_, lognum);141WritableFile* file;142ASSERT_OK(env_->NewWritableFile(fname, &file));143log::Writer writer(file);144WriteBatch batch;145batch.Put(key, val);146WriteBatchInternal::SetSequence(&batch, seq);147ASSERT_OK(writer.AddRecord(WriteBatchInternal::Contents(&batch)));148ASSERT_OK(file->Flush());149delete file;150}152private:153std::string dbname_;154Env* env_;155DB* db_;156};158TEST(RecoveryTest, ManifestReused) {159if (!CanAppend()) {160fprintf(stderr, "skipping test because env does not support appending\n");161return;162}163ASSERT_OK(Put("foo", "bar"));164Close();165std::string old_manifest = ManifestFileName();166Open();167ASSERT_EQ(old_manifest, ManifestFileName());168ASSERT_EQ("bar", Get("foo"));169Open();170ASSERT_EQ(old_manifest, ManifestFileName());171ASSERT_EQ("bar", Get("foo"));172}174TEST(RecoveryTest, LargeManifestCompacted) {175if (!CanAppend()) {176fprintf(stderr, "skipping test because env does not support appending\n");177return;178}179ASSERT_OK(Put("foo", "bar"));180Close();181std::string old_manifest = ManifestFileName();183// Pad with zeroes to make manifest file very big.184{185uint64_t len = FileSize(old_manifest);186WritableFile* file;187ASSERT_OK(env()->NewAppendableFile(old_manifest, &file));188std::string zeroes(3 * 1048576 - static_cast<size_t>(len), 0);189ASSERT_OK(file->Append(zeroes));190ASSERT_OK(file->Flush());191delete file;192}194Open();195std::string new_manifest = ManifestFileName();196ASSERT_NE(old_manifest, new_manifest);197ASSERT_GT(10000, FileSize(new_manifest));198ASSERT_EQ("bar", Get("foo"));200Open();201ASSERT_EQ(new_manifest, ManifestFileName());202ASSERT_EQ("bar", Get("foo"));203}205TEST(RecoveryTest, NoLogFiles) {206ASSERT_OK(Put("foo", "bar"));207ASSERT_EQ(1, DeleteLogFiles());208Open();209ASSERT_EQ("NOT_FOUND", Get("foo"));210Open();211ASSERT_EQ("NOT_FOUND", Get("foo"));212}214TEST(RecoveryTest, LogFileReuse) {215if (!CanAppend()) {216fprintf(stderr, "skipping test because env does not support appending\n");217return;218}219for (int i = 0; i < 2; i++) {220ASSERT_OK(Put("foo", "bar"));221if (i == 0) {222// Compact to ensure current log is empty223CompactMemTable();224}225Close();226ASSERT_EQ(1, NumLogs());227uint64_t number = FirstLogFile();228if (i == 0) {229ASSERT_EQ(0, FileSize(LogName(number)));230} else {231ASSERT_LT(0, FileSize(LogName(number)));232}233Open();234ASSERT_EQ(1, NumLogs());235ASSERT_EQ(number, FirstLogFile()) << "did not reuse log file";236ASSERT_EQ("bar", Get("foo"));237Open();238ASSERT_EQ(1, NumLogs());239ASSERT_EQ(number, FirstLogFile()) << "did not reuse log file";240ASSERT_EQ("bar", Get("foo"));241}242}244TEST(RecoveryTest, MultipleMemTables) {245// Make a large log.246const int kNum = 1000;247for (int i = 0; i < kNum; i++) {248char buf[100];249snprintf(buf, sizeof(buf), "%050d", i);250ASSERT_OK(Put(buf, buf));
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.