LCOV - code coverage report
Current view: top level - src - dbwrapper.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 75.8 % 194 147
Test Date: 2025-08-01 04:15:35 Functions: 96.7 % 30 29
Branches: 35.9 % 262 94

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

Generated by: LCOV version 2.0-1