txdb.h raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-present The Bitcoin Core developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #ifndef BITCOIN_TXDB_H
   7  #define BITCOIN_TXDB_H
   8  
   9  #include <coins.h>
  10  #include <dbwrapper.h>
  11  #include <kernel/caches.h>
  12  #include <kernel/cs_main.h>
  13  #include <sync.h>
  14  #include <util/fs.h>
  15  
  16  #include <cstddef>
  17  #include <cstdint>
  18  #include <future>
  19  #include <memory>
  20  #include <optional>
  21  #include <string>
  22  #include <vector>
  23  
  24  class COutPoint;
  25  class uint256;
  26  
  27  //! User-controlled performance and debug options.
  28  struct CoinsViewOptions {
  29      //! Maximum database write batch size in bytes.
  30      uint64_t batch_write_bytes{DEFAULT_DB_CACHE_BATCH};
  31      //! If non-zero, randomly exit when the database is flushed with (1/ratio) probability.
  32      int simulate_crash_ratio{0};
  33  };
  34  
  35  /** CCoinsView backed by the coin database (chainstate/) */
  36  class CCoinsViewDB final : public CCoinsView
  37  {
  38  protected:
  39      DBParams m_db_params;
  40      CoinsViewOptions m_options;
  41      //! Prevents CompactFull() from using m_db while ResizeCache() replaces it.
  42      Mutex m_db_mutex;
  43      std::unique_ptr<CDBWrapper> m_db;
  44      std::shared_future<void> m_compaction;
  45  public:
  46      explicit CCoinsViewDB(DBParams db_params, CoinsViewOptions options);
  47      ~CCoinsViewDB() override;
  48  
  49      std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
  50      std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override;
  51      bool HaveCoin(const COutPoint& outpoint) const override;
  52      uint256 GetBestBlock() const override;
  53      std::vector<uint256> GetHeadBlocks() const override;
  54      void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override;
  55      std::unique_ptr<CCoinsViewCursor> Cursor() const override;
  56  
  57      //! Whether an unsupported database format is used.
  58      bool NeedsUpgrade();
  59      size_t EstimateSize() const override;
  60  
  61      //! Dynamically alter the underlying leveldb cache size.
  62      void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_db_mutex);
  63  
  64      //! Perform a full compaction of the underlying LevelDB on a one-shot background thread.
  65      std::shared_future<void> CompactFullAsync() EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_db_mutex);
  66  
  67      //! Return an underlying LevelDB property value, if available.
  68      std::optional<std::string> GetDBProperty(const std::string& property);
  69  };
  70  
  71  #endif // BITCOIN_TXDB_H
  72