Coverage Report

Created: 2026-09-14 20:36

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