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/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 : :
35 : 4513518 : static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
36 : :
37 : 0 : bool DestroyDB(const std::string& path_str)
38 : : {
39 [ # # ]: 0 : return leveldb::DestroyDB(path_str, {}).ok();
40 : : }
41 : :
42 : : /** Handle database error by throwing dbwrapper_error exception.
43 : : */
44 : 159304 : static void HandleError(const leveldb::Status& status)
45 : : {
46 [ + - ]: 159304 : if (status.ok())
47 : 159304 : return;
48 [ # # ]: 0 : const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
49 [ # # ]: 0 : LogPrintf("%s\n", errmsg);
50 [ # # ]: 0 : LogPrintf("You can use -debug=leveldb to get more complete diagnostic messages\n");
51 [ # # ]: 0 : throw dbwrapper_error(errmsg);
52 : 0 : }
53 : :
54 : 3355 : class CBitcoinLevelDBLogger : public leveldb::Logger {
55 : : public:
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 : 3771 : void Logv(const char * format, va_list ap) override {
59 [ - + ]: 3771 : if (!LogAcceptCategory(BCLog::LEVELDB, BCLog::Level::Debug)) {
60 : : return;
61 : : }
62 : : char buffer[500];
63 [ # # ]: 0 : for (int iter = 0; iter < 2; iter++) {
64 : 0 : char* base;
65 : 0 : int bufsize;
66 [ # # ]: 0 : if (iter == 0) {
67 : : bufsize = sizeof(buffer);
68 : : base = buffer;
69 : : }
70 : : else {
71 : 0 : bufsize = 30000;
72 : 0 : base = new char[bufsize];
73 : : }
74 : 0 : char* p = base;
75 : 0 : char* limit = base + bufsize;
76 : :
77 : : // Print the message
78 [ # # ]: 0 : if (p < limit) {
79 : 0 : va_list backup_ap;
80 : 0 : va_copy(backup_ap, ap);
81 : : // Do not use vsnprintf elsewhere in bitcoin source code, see above.
82 : 0 : p += vsnprintf(p, limit - p, format, backup_ap);
83 : 0 : va_end(backup_ap);
84 : : }
85 : :
86 : : // Truncate to available space if necessary
87 [ # # ]: 0 : if (p >= limit) {
88 [ # # ]: 0 : if (iter == 0) {
89 : 0 : continue; // Try again with larger buffer
90 : : }
91 : : else {
92 : 0 : p = limit - 1;
93 : : }
94 : : }
95 : :
96 : : // Add newline if necessary
97 [ # # # # ]: 0 : if (p == base || p[-1] != '\n') {
98 : 0 : *p++ = '\n';
99 : : }
100 : :
101 [ # # ]: 0 : assert(p <= limit);
102 [ # # ]: 0 : base[std::min(bufsize - 1, (int)(p - base))] = '\0';
103 [ # # ]: 0 : LogDebug(BCLog::LEVELDB, "%s\n", util::RemoveSuffixView(base, "\n"));
104 [ # # ]: 0 : if (base != buffer) {
105 [ # # ]: 0 : delete[] base;
106 : : }
107 : : break;
108 : : }
109 : : }
110 : : };
111 : :
112 : 3355 : static 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 : 3355 : int default_open_files = options->max_open_files;
128 : : #ifndef WIN32
129 : 3355 : if (sizeof(void*) < 8) {
130 : : options->max_open_files = 64;
131 : : }
132 : : #endif
133 [ - + ]: 3355 : LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
134 : : options->max_open_files, default_open_files);
135 : 3355 : }
136 : :
137 : 3355 : static leveldb::Options GetOptions(size_t nCacheSize)
138 : : {
139 : 3355 : leveldb::Options options;
140 : 3355 : options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
141 : 3355 : options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
142 : 3355 : options.filter_policy = leveldb::NewBloomFilterPolicy(10);
143 : 3355 : options.compression = leveldb::kNoCompression;
144 [ - + ]: 3355 : options.info_log = new CBitcoinLevelDBLogger();
145 : 3355 : 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 : 3355 : options.paranoid_checks = true;
149 : : }
150 [ - + ]: 3355 : options.max_file_size = std::max(options.max_file_size, DBWRAPPER_MAX_FILE_SIZE);
151 : 3355 : SetMaxOpenFiles(&options);
152 : 3355 : return options;
153 : : }
154 : :
155 [ + - ]: 311898 : struct CDBBatch::WriteBatchImpl {
156 : : leveldb::WriteBatch batch;
157 : : };
158 : :
159 : 155949 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
160 : 155949 : : parent{_parent},
161 [ + - ]: 155949 : m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
162 : : {
163 [ + - ]: 155949 : Clear();
164 : 155949 : };
165 : :
166 : 155949 : CDBBatch::~CDBBatch() = default;
167 : :
168 : 155949 : void CDBBatch::Clear()
169 : : {
170 : 155949 : m_impl_batch->batch.Clear();
171 : 155949 : }
172 : :
173 : 1329324 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& ssValue)
174 : : {
175 : 1329324 : leveldb::Slice slKey(CharCast(key.data()), key.size());
176 : 1329324 : ssValue.Xor(dbwrapper_private::GetObfuscateKey(parent));
177 : 1329324 : leveldb::Slice slValue(CharCast(ssValue.data()), ssValue.size());
178 : 1329324 : m_impl_batch->batch.Put(slKey, slValue);
179 : 1329324 : }
180 : :
181 : 153416 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
182 : : {
183 : 153416 : leveldb::Slice slKey(CharCast(key.data()), key.size());
184 : 153416 : m_impl_batch->batch.Delete(slKey);
185 : 153416 : }
186 : :
187 : 136618 : size_t CDBBatch::ApproximateSize() const
188 : : {
189 : 136618 : return m_impl_batch->batch.ApproximateSize();
190 : : }
191 : :
192 : : struct LevelDBContext {
193 : : //! custom environment this database is using (may be nullptr in case of default environment)
194 : : leveldb::Env* penv;
195 : :
196 : : //! database options used
197 : : leveldb::Options options;
198 : :
199 : : //! options used when reading from the database
200 : : leveldb::ReadOptions readoptions;
201 : :
202 : : //! options used when iterating over values of the database
203 : : leveldb::ReadOptions iteroptions;
204 : :
205 : : //! options used when writing to the database
206 : : leveldb::WriteOptions writeoptions;
207 : :
208 : : //! options used when sync writing to the database
209 : : leveldb::WriteOptions syncoptions;
210 : :
211 : : //! the database itself
212 : : leveldb::DB* pdb;
213 : : };
214 : :
215 : 3355 : CDBWrapper::CDBWrapper(const DBParams& params)
216 [ + - + - : 16775 : : 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 [ + - ]: 3355 : DBContext().penv = nullptr;
219 [ + - ]: 3355 : DBContext().readoptions.verify_checksums = true;
220 [ + - ]: 3355 : DBContext().iteroptions.verify_checksums = true;
221 [ + - ]: 3355 : DBContext().iteroptions.fill_cache = false;
222 [ + - ]: 3355 : DBContext().syncoptions.sync = true;
223 [ + - + - ]: 3355 : DBContext().options = GetOptions(params.cache_bytes);
224 [ + - ]: 3355 : DBContext().options.create_if_missing = true;
225 [ + - ]: 3355 : if (params.memory_only) {
226 [ + - + - : 3355 : DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
+ - ]
227 [ + - + - ]: 3355 : DBContext().options.env = DBContext().penv;
228 : : } else {
229 [ # # ]: 0 : if (params.wipe_data) {
230 [ # # # # ]: 0 : LogPrintf("Wiping LevelDB in %s\n", fs::PathToString(params.path));
231 [ # # # # : 0 : leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
# # ]
232 [ # # ]: 0 : HandleError(result);
233 : 0 : }
234 [ # # ]: 0 : TryCreateDirectories(params.path);
235 [ # # # # ]: 0 : 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 [ + - + - : 6710 : leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
+ - + - ]
242 [ + - ]: 3355 : HandleError(status);
243 [ + - ]: 3355 : LogPrintf("Opened LevelDB successfully\n");
244 : :
245 [ - + ]: 3355 : if (params.options.force_compact) {
246 [ # # # # ]: 0 : LogPrintf("Starting database compaction of %s\n", fs::PathToString(params.path));
247 [ # # # # ]: 0 : DBContext().pdb->CompactRange(nullptr, nullptr);
248 [ # # # # ]: 0 : LogPrintf("Finished database compaction of %s\n", fs::PathToString(params.path));
249 : : }
250 : :
251 : : // The base-case obfuscation key, which is a noop.
252 [ + - + - ]: 3355 : obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
253 : :
254 [ + - ]: 3355 : bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
255 : :
256 [ + - + + : 3355 : if (!key_exists && params.obfuscate && IsEmpty()) {
+ - + - ]
257 : : // Initialize non-degenerate obfuscation if it won't upset
258 : : // existing, non-obfuscated data.
259 [ + - ]: 1811 : std::vector<unsigned char> new_key = CreateObfuscateKey();
260 : :
261 : : // Write `new_key` so we don't obfuscate the key with itself
262 [ + - ]: 1811 : Write(OBFUSCATE_KEY_KEY, new_key);
263 [ + - ]: 1811 : obfuscate_key = new_key;
264 : :
265 [ + - + - : 5433 : LogPrintf("Wrote new obfuscate key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key));
+ - ]
266 : 1811 : }
267 : :
268 [ + - + - : 10065 : LogPrintf("Using obfuscation key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key));
+ - - + ]
269 : 3355 : }
270 : :
271 : 6710 : CDBWrapper::~CDBWrapper()
272 : : {
273 [ + - ]: 3355 : delete DBContext().pdb;
274 : 3355 : DBContext().pdb = nullptr;
275 [ + - ]: 3355 : delete DBContext().options.filter_policy;
276 : 3355 : DBContext().options.filter_policy = nullptr;
277 [ + - ]: 3355 : delete DBContext().options.info_log;
278 : 3355 : DBContext().options.info_log = nullptr;
279 [ + - ]: 3355 : delete DBContext().options.block_cache;
280 : 3355 : DBContext().options.block_cache = nullptr;
281 [ + - ]: 3355 : delete DBContext().penv;
282 : 3355 : DBContext().options.env = nullptr;
283 : 3355 : }
284 : :
285 : 155949 : bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
286 : : {
287 : 155949 : const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, BCLog::Level::Debug);
288 : 155949 : double mem_before = 0;
289 [ + + ]: 155949 : if (log_memory) {
290 : 78 : mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
291 : : }
292 [ + + ]: 155949 : leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
293 [ + - ]: 155949 : HandleError(status);
294 [ + + ]: 155949 : if (log_memory) {
295 [ + - ]: 78 : double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
296 [ + - + - : 78 : LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
+ - ]
297 : : m_name, mem_before, mem_after);
298 : : }
299 [ - + ]: 155949 : return true;
300 : 155949 : }
301 : :
302 : 156 : size_t CDBWrapper::DynamicMemoryUsage() const
303 : : {
304 [ + - ]: 156 : std::string memory;
305 : 156 : std::optional<size_t> parsed;
306 [ + - + - : 156 : if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
+ - - + ]
307 [ # # # # : 0 : LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
# # ]
308 : 0 : return 0;
309 : : }
310 : 156 : return parsed.value();
311 : 156 : }
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.
317 : : const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
318 : :
319 : : const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
320 : :
321 : : /**
322 : : * Returns a string (consisting of 8 random bytes) suitable for use as an
323 : : * obfuscating XOR key.
324 : : */
325 : 1811 : std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
326 : : {
327 : 1811 : std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES);
328 : 1811 : GetRandBytes(ret);
329 : 1811 : return ret;
330 : : }
331 : :
332 : 1469651 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
333 : : {
334 [ + - ]: 1469651 : leveldb::Slice slKey(CharCast(key.data()), key.size());
335 [ + - ]: 1469651 : std::string strValue;
336 [ + - + - : 1469651 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
337 [ + + ]: 1469651 : if (!status.ok()) {
338 [ + - ]: 1224726 : if (status.IsNotFound())
339 : 1224726 : return std::nullopt;
340 [ # # # # ]: 0 : LogPrintf("LevelDB read failure: %s\n", status.ToString());
341 [ # # ]: 0 : HandleError(status);
342 : : }
343 : 244925 : return strValue;
344 : 1469651 : }
345 : :
346 : 1836 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
347 : : {
348 [ + - ]: 1836 : leveldb::Slice slKey(CharCast(key.data()), key.size());
349 : :
350 [ + - ]: 1836 : std::string strValue;
351 [ + - + - : 1836 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
352 [ + + ]: 1836 : if (!status.ok()) {
353 [ - + ]: 1523 : if (status.IsNotFound())
354 : : return false;
355 [ # # # # ]: 0 : LogPrintf("LevelDB read failure: %s\n", status.ToString());
356 [ # # ]: 0 : HandleError(status);
357 : : }
358 : : return true;
359 : 1836 : }
360 : :
361 : 75731 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
362 : : {
363 : 75731 : leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
364 : 75731 : leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
365 : 75731 : uint64_t size = 0;
366 : 75731 : leveldb::Range range(slKey1, slKey2);
367 : 75731 : DBContext().pdb->GetApproximateSizes(&range, 1, &size);
368 : 75731 : return size;
369 : : }
370 : :
371 : 1811 : bool CDBWrapper::IsEmpty()
372 : : {
373 [ + - ]: 1811 : std::unique_ptr<CDBIterator> it(NewIterator());
374 [ + - ]: 1811 : it->SeekToFirst();
375 [ + - ]: 3622 : return !(it->Valid());
376 : 1811 : }
377 : :
378 : 80316 : struct CDBIterator::IteratorImpl {
379 : : const std::unique_ptr<leveldb::Iterator> iter;
380 : :
381 : 80316 : explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
382 : : };
383 : :
384 : 80316 : CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
385 : 80316 : m_impl_iter(std::move(_piter)) {}
386 : :
387 : 80316 : CDBIterator* CDBWrapper::NewIterator()
388 : : {
389 [ + - + - : 80316 : return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ - + - +
- ]
390 : : }
391 : :
392 : 78505 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
393 : : {
394 : 78505 : leveldb::Slice slKey(CharCast(key.data()), key.size());
395 : 78505 : m_impl_iter->iter->Seek(slKey);
396 : 78505 : }
397 : :
398 : 3939993 : std::span<const std::byte> CDBIterator::GetKeyImpl() const
399 : : {
400 : 3939993 : return MakeByteSpan(m_impl_iter->iter->key());
401 : : }
402 : :
403 : 3939680 : std::span<const std::byte> CDBIterator::GetValueImpl() const
404 : : {
405 : 3939680 : return MakeByteSpan(m_impl_iter->iter->value());
406 : : }
407 : :
408 : 80316 : CDBIterator::~CDBIterator() = default;
409 : 4019996 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
410 : 1811 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
411 : 3939680 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
412 : :
413 : : namespace dbwrapper_private {
414 : :
415 : 5269004 : const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
416 : : {
417 : 5269004 : return w.obfuscate_key;
418 : : }
419 : :
420 : : } // namespace dbwrapper_private
|