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 : 52788963 : static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
38 : :
39 : 0 : bool DestroyDB(const std::string& path_str)
40 : : {
41 [ # # ]: 0 : return leveldb::DestroyDB(path_str, {}).ok();
42 : : }
43 : :
44 : : /** Handle database error by throwing dbwrapper_error exception.
45 : : */
46 : 5811908 : static void HandleError(const leveldb::Status& status)
47 : : {
48 [ + - ]: 5811908 : if (status.ok())
49 : 5811908 : return;
50 [ # # ]: 0 : const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
51 [ # # ]: 0 : LogError("%s", errmsg);
52 [ # # ]: 0 : LogInfo("You can use -debug=leveldb to get more complete diagnostic messages");
53 [ # # ]: 0 : throw dbwrapper_error(errmsg);
54 : 0 : }
55 : :
56 : 0 : 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 : 1780080 : void Logv(const char * format, va_list ap) override {
61 [ - + ]: 1780080 : 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 : 166486 : 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 : 166486 : int default_open_files = options->max_open_files;
130 : : #ifndef WIN32
131 : 166486 : if (sizeof(void*) < 8) {
132 : : options->max_open_files = 64;
133 : : }
134 : : #endif
135 [ - + ]: 166486 : LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
136 : : options->max_open_files, default_open_files);
137 : 166486 : }
138 : :
139 : 166486 : static leveldb::Options GetOptions(size_t nCacheSize, bool bloom_filter)
140 : : {
141 : 166486 : leveldb::Options options;
142 : 166486 : options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
143 : 166486 : options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
144 [ + + ]: 166486 : options.filter_policy = bloom_filter ? leveldb::NewBloomFilterPolicy(10) : nullptr;
145 : 166486 : options.compression = leveldb::kNoCompression;
146 : 166486 : options.info_log = new CBitcoinLevelDBLogger();
147 : 166486 : 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 : 166486 : options.paranoid_checks = true;
151 : : }
152 : 166486 : SetMaxOpenFiles(&options);
153 : 166486 : return options;
154 : : }
155 : :
156 : 0 : bool CDBWrapper::HasKeyStartingWith(const fs::path& path, uint8_t prefix)
157 : : {
158 [ # # # # : 0 : if (!fs::exists(path / "CURRENT")) return false;
# # ]
159 : :
160 : 0 : CBitcoinLevelDBLogger logger;
161 [ # # ]: 0 : leveldb::Options options;
162 : 0 : options.paranoid_checks = true;
163 : : // Avoid creating or rotating LevelDB's LOG files during this probe.
164 : 0 : options.info_log = &logger;
165 : :
166 : 0 : leveldb::DB* raw_db;
167 [ # # # # : 0 : HandleError(leveldb::DB::Open(options, fs::PathToString(path), &raw_db));
# # ]
168 [ # # ]: 0 : const std::unique_ptr<leveldb::DB> db{raw_db};
169 : :
170 : 0 : leveldb::ReadOptions iteroptions;
171 : 0 : iteroptions.verify_checksums = true;
172 : 0 : iteroptions.fill_cache = false;
173 [ # # # # ]: 0 : const std::unique_ptr<leveldb::Iterator> it{db->NewIterator(iteroptions)};
174 [ # # ]: 0 : const leveldb::Slice prefix_slice{reinterpret_cast<const char*>(&prefix), sizeof(prefix)};
175 [ # # ]: 0 : it->Seek(prefix_slice);
176 [ # # # # ]: 0 : HandleError(it->status());
177 [ # # # # : 0 : return it->Valid() && it->key().starts_with(prefix_slice);
# # # # ]
178 : 0 : }
179 : :
180 [ + - ]: 11290844 : struct CDBBatch::WriteBatchImpl {
181 : : leveldb::WriteBatch batch;
182 : : };
183 : :
184 : 5645422 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
185 : 5645422 : : parent{_parent},
186 : 5645422 : m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
187 : : {
188 [ + - ]: 5645422 : m_key_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
189 [ + - ]: 5645422 : m_value_scratch.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
190 [ + - ]: 5645422 : Clear();
191 : 5645422 : };
192 : :
193 : 5645422 : CDBBatch::~CDBBatch() = default;
194 : :
195 : 5660088 : void CDBBatch::Clear()
196 : : {
197 : 5660088 : m_impl_batch->batch.Clear();
198 [ - + - + ]: 5660088 : assert(m_key_scratch.empty());
199 [ - + - + ]: 5660088 : assert(m_value_scratch.empty());
200 : 5660088 : }
201 : :
202 : 15280704 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& value)
203 : : {
204 : 15280704 : leveldb::Slice slKey(CharCast(key.data()), key.size());
205 [ - + ]: 15280704 : dbwrapper_private::GetObfuscation(parent)(value);
206 [ - + ]: 15280704 : leveldb::Slice slValue(CharCast(value.data()), value.size());
207 : 15280704 : m_impl_batch->batch.Put(slKey, slValue);
208 : 15280704 : }
209 : :
210 : 10588043 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
211 : : {
212 : 10588043 : leveldb::Slice slKey(CharCast(key.data()), key.size());
213 : 10588043 : m_impl_batch->batch.Delete(slKey);
214 : 10588043 : }
215 : :
216 : 747866 : size_t CDBBatch::ApproximateSize() const
217 : : {
218 : 747866 : 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 : 166486 : CDBWrapper::CDBWrapper(const DBParams& params)
245 [ + - ]: 166486 : : m_db_context{std::make_unique<LevelDBContext>()}, m_path{params.path}
246 : : {
247 : 166486 : DBContext().penv = nullptr;
248 : 166486 : DBContext().readoptions.verify_checksums = true;
249 : 166486 : DBContext().iteroptions.verify_checksums = true;
250 : 166486 : DBContext().iteroptions.fill_cache = false;
251 : 166486 : DBContext().syncoptions.sync = true;
252 [ + - ]: 166486 : DBContext().options = GetOptions(params.cache_bytes, params.bloom_filter);
253 : 166486 : DBContext().options.create_if_missing = true;
254 : 166486 : DBContext().options.max_file_size = params.max_file_size;
255 [ + + - + ]: 166486 : assert(!(params.testing_env && params.memory_only));
256 [ + + ]: 166486 : if (params.testing_env) {
257 : 145469 : DBContext().options.env = params.testing_env;
258 [ + - ]: 21017 : } else if (params.memory_only) {
259 [ + - + - ]: 21017 : DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
260 : 21017 : DBContext().options.env = DBContext().penv;
261 : : }
262 [ + + ]: 166486 : if (!params.memory_only) {
263 [ - + ]: 145469 : if (params.wipe_data) {
264 [ # # # # ]: 0 : LogInfo("Wiping LevelDB in %s", fs::PathToString(params.path));
265 [ # # # # ]: 0 : leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
266 [ # # ]: 0 : HandleError(result);
267 : 0 : }
268 [ - + ]: 145469 : if (!params.testing_env) {
269 [ # # ]: 0 : TryCreateDirectories(params.path);
270 : : }
271 [ - + + - ]: 290938 : 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 [ - + + - ]: 332972 : leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
278 [ + - ]: 166486 : HandleError(status);
279 [ + - ]: 166486 : LogInfo("Opened LevelDB successfully");
280 : :
281 [ + + + - ]: 166486 : if (params.options.force_compact) CompactFull();
282 : :
283 [ + - + + : 166486 : if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
+ + + - +
- ]
284 : : // Generate and write the new obfuscation key.
285 : 8319 : const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
286 [ - + ]: 8319 : assert(!m_obfuscation); // Make sure the key is written without obfuscation.
287 [ + - ]: 8319 : Write(OBFUSCATION_KEY, obfuscation);
288 : 8319 : m_obfuscation = obfuscation;
289 [ + - - + : 16638 : LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - ]
290 : : }
291 [ + - - + : 332972 : LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - - + ]
292 : 166486 : }
293 : :
294 : 166486 : CDBWrapper::~CDBWrapper()
295 : : {
296 [ + - ]: 166486 : delete DBContext().pdb;
297 : 166486 : DBContext().pdb = nullptr;
298 [ + + ]: 166486 : delete DBContext().options.filter_policy;
299 : 166486 : DBContext().options.filter_policy = nullptr;
300 [ + - ]: 166486 : delete DBContext().options.info_log;
301 : 166486 : DBContext().options.info_log = nullptr;
302 [ + - ]: 166486 : delete DBContext().options.block_cache;
303 : 166486 : DBContext().options.block_cache = nullptr;
304 [ + + ]: 166486 : delete DBContext().penv;
305 : 166486 : DBContext().options.env = nullptr;
306 : 332972 : }
307 : :
308 : 5645422 : void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
309 : : {
310 : 5645422 : const bool log_memory = util::log::ShouldDebugLog(BCLog::LEVELDB);
311 : 5645422 : double mem_before = 0;
312 [ + + ]: 5645422 : if (log_memory) {
313 : 154 : mem_before = DynamicMemoryUsage() / double(1_MiB);
314 : : }
315 [ + + ]: 11290844 : leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
316 [ + - ]: 5645422 : HandleError(status);
317 [ + + ]: 5645422 : if (log_memory) {
318 [ + - ]: 154 : double mem_after{DynamicMemoryUsage() / double(1_MiB)};
319 [ + - + - : 770 : 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 : 5645422 : }
323 : :
324 : 16970 : std::optional<std::string> CDBWrapper::GetProperty(const std::string& property) const
325 : : {
326 [ - + + - : 16970 : if (std::string value; DBContext().pdb->GetProperty(property, &value)) return value;
+ - ]
327 : 0 : return std::nullopt;
328 : : }
329 : :
330 : 98032 : void CDBWrapper::CompactFull()
331 : : {
332 [ - + + - ]: 196064 : LogInfo("Starting database compaction of %s", fs::PathToString(m_path));
333 : 98032 : DBContext().pdb->CompactRange(nullptr, nullptr);
334 [ - + + - ]: 196064 : LogInfo("Finished database compaction of %s", fs::PathToString(m_path));
335 : 98032 : }
336 : :
337 : 16970 : size_t CDBWrapper::DynamicMemoryUsage() const
338 : : {
339 : 16970 : std::optional<size_t> parsed;
340 [ + - + - : 33940 : 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 : 16970 : return parsed.value();
345 : : }
346 : :
347 : 10880962 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
348 : : {
349 : 10880962 : leveldb::Slice slKey(CharCast(key.data()), key.size());
350 : 10880962 : std::string strValue;
351 [ + - ]: 10880962 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
352 [ + + ]: 10880962 : if (!status.ok()) {
353 [ + - ]: 4165024 : if (status.IsNotFound())
354 : 4165024 : return std::nullopt;
355 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
356 [ # # ]: 0 : HandleError(status);
357 : : }
358 : 6715938 : return strValue;
359 : 10880962 : }
360 : :
361 : 76218 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
362 : : {
363 : 76218 : leveldb::Slice slKey(CharCast(key.data()), key.size());
364 : :
365 : 76218 : std::string strValue;
366 [ + - ]: 76218 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
367 [ + + ]: 76218 : if (!status.ok()) {
368 [ - + ]: 43120 : if (status.IsNotFound())
369 : : return false;
370 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
371 [ # # ]: 0 : HandleError(status);
372 : : }
373 : : return true;
374 : 76218 : }
375 : :
376 : 205772 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
377 : : {
378 : 205772 : leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
379 : 205772 : leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
380 : 205772 : uint64_t size = 0;
381 : 205772 : leveldb::Range range(slKey1, slKey2);
382 : 205772 : DBContext().pdb->GetApproximateSizes(&range, 1, &size);
383 : 205772 : return size;
384 : : }
385 : :
386 : 14243 : bool CDBWrapper::IsEmpty()
387 : : {
388 [ + - ]: 14243 : std::unique_ptr<CDBIterator> it(NewIterator());
389 [ + - ]: 14243 : it->SeekToFirst();
390 [ + - ]: 28486 : return !(it->Valid());
391 : 14243 : }
392 : :
393 : 380575 : struct CDBIterator::IteratorImpl {
394 : : const std::unique_ptr<leveldb::Iterator> iter;
395 : :
396 : 380575 : explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
397 : : };
398 : :
399 : 380575 : CDBIterator::CDBIterator(const CDBWrapper& _parent, util::NotNullUniquePtr<IteratorImpl> _piter)
400 : 380575 : : parent(_parent),
401 [ + - ]: 380575 : m_impl_iter(std::move(_piter))
402 : : {
403 [ + - ]: 380575 : m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
404 : 380575 : }
405 : :
406 : 380575 : CDBIterator* CDBWrapper::NewIterator()
407 : : {
408 [ + - + - : 380575 : return new CDBIterator{*this, util::MakeNotNullUnique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ - ]
409 : : }
410 : :
411 : 270788 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
412 : : {
413 : 270788 : leveldb::Slice slKey(CharCast(key.data()), key.size());
414 : 270788 : m_impl_iter->iter->Seek(slKey);
415 : 270788 : }
416 : :
417 : 10398076 : 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 : 10398076 : return MakeByteSpan(m_impl_iter->iter->key());
422 : : }
423 : :
424 : 10120254 : std::span<const std::byte> CDBIterator::GetValueImpl() const
425 : : {
426 : 10120254 : return MakeByteSpan(m_impl_iter->iter->value());
427 : : }
428 : :
429 : 380575 : CDBIterator::~CDBIterator() = default;
430 : 10661532 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
431 : 162457 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
432 : 10170151 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
433 : :
434 : : namespace dbwrapper_private {
435 : :
436 : 25400958 : const Obfuscation& GetObfuscation(const CDBWrapper& w)
437 : : {
438 : 25400958 : return w.m_obfuscation;
439 : : }
440 : :
441 : : } // namespace dbwrapper_private
|