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