LCOV - code coverage report
Current view: top level - src - dbwrapper.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 79.4 % 194 154
Test Date: 2026-04-27 06:58:15 Functions: 96.7 % 30 29
Branches: 42.2 % 256 108

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2012-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <dbwrapper.h>
       6                 :             : 
       7                 :             : #include <leveldb/cache.h>
       8                 :             : #include <leveldb/db.h>
       9                 :             : #include <leveldb/env.h>
      10                 :             : #include <leveldb/filter_policy.h>
      11                 :             : #include <leveldb/helpers/memenv/memenv.h>
      12                 :             : #include <leveldb/iterator.h>
      13                 :             : #include <leveldb/options.h>
      14                 :             : #include <leveldb/slice.h>
      15                 :             : #include <leveldb/status.h>
      16                 :             : #include <leveldb/write_batch.h>
      17                 :             : #include <logging.h>
      18                 :             : #include <random.h>
      19                 :             : #include <serialize.h>
      20                 :             : #include <span.h>
      21                 :             : #include <streams.h>
      22                 :             : #include <util/byte_units.h>
      23                 :             : #include <util/fs.h>
      24                 :             : #include <util/fs_helpers.h>
      25                 :             : #include <util/log.h>
      26                 :             : #include <util/obfuscation.h>
      27                 :             : #include <util/strencodings.h>
      28                 :             : 
      29                 :             : #include <algorithm>
      30                 :             : #include <cassert>
      31                 :             : #include <cstdarg>
      32                 :             : #include <cstdint>
      33                 :             : #include <cstdio>
      34                 :             : #include <memory>
      35                 :             : #include <optional>
      36                 :             : #include <utility>
      37                 :             : 
      38                 :     6752608 : static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
      39                 :             : 
      40                 :          35 : bool DestroyDB(const std::string& path_str)
      41                 :             : {
      42         [ -  + ]:          35 :     return leveldb::DestroyDB(path_str, {}).ok();
      43                 :             : }
      44                 :             : 
      45                 :             : /** Handle database error by throwing dbwrapper_error exception.
      46                 :             :  */
      47                 :       45440 : static void HandleError(const leveldb::Status& status)
      48                 :             : {
      49         [ +  + ]:       45440 :     if (status.ok())
      50                 :       45430 :         return;
      51         [ +  - ]:          10 :     const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
      52         [ +  - ]:          10 :     LogError("%s", errmsg);
      53         [ +  - ]:          10 :     LogInfo("You can use -debug=leveldb to get more complete diagnostic messages");
      54         [ +  - ]:          10 :     throw dbwrapper_error(errmsg);
      55                 :          10 : }
      56                 :             : 
      57                 :        2860 : class CBitcoinLevelDBLogger : public leveldb::Logger {
      58                 :             : public:
      59                 :             :     // This code is adapted from posix_logger.h, which is why it is using vsprintf.
      60                 :             :     // Please do not do this in normal code
      61                 :       12307 :     void Logv(const char * format, va_list ap) override {
      62         [ -  + ]:       12307 :             if (!LogAcceptCategory(BCLog::LEVELDB, util::log::Level::Debug)) {
      63                 :             :                 return;
      64                 :             :             }
      65                 :             :             char buffer[500];
      66         [ #  # ]:           0 :             for (int iter = 0; iter < 2; iter++) {
      67                 :           0 :                 char* base;
      68                 :           0 :                 int bufsize;
      69         [ #  # ]:           0 :                 if (iter == 0) {
      70                 :             :                     bufsize = sizeof(buffer);
      71                 :             :                     base = buffer;
      72                 :             :                 }
      73                 :             :                 else {
      74                 :           0 :                     bufsize = 30000;
      75                 :           0 :                     base = new char[bufsize];
      76                 :             :                 }
      77                 :           0 :                 char* p = base;
      78                 :           0 :                 char* limit = base + bufsize;
      79                 :             : 
      80                 :             :                 // Print the message
      81         [ #  # ]:           0 :                 if (p < limit) {
      82                 :           0 :                     va_list backup_ap;
      83                 :           0 :                     va_copy(backup_ap, ap);
      84                 :             :                     // Do not use vsnprintf elsewhere in bitcoin source code, see above.
      85                 :           0 :                     p += vsnprintf(p, limit - p, format, backup_ap);
      86                 :           0 :                     va_end(backup_ap);
      87                 :             :                 }
      88                 :             : 
      89                 :             :                 // Truncate to available space if necessary
      90         [ #  # ]:           0 :                 if (p >= limit) {
      91         [ #  # ]:           0 :                     if (iter == 0) {
      92                 :           0 :                         continue;       // Try again with larger buffer
      93                 :             :                     }
      94                 :             :                     else {
      95                 :           0 :                         p = limit - 1;
      96                 :             :                     }
      97                 :             :                 }
      98                 :             : 
      99                 :             :                 // Add newline if necessary
     100   [ #  #  #  # ]:           0 :                 if (p == base || p[-1] != '\n') {
     101                 :           0 :                     *p++ = '\n';
     102                 :             :                 }
     103                 :             : 
     104         [ #  # ]:           0 :                 assert(p <= limit);
     105         [ #  # ]:           0 :                 base[std::min(bufsize - 1, (int)(p - base))] = '\0';
     106         [ #  # ]:           0 :                 LogDebug(BCLog::LEVELDB, "%s\n", util::RemoveSuffixView(base, "\n"));
     107         [ #  # ]:           0 :                 if (base != buffer) {
     108         [ #  # ]:           0 :                     delete[] base;
     109                 :             :                 }
     110                 :             :                 break;
     111                 :             :             }
     112                 :             :     }
     113                 :             : };
     114                 :             : 
     115                 :        2860 : static void SetMaxOpenFiles(leveldb::Options *options) {
     116                 :             :     // On most platforms the default setting of max_open_files (which is 1000)
     117                 :             :     // is optimal. On Windows using a large file count is OK because the handles
     118                 :             :     // do not interfere with select() loops. On 64-bit Unix hosts this value is
     119                 :             :     // also OK, because up to that amount LevelDB will use an mmap
     120                 :             :     // implementation that does not use extra file descriptors (the fds are
     121                 :             :     // closed after being mmap'ed).
     122                 :             :     //
     123                 :             :     // Increasing the value beyond the default is dangerous because LevelDB will
     124                 :             :     // fall back to a non-mmap implementation when the file count is too large.
     125                 :             :     // On 32-bit Unix host we should decrease the value because the handles use
     126                 :             :     // up real fds, and we want to avoid fd exhaustion issues.
     127                 :             :     //
     128                 :             :     // See PR #12495 for further discussion.
     129                 :             : 
     130                 :        2860 :     int default_open_files = options->max_open_files;
     131                 :             : #ifndef WIN32
     132                 :        2860 :     if (sizeof(void*) < 8) {
     133                 :             :         options->max_open_files = 64;
     134                 :             :     }
     135                 :             : #endif
     136         [ -  + ]:        2860 :     LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
     137                 :             :              options->max_open_files, default_open_files);
     138                 :        2860 : }
     139                 :             : 
     140                 :        2860 : static leveldb::Options GetOptions(size_t nCacheSize)
     141                 :             : {
     142                 :        2860 :     leveldb::Options options;
     143                 :        2860 :     options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
     144                 :        2860 :     options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
     145                 :        2860 :     options.filter_policy = leveldb::NewBloomFilterPolicy(10);
     146                 :        2860 :     options.compression = leveldb::kNoCompression;
     147         [ -  + ]:        2860 :     options.info_log = new CBitcoinLevelDBLogger();
     148                 :        2860 :     if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
     149                 :             :         // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
     150                 :             :         // on corruption in later versions.
     151                 :        2860 :         options.paranoid_checks = true;
     152                 :             :     }
     153         [ -  + ]:        2860 :     options.max_file_size = std::max(options.max_file_size, DBWRAPPER_MAX_FILE_SIZE);
     154                 :        2860 :     SetMaxOpenFiles(&options);
     155                 :        2860 :     return options;
     156                 :             : }
     157                 :             : 
     158         [ +  - ]:       85022 : struct CDBBatch::WriteBatchImpl {
     159                 :             :     leveldb::WriteBatch batch;
     160                 :             : };
     161                 :             : 
     162                 :       42511 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
     163                 :       42511 :     : parent{_parent},
     164                 :       42511 :       m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
     165                 :             : {
     166         [ +  - ]:       42511 :     Clear();
     167                 :       42511 : };
     168                 :             : 
     169                 :       42511 : CDBBatch::~CDBBatch() = default;
     170                 :             : 
     171                 :       42511 : void CDBBatch::Clear()
     172                 :             : {
     173                 :       42511 :     m_impl_batch->batch.Clear();
     174                 :       42511 : }
     175                 :             : 
     176                 :      500055 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& ssValue)
     177                 :             : {
     178                 :      500055 :     leveldb::Slice slKey(CharCast(key.data()), key.size());
     179         [ -  + ]:      500055 :     dbwrapper_private::GetObfuscation(parent)(ssValue);
     180         [ -  + ]:      500055 :     leveldb::Slice slValue(CharCast(ssValue.data()), ssValue.size());
     181                 :      500055 :     m_impl_batch->batch.Put(slKey, slValue);
     182                 :      500055 : }
     183                 :             : 
     184                 :       39018 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
     185                 :             : {
     186                 :       39018 :     leveldb::Slice slKey(CharCast(key.data()), key.size());
     187                 :       39018 :     m_impl_batch->batch.Delete(slKey);
     188                 :       39018 : }
     189                 :             : 
     190                 :      328661 : size_t CDBBatch::ApproximateSize() const
     191                 :             : {
     192                 :      328661 :     return m_impl_batch->batch.ApproximateSize();
     193                 :             : }
     194                 :             : 
     195                 :             : struct LevelDBContext {
     196                 :             :     //! custom environment this database is using (may be nullptr in case of default environment)
     197                 :             :     leveldb::Env* penv;
     198                 :             : 
     199                 :             :     //! database options used
     200                 :             :     leveldb::Options options;
     201                 :             : 
     202                 :             :     //! options used when reading from the database
     203                 :             :     leveldb::ReadOptions readoptions;
     204                 :             : 
     205                 :             :     //! options used when iterating over values of the database
     206                 :             :     leveldb::ReadOptions iteroptions;
     207                 :             : 
     208                 :             :     //! options used when writing to the database
     209                 :             :     leveldb::WriteOptions writeoptions;
     210                 :             : 
     211                 :             :     //! options used when sync writing to the database
     212                 :             :     leveldb::WriteOptions syncoptions;
     213                 :             : 
     214                 :             :     //! the database itself
     215                 :             :     leveldb::DB* pdb;
     216                 :             : };
     217                 :             : 
     218                 :        2860 : CDBWrapper::CDBWrapper(const DBParams& params)
     219   [ +  -  -  + ]:       14300 :     : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}
     220                 :             : {
     221         [ +  - ]:        2860 :     DBContext().penv = nullptr;
     222         [ +  - ]:        2860 :     DBContext().readoptions.verify_checksums = true;
     223         [ +  - ]:        2860 :     DBContext().iteroptions.verify_checksums = true;
     224         [ +  - ]:        2860 :     DBContext().iteroptions.fill_cache = false;
     225         [ +  - ]:        2860 :     DBContext().syncoptions.sync = true;
     226   [ +  -  +  - ]:        2860 :     DBContext().options = GetOptions(params.cache_bytes);
     227         [ +  - ]:        2860 :     DBContext().options.create_if_missing = true;
     228         [ +  + ]:        2860 :     if (params.memory_only) {
     229   [ +  -  +  -  :         330 :         DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
                   +  - ]
     230   [ +  -  +  - ]:         330 :         DBContext().options.env = DBContext().penv;
     231                 :             :     } else {
     232         [ +  + ]:        2530 :         if (params.wipe_data) {
     233   [ -  +  +  - ]:         136 :             LogInfo("Wiping LevelDB in %s", fs::PathToString(params.path));
     234   [ +  -  -  +  :         136 :             leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
                   +  - ]
     235         [ +  - ]:          68 :             HandleError(result);
     236                 :          68 :         }
     237         [ +  - ]:        2530 :         TryCreateDirectories(params.path);
     238   [ -  +  +  - ]:        7590 :         LogInfo("Opening LevelDB in %s", fs::PathToString(params.path));
     239                 :             :     }
     240                 :             :     // PathToString() return value is safe to pass to leveldb open function,
     241                 :             :     // because on POSIX leveldb passes the byte string directly to ::open(), and
     242                 :             :     // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW
     243                 :             :     // (see env_posix.cc and env_windows.cc).
     244   [ +  -  -  +  :        5720 :     leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
             +  -  +  - ]
     245         [ +  + ]:        2860 :     HandleError(status);
     246         [ +  - ]:        2851 :     LogInfo("Opened LevelDB successfully");
     247                 :             : 
     248         [ -  + ]:        2851 :     if (params.options.force_compact) {
     249   [ #  #  #  # ]:           0 :         LogInfo("Starting database compaction of %s", fs::PathToString(params.path));
     250   [ #  #  #  # ]:           0 :         DBContext().pdb->CompactRange(nullptr, nullptr);
     251   [ #  #  #  # ]:           0 :         LogInfo("Finished database compaction of %s", fs::PathToString(params.path));
     252                 :             :     }
     253                 :             : 
     254   [ +  +  +  +  :        2851 :     if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
          +  +  +  -  +  
                      + ]
     255                 :             :         // Generate and write the new obfuscation key.
     256                 :         516 :         const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
     257         [ -  + ]:         516 :         assert(!m_obfuscation); // Make sure the key is written without obfuscation.
     258         [ +  - ]:         516 :         Write(OBFUSCATION_KEY, obfuscation);
     259                 :         516 :         m_obfuscation = obfuscation;
     260   [ +  -  -  +  :        1548 :         LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
                   +  - ]
     261                 :             :     }
     262   [ +  -  -  +  :        8550 :     LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
             +  -  -  + ]
     263                 :        2860 : }
     264                 :             : 
     265                 :        2850 : CDBWrapper::~CDBWrapper()
     266                 :             : {
     267         [ +  - ]:        2850 :     delete DBContext().pdb;
     268                 :        2850 :     DBContext().pdb = nullptr;
     269         [ +  - ]:        2850 :     delete DBContext().options.filter_policy;
     270                 :        2850 :     DBContext().options.filter_policy = nullptr;
     271         [ +  - ]:        2850 :     delete DBContext().options.info_log;
     272                 :        2850 :     DBContext().options.info_log = nullptr;
     273         [ +  - ]:        2850 :     delete DBContext().options.block_cache;
     274                 :        2850 :     DBContext().options.block_cache = nullptr;
     275         [ +  + ]:        2850 :     delete DBContext().penv;
     276                 :        2850 :     DBContext().options.env = nullptr;
     277                 :        2850 : }
     278                 :             : 
     279                 :       42511 : void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
     280                 :             : {
     281                 :       42511 :     const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, util::log::Level::Debug);
     282                 :       42511 :     double mem_before = 0;
     283         [ -  + ]:       42511 :     if (log_memory) {
     284                 :           0 :         mem_before = DynamicMemoryUsage() / double(1_MiB);
     285                 :             :     }
     286         [ +  + ]:       42511 :     leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
     287         [ +  - ]:       42511 :     HandleError(status);
     288         [ -  + ]:       42511 :     if (log_memory) {
     289         [ #  # ]:           0 :         double mem_after{DynamicMemoryUsage() / double(1_MiB)};
     290   [ #  #  #  #  :           0 :         LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
                   #  # ]
     291                 :             :                  m_name, mem_before, mem_after);
     292                 :             :     }
     293                 :       42511 : }
     294                 :             : 
     295                 :           0 : size_t CDBWrapper::DynamicMemoryUsage() const
     296                 :             : {
     297         [ #  # ]:           0 :     std::string memory;
     298                 :           0 :     std::optional<size_t> parsed;
     299   [ #  #  #  #  :           0 :     if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
             #  #  #  # ]
     300   [ #  #  #  #  :           0 :         LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
                   #  # ]
     301                 :           0 :         return 0;
     302                 :             :     }
     303                 :           0 :     return parsed.value();
     304                 :           0 : }
     305                 :             : 
     306                 :     5707463 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
     307                 :             : {
     308         [ +  - ]:     5707463 :     leveldb::Slice slKey(CharCast(key.data()), key.size());
     309         [ +  - ]:     5707463 :     std::string strValue;
     310   [ +  -  +  -  :     5707463 :     leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
                   +  - ]
     311         [ +  + ]:     5707463 :     if (!status.ok()) {
     312         [ +  + ]:     5622664 :         if (status.IsNotFound())
     313                 :     5622663 :             return std::nullopt;
     314   [ +  -  +  - ]:           1 :         LogError("LevelDB read failure: %s", status.ToString());
     315         [ -  + ]:           1 :         HandleError(status);
     316                 :             :     }
     317                 :       84799 :     return strValue;
     318                 :     5707463 : }
     319                 :             : 
     320                 :        1306 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
     321                 :             : {
     322         [ +  - ]:        1306 :     leveldb::Slice slKey(CharCast(key.data()), key.size());
     323                 :             : 
     324         [ +  - ]:        1306 :     std::string strValue;
     325   [ +  -  +  -  :        1306 :     leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
                   +  - ]
     326         [ +  + ]:        1306 :     if (!status.ok()) {
     327         [ -  + ]:        1293 :         if (status.IsNotFound())
     328                 :             :             return false;
     329   [ #  #  #  # ]:           0 :         LogError("LevelDB read failure: %s", status.ToString());
     330         [ #  # ]:           0 :         HandleError(status);
     331                 :             :     }
     332                 :             :     return true;
     333                 :        1306 : }
     334                 :             : 
     335                 :         104 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
     336                 :             : {
     337                 :         104 :     leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
     338                 :         104 :     leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
     339                 :         104 :     uint64_t size = 0;
     340                 :         104 :     leveldb::Range range(slKey1, slKey2);
     341                 :         104 :     DBContext().pdb->GetApproximateSizes(&range, 1, &size);
     342                 :         104 :     return size;
     343                 :             : }
     344                 :             : 
     345                 :         520 : bool CDBWrapper::IsEmpty()
     346                 :             : {
     347         [ +  - ]:         520 :     std::unique_ptr<CDBIterator> it(NewIterator());
     348         [ +  - ]:         520 :     it->SeekToFirst();
     349         [ +  - ]:        1040 :     return !(it->Valid());
     350                 :         520 : }
     351                 :             : 
     352                 :        5021 : struct CDBIterator::IteratorImpl {
     353                 :             :     const std::unique_ptr<leveldb::Iterator> iter;
     354                 :             : 
     355                 :        5021 :     explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
     356                 :             : };
     357                 :             : 
     358                 :        5021 : CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
     359                 :        5021 :                                                                                             m_impl_iter(std::move(_piter)) {}
     360                 :             : 
     361                 :        5021 : CDBIterator* CDBWrapper::NewIterator()
     362                 :             : {
     363   [ +  -  +  -  :        5021 :     return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
          +  -  +  -  +  
                      - ]
     364                 :             : }
     365                 :             : 
     366                 :        4503 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
     367                 :             : {
     368                 :        4503 :     leveldb::Slice slKey(CharCast(key.data()), key.size());
     369                 :        4503 :     m_impl_iter->iter->Seek(slKey);
     370                 :        4503 : }
     371                 :             : 
     372                 :      408788 : std::span<const std::byte> CDBIterator::GetKeyImpl() const
     373                 :             : {
     374                 :             :     // The returned span borrows from the current iterator entry and is only
     375                 :             :     // valid until the iterator is advanced.
     376                 :      408788 :     return MakeByteSpan(m_impl_iter->iter->key());
     377                 :             : }
     378                 :             : 
     379                 :      407796 : std::span<const std::byte> CDBIterator::GetValueImpl() const
     380                 :             : {
     381                 :      407796 :     return MakeByteSpan(m_impl_iter->iter->value());
     382                 :             : }
     383                 :             : 
     384                 :        5021 : CDBIterator::~CDBIterator() = default;
     385                 :      412657 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
     386                 :         520 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
     387                 :      407480 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
     388                 :             : 
     389                 :             : namespace dbwrapper_private {
     390                 :             : 
     391                 :      907865 : const Obfuscation& GetObfuscation(const CDBWrapper& w)
     392                 :             : {
     393                 :      907865 :     return w.m_obfuscation;
     394                 :             : }
     395                 :             : 
     396                 :             : } // namespace dbwrapper_private
        

Generated by: LCOV version 2.0-1