Coverage Report

Created: 2026-10-07 13:27

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
6.40M
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
30.0k
{
48
30.0k
    if (status.ok())
49
30.0k
        return;
50
13
    const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
51
13
    LogError("%s", errmsg);
52
13
    LogInfo("You can use -debug=leveldb to get more complete diagnostic messages");
53
13
    throw dbwrapper_error(errmsg);
54
30.0k
}
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.5k
    void Logv(const char * format, va_list ap) override {
61
12.5k
            if (!util::log::ShouldDebugLog(BCLog::LEVELDB)) {
62
12.5k
                return;
63
12.5k
            }
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
3.04k
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
3.04k
    int default_open_files = options->max_open_files;
130
3.04k
#ifndef WIN32
131
3.04k
    if (sizeof(void*) < 8) {
132
0
        options->max_open_files = 64;
133
0
    }
134
3.04k
#endif
135
3.04k
    LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
136
3.04k
             options->max_open_files, default_open_files);
137
3.04k
}
138
139
static leveldb::Options GetOptions(size_t nCacheSize, bool bloom_filter)
140
3.04k
{
141
3.04k
    leveldb::Options options;
142
3.04k
    options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
143
3.04k
    options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
144
3.04k
    options.filter_policy = bloom_filter ? leveldb::NewBloomFilterPolicy(10) : nullptr;
145
3.04k
    options.compression = leveldb::kNoCompression;
146
3.04k
    options.info_log = new CBitcoinLevelDBLogger();
147
3.04k
    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
3.04k
        options.paranoid_checks = true;
151
3.04k
    }
152
3.04k
    SetMaxOpenFiles(&options);
153
3.04k
    return options;
154
3.04k
}
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.8k
    : parent{_parent},
186
26.8k
      m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
187
26.8k
{
188
26.8k
    m_key_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
189
26.8k
    m_value_scratch.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
190
26.8k
    Clear();
191
26.8k
};
192
193
26.8k
CDBBatch::~CDBBatch() = default;
194
195
void CDBBatch::Clear()
196
26.8k
{
197
26.8k
    m_impl_batch->batch.Clear();
198
26.8k
    assert(m_key_scratch.empty());
199
26.8k
    assert(m_value_scratch.empty());
200
26.8k
}
201
202
void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& value)
203
452k
{
204
452k
    leveldb::Slice slKey(CharCast(key.data()), key.size());
205
452k
    dbwrapper_private::GetObfuscation(parent)(value);
206
452k
    leveldb::Slice slValue(CharCast(value.data()), value.size());
207
452k
    m_impl_batch->batch.Put(slKey, slValue);
208
452k
}
209
210
void CDBBatch::EraseImpl(std::span<const std::byte> key)
211
41.0k
{
212
41.0k
    leveldb::Slice slKey(CharCast(key.data()), key.size());
213
41.0k
    m_impl_batch->batch.Delete(slKey);
214
41.0k
}
215
216
size_t CDBBatch::ApproximateSize() const
217
327k
{
218
327k
    return m_impl_batch->batch.ApproximateSize();
219
327k
}
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
3.04k
    : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}
246
3.04k
{
247
3.04k
    DBContext().penv = nullptr;
248
3.04k
    DBContext().readoptions.verify_checksums = true;
249
3.04k
    DBContext().iteroptions.verify_checksums = true;
250
3.04k
    DBContext().iteroptions.fill_cache = false;
251
3.04k
    DBContext().syncoptions.sync = true;
252
3.04k
    DBContext().options = GetOptions(params.cache_bytes, params.bloom_filter);
253
3.04k
    DBContext().options.create_if_missing = true;
254
3.04k
    DBContext().options.max_file_size = params.max_file_size;
255
3.04k
    assert(!(params.testing_env && params.memory_only));
256
3.04k
    if (params.testing_env) {
257
0
        DBContext().options.env = params.testing_env;
258
3.04k
    } else if (params.memory_only) {
259
407
        DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
260
407
        DBContext().options.env = DBContext().penv;
261
407
    }
262
3.04k
    if (!params.memory_only) {
263
2.64k
        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.64k
        if (!params.testing_env) {
269
2.64k
            TryCreateDirectories(params.path);
270
2.64k
        }
271
2.64k
        LogInfo("Opening LevelDB in %s", fs::PathToString(params.path));
272
2.64k
    }
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
3.04k
    leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
278
3.04k
    HandleError(status);
279
3.04k
    LogInfo("Opened LevelDB successfully");
280
281
3.04k
    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
3.04k
    if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
288
        // Generate and write the new obfuscation key.
289
563
        const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
290
563
        assert(!m_obfuscation); // Make sure the key is written without obfuscation.
291
563
        Write(OBFUSCATION_KEY, obfuscation);
292
563
        m_obfuscation = obfuscation;
293
563
        LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
294
563
    }
