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 <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 : 7416587 : static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
38 : :
39 : 36 : bool DestroyDB(const std::string& path_str)
40 : : {
41 [ - + ]: 36 : return leveldb::DestroyDB(path_str, {}).ok();
42 : : }
43 : :
44 : : /** Handle database error by throwing dbwrapper_error exception.
45 : : */
46 : 50274 : static void HandleError(const leveldb::Status& status)
47 : : {
48 [ + + ]: 50274 : if (status.ok())
49 : 50262 : 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 : 12 : }
55 : :
56 : 3 : 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 : 13558 : void Logv(const char * format, va_list ap) override {
61 [ - + ]: 13558 : if (!util::log::ShouldDebugLog(BCLog::LEVELDB)) {
62 : : return;
63 : : }
64 : : 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 : : bufsize = sizeof(buffer);
70 : : base = buffer;
71 : : }
72 : : else {
73 : 0 : bufsize = 30000;
74 : 0 : base = new char[bufsize];
75 : : }
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 : : }
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 : : }
93 : : else {
94 : 0 : p = limit - 1;
95 : : }
96 : : }
97 : :
98 : : // Add newline if necessary
99 [ # # # # ]: 0 : if (p == base || p[-1] != '\n') {
100 : 0 : *p++ = '\n';
101 : : }
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 : : }
109 : : break;
110 : : }
111 : : }
112 : : };
113 : :
114 : 3230 : 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 : 3230 : int default_open_files = options->max_open_files;
130 : : #ifndef WIN32
131 : 3230 : if (sizeof(void*) < 8) {
132 : : options->max_open_files = 64;
133 : : }
134 : : #endif
135 [ - + ]: 3230 : LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
136 : : options->max_open_files, default_open_files);
137 : 3230 : }
138 : :
139 : 3230 : static leveldb::Options GetOptions(size_t nCacheSize, bool bloom_filter)
140 : : {
141 : 3230 : leveldb::Options options;
142 : 3230 : options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
143 : 3230 : options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
144 [ + + ]: 3230 : options.filter_policy = bloom_filter ? leveldb::NewBloomFilterPolicy(10) : nullptr;
145 : 3230 : options.compression = leveldb::kNoCompression;
146 : 3230 : options.info_log = new CBitcoinLevelDBLogger();
147 : 3230 : 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 : 3230 : options.paranoid_checks = true;
151 : : }
152 : 3230 : SetMaxOpenFiles(&options);
153 : 3230 : return options;
154 : : }
155 : :
156 : 45 : bool CDBWrapper::HasKeyStartingWith(const fs::path& path, uint8_t prefix)
157 : : {
158 [ + - + - : 180 : 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 [ - + + - : 93 : HandleError(leveldb::DB::Open(options, fs::PathToString(path), &raw_db));
+ + ]
168 [ + - ]: 27 : const std::unique_ptr<leveldb::DB> db{raw_db};
169 : :
170 : 27 : leveldb::ReadOptions iteroptions;
171 : 27 : iteroptions.verify_checksums = true;
172 : 27 : iteroptions.fill_cache = false;
173 [ + - + - ]: 27 : const std::unique_ptr<leveldb::Iterator> it{db->NewIterator(iteroptions)};
174 [ + - ]: 27 : const leveldb::Slice prefix_slice{reinterpret_cast<const char*>(&prefix), sizeof(prefix)};
175 [ + - ]: 27 : it->Seek(prefix_slice);
176 [ + - + - ]: 27 : HandleError(it->status());
177 [ + - + + : 27 : return it->Valid() && it->key().starts_with(prefix_slice);
+ - + + ]
178 : 27 : }
179 : :
180 [ + - ]: 93806 : struct CDBBatch::WriteBatchImpl {
181 : : leveldb::WriteBatch batch;
182 : : };
183 : :
184 : 46903 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
185 : 46903 : : parent{_parent},
186 : 46903 : m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
187 : : {
188 [ + - ]: 46903 : m_key_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
189 [ + - ]: 46903 : m_value_scratch.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
190 [ + - ]: 46903 : Clear();
191 : 46903 : };
192 : :
193 : 46903 : CDBBatch::~CDBBatch() = default;
194 : :
195 : 46905 : void CDBBatch::Clear()
196 : : {
197 : 46905 : m_impl_batch->batch.Clear();
198 [ - + - + ]: 46905 : assert(m_key_scratch.empty());
199 [ - + - + ]: 46905 : assert(m_value_scratch.empty());
200 : 46905 : }
201 : :
202 : 535426 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& value)
203 : : {
204 : 535426 : leveldb::Slice slKey(CharCast(key.data()), key.size());
205 [ - + ]: 535426 : dbwrapper_private::GetObfuscation(parent)(value);
206 [ - + ]: 535426 : leveldb::Slice slValue(CharCast(value.data()), value.size());
207 : 535426 : m_impl_batch->batch.Put(slKey, slValue);
208 : 535426 : }
209 : :
210 : 40208 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
211 : : {
212 : 40208 : leveldb::Slice slKey(CharCast(key.data()), key.size());
213 : 40208 : m_impl_batch->batch.Delete(slKey);
214 : 40208 : }
215 : :
216 : 348643 : size_t CDBBatch::ApproximateSize() const
217 : : {
218 : 348643 : return m_impl_batch->batch.ApproximateSize();
219 : : }
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 : 3230 : CDBWrapper::CDBWrapper(const DBParams& params)
245 [ + - ]: 3230 : : m_db_context{std::make_unique<LevelDBContext>()}, m_path{params.path}
246 : : {
247 [ + - ]: 3230 : DBContext().penv = nullptr;
248 : 3230 : DBContext().readoptions.verify_checksums = true;
249 : 3230 : DBContext().iteroptions.verify_checksums = true;
250 : 3230 : DBContext().iteroptions.fill_cache = false;
251 : 3230 : DBContext().syncoptions.sync = true;
252 [ + - ]: 3230 : DBContext().options = GetOptions(params.cache_bytes, params.bloom_filter);
253 : 3230 : DBContext().options.create_if_missing = true;
254 : 3230 : DBContext().options.max_file_size = params.max_file_size;
255 [ - + - - ]: 3230 : assert(!(params.testing_env && params.memory_only));
256 [ - + ]: 3230 : if (params.testing_env) {
257 : 0 : DBContext().options.env = params.testing_env;
258 [ + + ]: 3230 : } else if (params.memory_only) {
259 [ + - + - ]: 425 : DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
260 : 425 : DBContext().options.env = DBContext().penv;
261 : : }
262 [ + + ]: 3230 : if (!params.memory_only) {
263 [ + + ]: 2805 : if (params.wipe_data) {
264 [ - + + - ]: 158 : LogInfo("Wiping LevelDB in %s", fs::PathToString(params.path));
265 [ - + + - ]: 158 : leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
266 [ + - ]: 79 : HandleError(result);
267 : 79 : }
268 [ + - ]: 2805 : if (!params.testing_env) {
269 [ + - ]: 2805 : TryCreateDirectories(params.path);
270 : : }
271 [ - + + - ]: 5610 : LogInfo("Opening LevelDB in %s", fs::PathToString(params.path));
272 : : }
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 [ - + + - ]: 6460 : leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
278 [ + + ]: 3230 : HandleError(status);
279 [ + - ]: 3224 : LogInfo("Opened LevelDB successfully");
280 : :
281 [ + + + - ]: 3224 : if (params.options.force_compact) CompactFull();
282 : :
283 [ + + + + : 3224 : if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
+ + + - +
+ ]
284 : : // Generate and write the new obfuscation key.
285 : 586 : const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
286 [ - + ]: 586 : assert(!m_obfuscation); // Make sure the key is written without obfuscation.
287 [ + - ]: 586 : Write(OBFUSCATION_KEY, obfuscation);
288 : 586 : m_obfuscation = obfuscation;
289 [ + - - + : 1172 : LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - ]
290 : : }
291 [ + - - + : 6446 : LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - - + ]
292 : 3237 : }
293 : :
294 : 3223 : CDBWrapper::~CDBWrapper()
295 : : {
296 [ + - ]: 3223 : delete DBContext().pdb;
297 [ + + ]: 3223 : DBContext().pdb = nullptr;
298 [ + + ]: 3223 : delete DBContext().options.filter_policy;
299 [ + - ]: 3223 : DBContext().options.filter_policy = nullptr;
300 [ + - ]: 3223 : delete DBContext().options.info_log;
301 [ + - ]: 3223 : DBContext().options.info_log = nullptr;
302 [ + - ]: 3223 : delete DBContext().options.block_cache;
303 [ + + ]: 3223 : DBContext().options.block_cache = nullptr;
304 [ + + ]: 3223 : delete DBContext().penv;
305 : 3223 : DBContext().options.env = nullptr;
306 : 6446 : }
307 : :
308 : 46905 : void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
309 : : {
310 : 46905 : const bool log_memory = util::log::ShouldDebugLog(BCLog::LEVELDB);
311 : 46905 : double mem_before = 0;
312 [ + + ]: 46905 : if (log_memory) {
313 : 8 : mem_before = DynamicMemoryUsage() / double(1_MiB);
314 : : }
315 [ + + ]: 46905 : leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
316 [ + - ]: 46905 : HandleError(status);
317 [ + + ]: 46905 : if (log_memory) {
318 [ + - ]: 8 : double mem_after{DynamicMemoryUsage() / double(1_MiB)};
319 [ + - + - : 40 : LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
+ - - + +
- ]
320 : : fs::PathToString(m_path.stem()), mem_before, mem_after);
321 : : }
322 : 46905 : }
323 : :
324 : 18 : std::optional<std::string> CDBWrapper::GetProperty(const std::string& property) const
325 : : {
326 [ - + + - : 18 : if (std::string value; DBContext().pdb->GetProperty(property, &value)) return value;
+ - ]
327 : 0 : return std::nullopt;
328 : : }
329 : :
330 : 8 : void CDBWrapper::CompactFull()
331 : : {
332 [ - + + - ]: 16 : LogInfo("Starting database compaction of %s", fs::PathToString(m_path));
333 : 8 : DBContext().pdb->CompactRange(nullptr, nullptr);
334 [ - + + - ]: 16 : LogInfo("Finished database compaction of %s", fs::PathToString(m_path));
335 : 8 : }
336 : :
337 : 16 : size_t CDBWrapper::DynamicMemoryUsage() const
338 : : {
339 : 16 : std::optional<size_t> parsed;
340 [ + - + - : 32 : if (auto memory{GetProperty("leveldb.approximate-memory-usage")}; !memory || !(parsed = ToIntegral<size_t>(*memory))) {
- + - + ]
341 [ # # # # : 0 : LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
# # ]
342 : 0 : return 0;
343 : 0 : }
344 : 16 : return parsed.value();
345 : : }
346 : :
347 : 6293736 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
348 : : {
349 [ + - ]: 6293736 : leveldb::Slice slKey(CharCast(key.data()), key.size());
350 [ + - ]: 6293736 : std::string strValue;
351 [ + - ]: 6293736 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
352 [ + + ]: 6293736 : if (!status.ok()) {
353 [ + + ]: 6182137 : if (status.IsNotFound())
354 : 6182134 : return std::nullopt;
355 [ + - + - ]: 3 : LogError("LevelDB read failure: %s", status.ToString());
356 [ - + ]: 3 : HandleError(status);
357 : : }
358 : 111599 : return strValue;
359 : 6293736 : }
360 : :
361 : 6445 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
362 : : {
363 [ + - ]: 6445 : leveldb::Slice slKey(CharCast(key.data()), key.size());
364 : :
365 [ + - ]: 6445 : std::string strValue;
366 [ + - ]: 6445 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
367 [ + + ]: 6445 : if (!status.ok()) {
368 [ - + ]: 5925 : if (status.IsNotFound())
369 : : return false;
370 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
371 [ # # ]: 0 : HandleError(status);
372 : : }
373 : : return true;
374 : 6445 : }
375 : :
376 : 104 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
377 : : {
378 : 104 : leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
379 : 104 : leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
380 : 104 : uint64_t size = 0;
381 : 104 : leveldb::Range range(slKey1, slKey2);
382 : 104 : DBContext().pdb->GetApproximateSizes(&range, 1, &size);
383 : 104 : return size;
384 : : }
385 : :
386 : 590 : bool CDBWrapper::IsEmpty()
387 : : {
388 [ + - ]: 590 : std::unique_ptr<CDBIterator> it(NewIterator());
389 [ + - ]: 590 : it->SeekToFirst();
390 [ + - ]: 1180 : return !(it->Valid());
391 : 590 : }
392 : :
393 : 5722 : struct CDBIterator::IteratorImpl {
394 : : const std::unique_ptr<leveldb::Iterator> iter;
395 : :
396 : 5722 : explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
397 : : };
398 : :
399 : 5722 : CDBIterator::CDBIterator(const CDBWrapper& _parent, util::NotNullUniquePtr<IteratorImpl> _piter)
400 : 5722 : : parent(_parent),
401 [ + - ]: 5722 : m_impl_iter(std::move(_piter))
402 : : {
403 [ + - ]: 5722 : m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
404 : 5722 : }
405 : :
406 : 5722 : CDBIterator* CDBWrapper::NewIterator()
407 : : {
408 [ + - + - : 5722 : return new CDBIterator{*this, util::MakeNotNullUnique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ - ]
409 : : }
410 : :
411 : 5138 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
412 : : {
413 : 5138 : leveldb::Slice slKey(CharCast(key.data()), key.size());
414 : 5138 : m_impl_iter->iter->Seek(slKey);
415 : 5138 : }
416 : :
417 : 483101 : std::span<const std::byte> CDBIterator::GetKeyImpl() const
418 : : {
419 : : // The returned span borrows from the current iterator entry and is only
420 : : // valid until the iterator is advanced.
421 : 483101 : return MakeByteSpan(m_impl_iter->iter->key());
422 : : }
423 : :
424 : 481673 : std::span<const std::byte> CDBIterator::GetValueImpl() const
425 : : {
426 : 481673 : return MakeByteSpan(m_impl_iter->iter->value());
427 : : }
428 : :
429 : 5722 : CDBIterator::~CDBIterator() = default;
430 : 487394 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
431 : 590 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
432 : 481517 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
433 : :
434 : : namespace dbwrapper_private {
435 : :
436 : 1017113 : const Obfuscation& GetObfuscation(const CDBWrapper& w)
437 : : {
438 : 1017113 : return w.m_obfuscation;
439 : : }
440 : :
441 : : } // namespace dbwrapper_private
|