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 : 31720864 : 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 : 3591372 : static void HandleError(const leveldb::Status& status)
47 : : {
48 [ + - ]: 3591372 : if (status.ok())
49 : 3591372 : 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 : 59823 : 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 : 359641 : void Logv(const char * format, va_list ap) override {
61 [ - + ]: 359641 : 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 : 59823 : 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 : 59823 : int default_open_files = options->max_open_files;
130 : : #ifndef WIN32
131 : 59823 : if (sizeof(void*) < 8) {
132 : : options->max_open_files = 64;
133 : : }
134 : : #endif
135 [ - + ]: 59823 : LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
136 : : options->max_open_files, default_open_files);
137 : 59823 : }
138 : :
139 : 59823 : static leveldb::Options GetOptions(size_t nCacheSize)
140 : : {
141 : 59823 : leveldb::Options options;
142 : 59823 : options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
143 : 59823 : options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
144 : 59823 : options.filter_policy = leveldb::NewBloomFilterPolicy(10);
145 : 59823 : options.compression = leveldb::kNoCompression;
146 : 59823 : options.info_log = new CBitcoinLevelDBLogger();
147 : 59823 : 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 : 59823 : options.paranoid_checks = true;
151 : : }
152 : 59823 : SetMaxOpenFiles(&options);
153 : 59823 : return options;
154 : : }
155 : :
156 [ + - ]: 7063098 : struct CDBBatch::WriteBatchImpl {
157 : : leveldb::WriteBatch batch;
158 : : };
159 : :
160 : 3531549 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
161 : 3531549 : : parent{_parent},
162 : 3531549 : m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
163 : : {
164 [ + - ]: 3531549 : m_key_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
165 [ + - ]: 3531549 : m_value_scratch.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
166 [ + - ]: 3531549 : Clear();
167 : 3531549 : };
168 : :
169 : 3531549 : CDBBatch::~CDBBatch() = default;
170 : :
171 : 3536700 : void CDBBatch::Clear()
172 : : {
173 : 3536700 : m_impl_batch->batch.Clear();
174 [ - + - + ]: 3536700 : assert(m_key_scratch.empty());
175 [ - + - + ]: 3536700 : assert(m_value_scratch.empty());
176 : 3536700 : }
177 : :
178 : 8697500 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& value)
179 : : {
180 : 8697500 : leveldb::Slice slKey(CharCast(key.data()), key.size());
181 [ - + ]: 8697500 : dbwrapper_private::GetObfuscation(parent)(value);
182 [ - + ]: 8697500 : leveldb::Slice slValue(CharCast(value.data()), value.size());
183 : 8697500 : m_impl_batch->batch.Put(slKey, slValue);
184 : 8697500 : }
185 : :
186 : 6857285 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
187 : : {
188 : 6857285 : leveldb::Slice slKey(CharCast(key.data()), key.size());
189 : 6857285 : m_impl_batch->batch.Delete(slKey);
190 : 6857285 : }
191 : :
192 : 289662 : size_t CDBBatch::ApproximateSize() const
193 : : {
194 : 289662 : return m_impl_batch->batch.ApproximateSize();
195 : : }
196 : :
197 : : struct LevelDBContext {
198 : : //! custom environment this database is using (may be nullptr in case of default environment)
199 : : leveldb::Env* penv;
200 : :
201 : : //! database options used
202 : : leveldb::Options options;
203 : :
204 : : //! options used when reading from the database
205 : : leveldb::ReadOptions readoptions;
206 : :
207 : : //! options used when iterating over values of the database
208 : : leveldb::ReadOptions iteroptions;
209 : :
210 : : //! options used when writing to the database
211 : : leveldb::WriteOptions writeoptions;
212 : :
213 : : //! options used when sync writing to the database
214 : : leveldb::WriteOptions syncoptions;
215 : :
216 : : //! the database itself
217 : : leveldb::DB* pdb;
218 : : };
219 : :
220 : 59823 : CDBWrapper::CDBWrapper(const DBParams& params)
221 [ + - - + ]: 299115 : : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}
222 : : {
223 [ + - ]: 59823 : DBContext().penv = nullptr;
224 [ + - ]: 59823 : DBContext().readoptions.verify_checksums = true;
225 [ + - ]: 59823 : DBContext().iteroptions.verify_checksums = true;
226 [ + - ]: 59823 : DBContext().iteroptions.fill_cache = false;
227 [ + - ]: 59823 : DBContext().syncoptions.sync = true;
228 [ + - + - ]: 59823 : DBContext().options = GetOptions(params.cache_bytes);
229 [ + - ]: 59823 : DBContext().options.create_if_missing = true;
230 [ + - ]: 59823 : DBContext().options.max_file_size = params.max_file_size;
231 [ + + - + ]: 59823 : assert(!(params.testing_env && params.memory_only));
232 [ + + ]: 59823 : if (params.testing_env) {
233 [ + - ]: 47875 : DBContext().options.env = params.testing_env;
234 [ + - ]: 11948 : } else if (params.memory_only) {
235 [ + - + - : 11948 : DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
+ - ]
236 [ + - + - ]: 11948 : DBContext().options.env = DBContext().penv;
237 : : }
238 [ + + ]: 59823 : if (!params.memory_only) {
239 [ - + ]: 47875 : if (params.wipe_data) {
240 [ # # # # ]: 0 : LogInfo("Wiping LevelDB in %s", fs::PathToString(params.path));
241 [ # # # # : 0 : leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
# # ]
242 [ # # ]: 0 : HandleError(result);
243 : 0 : }
244 [ - + ]: 47875 : if (!params.testing_env) {
245 [ # # ]: 0 : TryCreateDirectories(params.path);
246 : : }
247 [ - + + - ]: 95750 : LogInfo("Opening LevelDB in %s", fs::PathToString(params.path));
248 : : }
249 : : // PathToString() return value is safe to pass to leveldb open function,
250 : : // because on POSIX leveldb passes the byte string directly to ::open(), and
251 : : // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW
252 : : // (see env_posix.cc and env_windows.cc).
253 [ + - - + : 119646 : leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
+ - + - ]
254 [ + - ]: 59823 : HandleError(status);
255 [ + - ]: 59823 : LogInfo("Opened LevelDB successfully");
256 : :
257 [ + + ]: 59823 : if (params.options.force_compact) {
258 [ - + + - ]: 28468 : LogInfo("Starting database compaction of %s", fs::PathToString(params.path));
259 [ + - + - ]: 14234 : DBContext().pdb->CompactRange(nullptr, nullptr);
260 [ - + + - ]: 28468 : LogInfo("Finished database compaction of %s", fs::PathToString(params.path));
261 : : }
262 : :
263 [ + - + + : 59823 : if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
+ + + - +
- ]
264 : : // Generate and write the new obfuscation key.
265 : 5990 : const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
266 [ - + ]: 5990 : assert(!m_obfuscation); // Make sure the key is written without obfuscation.
267 [ + - ]: 5990 : Write(OBFUSCATION_KEY, obfuscation);
268 : 5990 : m_obfuscation = obfuscation;
269 [ + - - + : 11980 : LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - ]
270 : : }
271 [ + - - + : 119646 : LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - - + ]
272 : 59823 : }
273 : :
274 : 59823 : CDBWrapper::~CDBWrapper()
275 : : {
276 [ + - ]: 59823 : delete DBContext().pdb;
277 : 59823 : DBContext().pdb = nullptr;
278 [ + - ]: 59823 : delete DBContext().options.filter_policy;
279 : 59823 : DBContext().options.filter_policy = nullptr;
280 [ + - ]: 59823 : delete DBContext().options.info_log;
281 : 59823 : DBContext().options.info_log = nullptr;
282 [ + - ]: 59823 : delete DBContext().options.block_cache;
283 : 59823 : DBContext().options.block_cache = nullptr;
284 [ + + ]: 59823 : delete DBContext().penv;
285 : 59823 : DBContext().options.env = nullptr;
286 : 59823 : }
287 : :
288 : 3531549 : void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
289 : : {
290 : 3531549 : const bool log_memory = util::log::ShouldDebugLog(BCLog::LEVELDB);
291 : 3531549 : double mem_before = 0;
292 [ + + ]: 3531549 : if (log_memory) {
293 : 252 : mem_before = DynamicMemoryUsage() / double(1_MiB);
294 : : }
295 [ + + ]: 3531549 : leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
296 [ + - ]: 3531549 : HandleError(status);
297 [ + + ]: 3531549 : if (log_memory) {
298 [ + - ]: 252 : double mem_after{DynamicMemoryUsage() / double(1_MiB)};
299 [ + - + - : 3531549 : LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
+ - - + ]
300 : : m_name, mem_before, mem_after);
301 : : }
302 : 3531549 : }
303 : :
304 : 2016 : size_t CDBWrapper::DynamicMemoryUsage() const
305 : : {
306 [ + - ]: 2016 : std::string memory;
307 : 2016 : std::optional<size_t> parsed;
308 [ + - + - : 4032 : if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
+ - - + ]
309 [ # # # # : 0 : LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
# # ]
310 : 0 : return 0;
311 : : }
312 : 2016 : return parsed.value();
313 : 2016 : }
314 : :
315 : 7120258 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
316 : : {
317 [ + - ]: 7120258 : leveldb::Slice slKey(CharCast(key.data()), key.size());
318 [ + - ]: 7120258 : std::string strValue;
319 [ + - + - : 7120258 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
320 [ + + ]: 7120258 : if (!status.ok()) {
321 [ + - ]: 3383038 : if (status.IsNotFound())
322 : 3383038 : return std::nullopt;
323 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
324 [ # # ]: 0 : HandleError(status);
325 : : }
326 : 3737220 : return strValue;
327 : 7120258 : }
328 : :
329 : 25161 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
330 : : {
331 [ + - ]: 25161 : leveldb::Slice slKey(CharCast(key.data()), key.size());
332 : :
333 [ + - ]: 25161 : std::string strValue;
334 [ + - + - : 25161 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
335 [ + + ]: 25161 : if (!status.ok()) {
336 [ - + ]: 18478 : if (status.IsNotFound())
337 : : return false;
338 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
339 [ # # ]: 0 : HandleError(status);
340 : : }
341 : : return true;
342 : 25161 : }
343 : :
344 : 103508 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
345 : : {
346 : 103508 : leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
347 : 103508 : leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
348 : 103508 : uint64_t size = 0;
349 : 103508 : leveldb::Range range(slKey1, slKey2);
350 : 103508 : DBContext().pdb->GetApproximateSizes(&range, 1, &size);
351 : 103508 : return size;
352 : : }
353 : :
354 : 7955 : bool CDBWrapper::IsEmpty()
355 : : {
356 [ + - ]: 7955 : std::unique_ptr<CDBIterator> it(NewIterator());
357 [ + - ]: 7955 : it->SeekToFirst();
358 [ + - ]: 15910 : return !(it->Valid());
359 : 7955 : }
360 : :
361 : 173008 : struct CDBIterator::IteratorImpl {
362 : : const std::unique_ptr<leveldb::Iterator> iter;
363 : :
364 : 173008 : explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
365 : : };
366 : :
367 : 173008 : CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
368 [ + - ]: 173008 : m_impl_iter(std::move(_piter))
369 : : {
370 [ + - ]: 173008 : m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
371 : 173008 : }
372 : :
373 : 173008 : CDBIterator* CDBWrapper::NewIterator()
374 : : {
375 [ + - + - : 173008 : return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ - + - +
- ]
376 : : }
377 : :
378 : 116144 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
379 : : {
380 : 116144 : leveldb::Slice slKey(CharCast(key.data()), key.size());
381 : 116144 : m_impl_iter->iter->Seek(slKey);
382 : 116144 : }
383 : :
384 : 4856381 : std::span<const std::byte> CDBIterator::GetKeyImpl() const
385 : : {
386 : : // The returned span borrows from the current iterator entry and is only
387 : : // valid until the iterator is advanced.
388 : 4856381 : return MakeByteSpan(m_impl_iter->iter->key());
389 : : }
390 : :
391 : 4773075 : std::span<const std::byte> CDBIterator::GetValueImpl() const
392 : : {
393 : 4773075 : return MakeByteSpan(m_impl_iter->iter->value());
394 : : }
395 : :
396 : 173008 : CDBIterator::~CDBIterator() = default;
397 : 4987109 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
398 : 56864 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
399 : 4814101 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
400 : :
401 : : namespace dbwrapper_private {
402 : :
403 : 13470575 : const Obfuscation& GetObfuscation(const CDBWrapper& w)
404 : : {
405 : 13470575 : return w.m_obfuscation;
406 : : }
407 : :
408 : : } // namespace dbwrapper_private
|