295
3.04k
    LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
296
3.04k
}
297
298
CDBWrapper::~CDBWrapper()
299
3.04k
{
300
3.04k
    delete DBContext().pdb;
301
3.04k
    DBContext().pdb = nullptr;
302
3.04k
    delete DBContext().options.filter_policy;
303
3.04k
    DBContext().options.filter_policy = nullptr;
304
3.04k
    delete DBContext().options.info_log;
305
3.04k
    DBContext().options.info_log = nullptr;
306
3.04k
    delete DBContext().options.block_cache;
307
3.04k
    DBContext().options.block_cache = nullptr;
308
3.04k
    delete DBContext().penv;
309
3.04k
    DBContext().options.env = nullptr;
310
3.04k
}
311
312
void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
313
26.8k
{
314
26.8k
    const bool log_memory = util::log::ShouldDebugLog(BCLog::LEVELDB);
315
26.8k
    double mem_before = 0;
316
26.8k
    if (log_memory) {
317
8
        mem_before = DynamicMemoryUsage() / double(1_MiB);
318
8
    }
319
26.8k
    leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
320
26.8k
    HandleError(status);
321
26.8k
    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.8k
}
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
7
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
5.44M
{
348
5.44M
    leveldb::Slice slKey(CharCast(key.data()), key.size());
349
5.44M
    std::string strValue;
350
5.44M
    leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
351
5.44M
    if (!status.ok()) {
352
5.33M
        if (status.IsNotFound())
353
5.33M
            return std::nullopt;
354
2
        LogError("LevelDB read failure: %s", status.ToString());
355
2
        HandleError(status);
356
2
    }
357
111k
    return strValue;
358
5.44M
}
359
360
bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
361
6.13k
{
362
6.13k
    leveldb::Slice slKey(CharCast(key.data()), key.size());
363
364
6.13k
    std::string strValue;
365
6.13k
    leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
366
6.13k
    if (!status.ok()) {
367
5.61k
        if (status.IsNotFound())
368
5.61k
            return false;
369
0
        LogError("LevelDB read failure: %s", status.ToString());
370
0
        HandleError(status);
371
0
    }
372
520
    return true;
373
6.13k
}
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
567
{
387
567
    std::unique_ptr<CDBIterator> it(NewIterator());
388
567
    it->SeekToFirst();
389
567
    return !(it->Valid());
390
567
}
391
392
struct CDBIterator::IteratorImpl {
393
    const std::unique_ptr<leveldb::Iterator> iter;
394
395
5.45k
    explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
396
};
397
398
5.45k
CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
399
5.45k
                                                                                            m_impl_iter(std::move(_piter))
400
5.45k
{
401
5.45k
    m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
402
5.45k
}
403
404
CDBIterator* CDBWrapper::NewIterator()
405
5.45k
{
406
5.45k
    return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
407
5.45k
}
408
409
void CDBIterator::SeekImpl(std::span<const std::byte> key)
410
4.89k
{
411
4.89k
    leveldb::Slice slKey(CharCast(key.data()), key.size());
412
4.89k
    m_impl_iter->iter->Seek(slKey);
413
4.89k
}
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
428k
{
424
428k
    return MakeByteSpan(m_impl_iter->iter->value());
425
428k
}
426
427
5.45k
CDBIterator::~CDBIterator() = default;
428
434k
bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
429
567
void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
430
428k
void CDBIterator::Next() { m_impl_iter->iter->Next(); }
431
432
namespace dbwrapper_private {
433
434
const Obfuscation& GetObfuscation(const CDBWrapper& w)
435
880k
{
436
880k
    return w.m_obfuscation;
437
880k
}
438
439
} // namespace dbwrapper_private