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) 2011 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#ifndef STORAGE_LEVELDB_DB_DB_IMPL_H_6#define STORAGE_LEVELDB_DB_DB_IMPL_H_8#include <atomic>9#include <deque>10#include <set>11#include <string>13#include "db/dbformat.h"14#include "db/log_writer.h"15#include "db/snapshot.h"16#include "leveldb/db.h"17#include "leveldb/env.h"18#include "port/port.h"19#include "port/thread_annotations.h"21namespace leveldb {23class MemTable;24class TableCache;25class Version;26class VersionEdit;27class VersionSet;29class DBImpl : public DB {30public:31DBImpl(const Options& options, const std::string& dbname);33DBImpl(const DBImpl&) = delete;34DBImpl& operator=(const DBImpl&) = delete;36~DBImpl() override;38// Implementations of the DB interface39Status Put(const WriteOptions&, const Slice& key,40const Slice& value) override;41Status Delete(const WriteOptions&, const Slice& key) override;42Status Write(const WriteOptions& options, WriteBatch* updates) override;43Status Get(const ReadOptions& options, const Slice& key,44std::string* value) override;45Iterator* NewIterator(const ReadOptions&) override;46const Snapshot* GetSnapshot() override;47void ReleaseSnapshot(const Snapshot* snapshot) override;48bool GetProperty(const Slice& property, std::string* value) override;49void GetApproximateSizes(const Range* range, int n, uint64_t* sizes) override;50void CompactRange(const Slice* begin, const Slice* end) override;52// Extra methods (for testing) that are not in the public DB interface54// Compact any files in the named level that overlap [*begin,*end]55void TEST_CompactRange(int level, const Slice* begin, const Slice* end);57// Force current memtable contents to be compacted.58Status TEST_CompactMemTable();60// Return an internal iterator over the current state of the database.61// The keys of this iterator are internal keys (see format.h).62// The returned iterator should be deleted when no longer needed.63Iterator* TEST_NewInternalIterator();65// Return the maximum overlapping data (in bytes) at next level for any66// file at a level >= 1.67int64_t TEST_MaxNextLevelOverlappingBytes();69// Record a sample of bytes read at the specified internal key.70// Samples are taken approximately once every config::kReadBytesPeriod71// bytes.72void RecordReadSample(Slice key);74private:75friend class DB;76struct CompactionState;77struct Writer;79// Information for a manual compaction80struct ManualCompaction {81int level;82bool done;83const InternalKey* begin; // null means beginning of key range84const InternalKey* end; // null means end of key range85InternalKey tmp_storage; // Used to keep track of compaction progress86};88// Per level compaction stats. stats_[level] stores the stats for89// compactions that produced data for the specified "level".90struct CompactionStats {91CompactionStats() : micros(0), bytes_read(0), bytes_written(0) {}93void Add(const CompactionStats& c) {94this->micros += c.micros;95this->bytes_read += c.bytes_read;96this->bytes_written += c.bytes_written;97}99int64_t micros;100int64_t bytes_read;101int64_t bytes_written;102};104Iterator* NewInternalIterator(const ReadOptions&,105SequenceNumber* latest_snapshot,106uint32_t* seed);108Status NewDB();110// Recover the descriptor from persistent storage. May do a significant111// amount of work to recover recently logged updates. Any changes to112// be made to the descriptor are added to *edit.113Status Recover(VersionEdit* edit, bool* save_manifest)114EXCLUSIVE_LOCKS_REQUIRED(mutex_);116void MaybeIgnoreError(Status* s) const;118// Delete any unneeded files and stale in-memory entries.119void DeleteObsoleteFiles() EXCLUSIVE_LOCKS_REQUIRED(mutex_);121// Compact the in-memory write buffer to disk. Switches to a new122// log-file/memtable and writes a new descriptor iff successful.123// Errors are recorded in bg_error_.124void CompactMemTable() EXCLUSIVE_LOCKS_REQUIRED(mutex_);126Status RecoverLogFile(uint64_t log_number, bool last_log, bool* save_manifest,127VersionEdit* edit, SequenceNumber* max_sequence)128EXCLUSIVE_LOCKS_REQUIRED(mutex_);130Status WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base)131EXCLUSIVE_LOCKS_REQUIRED(mutex_);133Status MakeRoomForWrite(bool force /* compact even if there is room? */)134EXCLUSIVE_LOCKS_REQUIRED(mutex_);135WriteBatch* BuildBatchGroup(Writer** last_writer)136EXCLUSIVE_LOCKS_REQUIRED(mutex_);138void RecordBackgroundError(const Status& s);140void MaybeScheduleCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);141static void BGWork(void* db);142void BackgroundCall();143void BackgroundCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);144void CleanupCompaction(CompactionState* compact)145EXCLUSIVE_LOCKS_REQUIRED(mutex_);146Status DoCompactionWork(CompactionState* compact)147EXCLUSIVE_LOCKS_REQUIRED(mutex_);149Status OpenCompactionOutputFile(CompactionState* compact);150Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input);151Status InstallCompactionResults(CompactionState* compact)152EXCLUSIVE_LOCKS_REQUIRED(mutex_);154const Comparator* user_comparator() const {155return internal_comparator_.user_comparator();156}158// Constant after construction159Env* const env_;160const InternalKeyComparator internal_comparator_;161const InternalFilterPolicy internal_filter_policy_;162const Options options_; // options_.comparator == &internal_comparator_163const bool owns_info_log_;164const bool owns_cache_;165const std::string dbname_;167// table_cache_ provides its own synchronization168TableCache* const table_cache_;170// Lock over the persistent DB state. Non-null iff successfully acquired.171FileLock* db_lock_;173// State below is protected by mutex_174port::Mutex mutex_;175std::atomic<bool> shutting_down_;176port::CondVar background_work_finished_signal_ GUARDED_BY(mutex_);177MemTable* mem_;178MemTable* imm_ GUARDED_BY(mutex_); // Memtable being compacted179std::atomic<bool> has_imm_; // So bg thread can detect non-null imm_180WritableFile* logfile_;181uint64_t logfile_number_ GUARDED_BY(mutex_);182log::Writer* log_;183uint32_t seed_ GUARDED_BY(mutex_); // For sampling.185// Queue of writers.186std::deque<Writer*> writers_ GUARDED_BY(mutex_);187WriteBatch* tmp_batch_ GUARDED_BY(mutex_);189SnapshotList snapshots_ GUARDED_BY(mutex_);191// Set of table files to protect from deletion because they are192// part of ongoing compactions.193std::set<uint64_t> pending_outputs_ GUARDED_BY(mutex_);195// Has a background compaction been scheduled or is running?196bool background_compaction_scheduled_ GUARDED_BY(mutex_);198ManualCompaction* manual_compaction_ GUARDED_BY(mutex_);200VersionSet* const versions_ GUARDED_BY(mutex_);202// Have we encountered a background error in paranoid mode?203Status bg_error_ GUARDED_BY(mutex_);205CompactionStats stats_[config::kNumLevels] GUARDED_BY(mutex_);206};208// Sanitize db options. The caller should delete result.info_log if209// it is not equal to src.info_log.210Options SanitizeOptions(const std::string& db,211const InternalKeyComparator* icmp,212const InternalFilterPolicy* ipolicy,213const Options& src);215} // namespace leveldb217#endif // STORAGE_LEVELDB_DB_DB_IMPL_H_
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.