Bitcoin Core 29.99.0
P2P Digital Currency
dbwrapper.cpp
Go to the documentation of this file.
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/strencodings.h>
15
16#include <algorithm>
17#include <cassert>
18#include <cstdarg>
19#include <cstdint>
20#include <cstdio>
21#include <leveldb/cache.h>
22#include <leveldb/db.h>
23#include <leveldb/env.h>
24#include <leveldb/filter_policy.h>
25#include <leveldb/helpers/memenv/memenv.h>
26#include <leveldb/iterator.h>
27#include <leveldb/options.h>
28#include <leveldb/slice.h>
29#include <leveldb/status.h>
30#include <leveldb/write_batch.h>
31#include <memory>
32#include <optional>
33#include <utility>
34
35static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
36
37bool DestroyDB(const std::string& path_str)
38{
39 return leveldb::DestroyDB(path_str, {}).ok();
40}
41
44static void HandleError(const leveldb::Status& status)
45{
46 if (status.ok())
47 return;
48 const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
49 LogPrintf("%s\n", errmsg);
50 LogPrintf("You can use -debug=leveldb to get more complete diagnostic messages\n");
51 throw dbwrapper_error(errmsg);
52}
53
54class CBitcoinLevelDBLogger : public leveldb::Logger {
55public:
56 // This code is adapted from posix_logger.h, which is why it is using vsprintf.
57 // Please do not do this in normal code
58 void Logv(const char * format, va_list ap) override {
60 return;
61 }
62 char buffer[500];
63 for (int iter = 0; iter < 2; iter++) {
64 char* base;
65 int bufsize;
66 if (iter == 0) {
67 bufsize = sizeof(buffer);
68 base = buffer;
69 }
70 else {
71 bufsize = 30000;
72 base = new char[bufsize];
73 }
74 char* p = base;
75 char* limit = base + bufsize;
76
77 // Print the message
78 if (p < limit) {
79 va_list backup_ap;
80 va_copy(backup_ap, ap);
81 // Do not use vsnprintf elsewhere in bitcoin source code, see above.
82 p += vsnprintf(p, limit - p, format, backup_ap);
83 va_end(backup_ap);
84 }
85
86 // Truncate to available space if necessary
87 if (p >= limit) {
88 if (iter == 0) {
89 continue; // Try again with larger buffer
90 }
91 else {
92 p = limit - 1;
93 }
94 }
95
96 // Add newline if necessary
97 if (p == base || p[-1] != '\n') {
98 *p++ = '\n';
99 }
100
101 assert(p <= limit);
102 base[std::min(bufsize - 1, (int)(p - base))] = '\0';
103 LogDebug(BCLog::LEVELDB, "%s\n", util::RemoveSuffixView(base, "\n"));
104 if (base != buffer) {
105 delete[] base;
106 }
107 break;
108 }
109 }
110};
111
112static void SetMaxOpenFiles(leveldb::Options *options) {
113 // On most platforms the default setting of max_open_files (which is 1000)
114 // is optimal. On Windows using a large file count is OK because the handles
115 // do not interfere with select() loops. On 64-bit Unix hosts this value is
116 // also OK, because up to that amount LevelDB will use an mmap
117 // implementation that does not use extra file descriptors (the fds are
118 // closed after being mmap'ed).
119 //
120 // Increasing the value beyond the default is dangerous because LevelDB will
121 // fall back to a non-mmap implementation when the file count is too large.
122 // On 32-bit Unix host we should decrease the value because the handles use
123 // up real fds, and we want to avoid fd exhaustion issues.
124 //
125 // See PR #12495 for further discussion.
126
127 int default_open_files = options->max_open_files;
128#ifndef WIN32
129 if (sizeof(void*) < 8) {
130 options->max_open_files = 64;
131 }
132#endif
133 LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
134 options->max_open_files, default_open_files);
135}
136
137static leveldb::Options GetOptions(size_t nCacheSize)
138{
139 leveldb::Options options;
140 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
141 options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
142 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
143 options.compression = leveldb::kNoCompression;
144 options.info_log = new CBitcoinLevelDBLogger();
145 if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
146 // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
147 // on corruption in later versions.
148 options.paranoid_checks = true;
149 }
150 options.max_file_size = std::max(options.max_file_size, DBWRAPPER_MAX_FILE_SIZE);
151 SetMaxOpenFiles(&options);
152 return options;
153}
154
156 leveldb::WriteBatch batch;
157};
158
160 : parent{_parent},
161 m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
162{
163 Clear();
164};
165
166CDBBatch::~CDBBatch() = default;
167
169{
170 m_impl_batch->batch.Clear();
171}
172
173void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& ssValue)
174{
175 leveldb::Slice slKey(CharCast(key.data()), key.size());
177 leveldb::Slice slValue(CharCast(ssValue.data()), ssValue.size());
178 m_impl_batch->batch.Put(slKey, slValue);
179}
180
181void CDBBatch::EraseImpl(std::span<const std::byte> key)
182{
183 leveldb::Slice slKey(CharCast(key.data()), key.size());
184 m_impl_batch->batch.Delete(slKey);
185}
186
188{
189 return m_impl_batch->batch.ApproximateSize();
190}
191
194 leveldb::Env* penv;
195
197 leveldb::Options options;
198
200 leveldb::ReadOptions readoptions;
201
203 leveldb::ReadOptions iteroptions;
204
206 leveldb::WriteOptions writeoptions;
207
209 leveldb::WriteOptions syncoptions;
210
212 leveldb::DB* pdb;
214
216 : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}, m_path{params.path}, m_is_memory{params.memory_only}
217{
218 DBContext().penv = nullptr;
219 DBContext().readoptions.verify_checksums = true;
220 DBContext().iteroptions.verify_checksums = true;
221 DBContext().iteroptions.fill_cache = false;
222 DBContext().syncoptions.sync = true;
223 DBContext().options = GetOptions(params.cache_bytes);
224 DBContext().options.create_if_missing = true;
225 if (params.memory_only) {
226 DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
227 DBContext().options.env = DBContext().penv;
228 } else {
229 if (params.wipe_data) {
230 LogPrintf("Wiping LevelDB in %s\n", fs::PathToString(params.path));
231 leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
232 HandleError(result);
233 }
235 LogPrintf("Opening LevelDB in %s\n", fs::PathToString(params.path));
236 }
237 // PathToString() return value is safe to pass to leveldb open function,
238 // because on POSIX leveldb passes the byte string directly to ::open(), and
239 // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW
240 // (see env_posix.cc and env_windows.cc).
241 leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
242 HandleError(status);
243 LogPrintf("Opened LevelDB successfully\n");
244
245 if (params.options.force_compact) {
246 LogPrintf("Starting database compaction of %s\n", fs::PathToString(params.path));
247 DBContext().pdb->CompactRange(nullptr, nullptr);
248 LogPrintf("Finished database compaction of %s\n", fs::PathToString(params.path));
249 }
250
251 // The base-case obfuscation key, which is a noop.
252 obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
253
254 bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
255
256 if (!key_exists && params.obfuscate && IsEmpty()) {
257 // Initialize non-degenerate obfuscation if it won't upset
258 // existing, non-obfuscated data.
259 std::vector<unsigned char> new_key = CreateObfuscateKey();
260
261 // Write `new_key` so we don't obfuscate the key with itself
262 Write(OBFUSCATE_KEY_KEY, new_key);
263 obfuscate_key = new_key;
264
265 LogPrintf("Wrote new obfuscate key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key));
266 }
267
268 LogPrintf("Using obfuscation key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key));
269}
270
272{
273 delete DBContext().pdb;
274 DBContext().pdb = nullptr;
275 delete DBContext().options.filter_policy;
276 DBContext().options.filter_policy = nullptr;
277 delete DBContext().options.info_log;
278 DBContext().options.info_log = nullptr;
279 delete DBContext().options.block_cache;
280 DBContext().options.block_cache = nullptr;
281 delete DBContext().penv;
282 DBContext().options.env = nullptr;
283}
284
285bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
286{
287 const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, BCLog::Level::Debug);
288 double mem_before = 0;
289 if (log_memory) {
290 mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
291 }
292 leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
293 HandleError(status);
294 if (log_memory) {
295 double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
296 LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
297 m_name, mem_before, mem_after);
298 }
299 return true;
300}
301
303{
304 std::string memory;
305 std::optional<size_t> parsed;
306 if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
307 LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
308 return 0;
309 }
310 return parsed.value();
311}
312
313// Prefixed with null character to avoid collisions with other keys
314//
315// We must use a string constructor which specifies length so that we copy
316// past the null-terminator.
317const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
318
319const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
320
325std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
326{
327 std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES);
329 return ret;
330}
331
332std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
333{
334 leveldb::Slice slKey(CharCast(key.data()), key.size());
335 std::string strValue;
336 leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
337 if (!status.ok()) {
338 if (status.IsNotFound())
339 return std::nullopt;
340 LogPrintf("LevelDB read failure: %s\n", status.ToString());
341 HandleError(status);
342 }
343 return strValue;
344}
345
346bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
347{
348 leveldb::Slice slKey(CharCast(key.data()), key.size());
349
350 std::string strValue;
351 leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
352 if (!status.ok()) {
353 if (status.IsNotFound())
354 return false;
355 LogPrintf("LevelDB read failure: %s\n", status.ToString());
356 HandleError(status);
357 }
358 return true;
359}
360
361size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
362{
363 leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
364 leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
365 uint64_t size = 0;
366 leveldb::Range range(slKey1, slKey2);
367 DBContext().pdb->GetApproximateSizes(&range, 1, &size);
368 return size;
369}
370
372{
373 std::unique_ptr<CDBIterator> it(NewIterator());
374 it->SeekToFirst();
375 return !(it->Valid());
376}
377
379 const std::unique_ptr<leveldb::Iterator> iter;
380
381 explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
382};
383
384CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
385 m_impl_iter(std::move(_piter)) {}
386
388{
389 return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
390}
391
392void CDBIterator::SeekImpl(std::span<const std::byte> key)
393{
394 leveldb::Slice slKey(CharCast(key.data()), key.size());
395 m_impl_iter->iter->Seek(slKey);
396}
397
398std::span<const std::byte> CDBIterator::GetKeyImpl() const
399{
400 return MakeByteSpan(m_impl_iter->iter->key());
401}
402
403std::span<const std::byte> CDBIterator::GetValueImpl() const
404{
405 return MakeByteSpan(m_impl_iter->iter->value());
406}
407
408CDBIterator::~CDBIterator() = default;
409bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
410void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
411void CDBIterator::Next() { m_impl_iter->iter->Next(); }
412
414
415const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
416{
417 return w.obfuscate_key;
418}
419
420} // namespace dbwrapper_private
int ret
void Logv(const char *format, va_list ap) override
Definition: dbwrapper.cpp:58
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:74
void WriteImpl(std::span< const std::byte > key, DataStream &ssValue)
Definition: dbwrapper.cpp:173
const std::unique_ptr< WriteBatchImpl > m_impl_batch
Definition: dbwrapper.h:81
void EraseImpl(std::span< const std::byte > key)
Definition: dbwrapper.cpp:181
DataStream ssValue
Definition: dbwrapper.h:84
void Clear()
Definition: dbwrapper.cpp:168
CDBBatch(const CDBWrapper &_parent)
Definition: dbwrapper.cpp:159
size_t ApproximateSize() const
Definition: dbwrapper.cpp:187
const CDBWrapper & parent
Definition: dbwrapper.h:78
CDBIterator(const CDBWrapper &_parent, std::unique_ptr< IteratorImpl > _piter)
Definition: dbwrapper.cpp:384
const std::unique_ptr< IteratorImpl > m_impl_iter
Definition: dbwrapper.h:128
void SeekImpl(std::span< const std::byte > key)
Definition: dbwrapper.cpp:392
std::span< const std::byte > GetKeyImpl() const
Definition: dbwrapper.cpp:398
bool Valid() const
Definition: dbwrapper.cpp:409
void SeekToFirst()
Definition: dbwrapper.cpp:410
void Next()
Definition: dbwrapper.cpp:411
std::span< const std::byte > GetValueImpl() const
Definition: dbwrapper.cpp:403
std::optional< std::string > ReadImpl(std::span< const std::byte > key) const
Definition: dbwrapper.cpp:332
size_t EstimateSizeImpl(std::span< const std::byte > key1, std::span< const std::byte > key2) const
Definition: dbwrapper.cpp:361
size_t DynamicMemoryUsage() const
Definition: dbwrapper.cpp:302
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:285
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:220
CDBIterator * NewIterator()
Definition: dbwrapper.cpp:387
std::string m_name
the name of this database
Definition: dbwrapper.h:188
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:240
std::vector< unsigned char > obfuscate_key
a key used for optional XOR-obfuscation of the database
Definition: dbwrapper.h:191
CDBWrapper(const DBParams &params)
Definition: dbwrapper.cpp:215
static const unsigned int OBFUSCATE_KEY_NUM_BYTES
the length of the obfuscate key in number of bytes
Definition: dbwrapper.h:197
static const std::string OBFUSCATE_KEY_KEY
the key under which the obfuscation key is stored
Definition: dbwrapper.h:194
bool ExistsImpl(std::span< const std::byte > key) const
Definition: dbwrapper.cpp:346
std::vector< unsigned char > CreateObfuscateKey() const
Returns a string (consisting of 8 random bytes) suitable for use as an obfuscating XOR key.
Definition: dbwrapper.cpp:325
auto & DBContext() const LIFETIMEBOUND
Definition: dbwrapper.h:210
bool IsEmpty()
Return true if the database managed by this class contains no entries.
Definition: dbwrapper.cpp:371
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
size_type size() const
Definition: streams.h:181
void Xor(const std::vector< unsigned char > &key)
XOR the contents of this stream with a certain key.
Definition: streams.h:276
value_type * data()
Definition: streams.h:188
static leveldb::Options GetOptions(size_t nCacheSize)
Definition: dbwrapper.cpp:137
static auto CharCast(const std::byte *data)
Definition: dbwrapper.cpp:35
bool DestroyDB(const std::string &path_str)
Definition: dbwrapper.cpp:37
static void SetMaxOpenFiles(leveldb::Options *options)
Definition: dbwrapper.cpp:112
static void HandleError(const leveldb::Status &status)
Handle database error by throwing dbwrapper_error exception.
Definition: dbwrapper.cpp:44
static const size_t DBWRAPPER_MAX_FILE_SIZE
Definition: dbwrapper.h:25
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:261
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:233
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
@ LEVELDB
Definition: logging.h:63
These should be considered an implementation detail of the specific database.
Definition: dbwrapper.cpp:413
const std::vector< unsigned char > & GetObfuscateKey(const CDBWrapper &w)
Work around circular dependency, as well as for testing in dbwrapper_tests.
Definition: dbwrapper.cpp:415
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
std::string_view RemoveSuffixView(std::string_view str, std::string_view suffix)
Definition: string.h:161
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:676
auto MakeByteSpan(const V &v) noexcept
Definition: span.h:84
leveldb::WriteBatch batch
Definition: dbwrapper.cpp:156
IteratorImpl(leveldb::Iterator *_iter)
Definition: dbwrapper.cpp:381
const std::unique_ptr< leveldb::Iterator > iter
Definition: dbwrapper.cpp:379
bool force_compact
Compact database on startup.
Definition: dbwrapper.h:30
Application-specific storage settings.
Definition: dbwrapper.h:34
DBOptions options
Passed-through options.
Definition: dbwrapper.h:47
bool obfuscate
If true, store data obfuscated via simple XOR.
Definition: dbwrapper.h:45
bool wipe_data
If true, remove all existing data.
Definition: dbwrapper.h:42
size_t cache_bytes
Configures various leveldb cache settings.
Definition: dbwrapper.h:38
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:36
bool memory_only
If true, use leveldb's memory environment.
Definition: dbwrapper.h:40
leveldb::Env * penv
custom environment this database is using (may be nullptr in case of default environment)
Definition: dbwrapper.cpp:194
leveldb::ReadOptions iteroptions
options used when iterating over values of the database
Definition: dbwrapper.cpp:203
leveldb::ReadOptions readoptions
options used when reading from the database
Definition: dbwrapper.cpp:200
leveldb::Options options
database options used
Definition: dbwrapper.cpp:197
leveldb::DB * pdb
the database itself
Definition: dbwrapper.cpp:212
leveldb::WriteOptions syncoptions
options used when sync writing to the database
Definition: dbwrapper.cpp:209
leveldb::WriteOptions writeoptions
options used when writing to the database
Definition: dbwrapper.cpp:206
assert(!tx.IsCoinBase())