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 <logging.h>
18 : : #include <random.h>
19 : : #include <serialize.h>
20 : : #include <span.h>
21 : : #include <streams.h>
22 : : #include <util/byte_units.h>
23 : : #include <util/fs.h>
24 : : #include <util/fs_helpers.h>
25 : : #include <util/log.h>
26 : : #include <util/obfuscation.h>
27 : : #include <util/strencodings.h>
28 : :
29 : : #include <algorithm>
30 : : #include <cassert>
31 : : #include <cstdarg>
32 : : #include <cstdint>
33 : : #include <cstdio>
34 : : #include <memory>
35 : : #include <optional>
36 : : #include <utility>
37 : :
38 : 31814118 : static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); }
39 : :
40 : 0 : bool DestroyDB(const std::string& path_str)
41 : : {
42 [ # # ]: 0 : return leveldb::DestroyDB(path_str, {}).ok();
43 : : }
44 : :
45 : : /** Handle database error by throwing dbwrapper_error exception.
46 : : */
47 : 3479307 : static void HandleError(const leveldb::Status& status)
48 : : {
49 [ + - ]: 3479307 : if (status.ok())
50 : 3479307 : return;
51 [ # # ]: 0 : const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
52 [ # # ]: 0 : LogError("%s", errmsg);
53 [ # # ]: 0 : LogInfo("You can use -debug=leveldb to get more complete diagnostic messages");
54 [ # # ]: 0 : throw dbwrapper_error(errmsg);
55 : 0 : }
56 : :
57 : 12516 : class CBitcoinLevelDBLogger : public leveldb::Logger {
58 : : public:
59 : : // This code is adapted from posix_logger.h, which is why it is using vsprintf.
60 : : // Please do not do this in normal code
61 : 28348 : void Logv(const char * format, va_list ap) override {
62 [ - + ]: 28348 : if (!LogAcceptCategory(BCLog::LEVELDB, util::log::Level::Debug)) {
63 : : return;
64 : : }
65 : : char buffer[500];
66 [ # # ]: 0 : for (int iter = 0; iter < 2; iter++) {
67 : 0 : char* base;
68 : 0 : int bufsize;
69 [ # # ]: 0 : if (iter == 0) {
70 : : bufsize = sizeof(buffer);
71 : : base = buffer;
72 : : }
73 : : else {
74 : 0 : bufsize = 30000;
75 : 0 : base = new char[bufsize];
76 : : }
77 : 0 : char* p = base;
78 : 0 : char* limit = base + bufsize;
79 : :
80 : : // Print the message
81 [ # # ]: 0 : if (p < limit) {
82 : 0 : va_list backup_ap;
83 : 0 : va_copy(backup_ap, ap);
84 : : // Do not use vsnprintf elsewhere in bitcoin source code, see above.
85 : 0 : p += vsnprintf(p, limit - p, format, backup_ap);
86 : 0 : va_end(backup_ap);
87 : : }
88 : :
89 : : // Truncate to available space if necessary
90 [ # # ]: 0 : if (p >= limit) {
91 [ # # ]: 0 : if (iter == 0) {
92 : 0 : continue; // Try again with larger buffer
93 : : }
94 : : else {
95 : 0 : p = limit - 1;
96 : : }
97 : : }
98 : :
99 : : // Add newline if necessary
100 [ # # # # ]: 0 : if (p == base || p[-1] != '\n') {
101 : 0 : *p++ = '\n';
102 : : }
103 : :
104 [ # # ]: 0 : assert(p <= limit);
105 [ # # ]: 0 : base[std::min(bufsize - 1, (int)(p - base))] = '\0';
106 [ # # ]: 0 : LogDebug(BCLog::LEVELDB, "%s\n", util::RemoveSuffixView(base, "\n"));
107 [ # # ]: 0 : if (base != buffer) {
108 [ # # ]: 0 : delete[] base;
109 : : }
110 : : break;
111 : : }
112 : : }
113 : : };
114 : :
115 : 12516 : static void SetMaxOpenFiles(leveldb::Options *options) {
116 : : // On most platforms the default setting of max_open_files (which is 1000)
117 : : // is optimal. On Windows using a large file count is OK because the handles
118 : : // do not interfere with select() loops. On 64-bit Unix hosts this value is
119 : : // also OK, because up to that amount LevelDB will use an mmap
120 : : // implementation that does not use extra file descriptors (the fds are
121 : : // closed after being mmap'ed).
122 : : //
123 : : // Increasing the value beyond the default is dangerous because LevelDB will
124 : : // fall back to a non-mmap implementation when the file count is too large.
125 : : // On 32-bit Unix host we should decrease the value because the handles use
126 : : // up real fds, and we want to avoid fd exhaustion issues.
127 : : //
128 : : // See PR #12495 for further discussion.
129 : :
130 : 12516 : int default_open_files = options->max_open_files;
131 : : #ifndef WIN32
132 : 12516 : if (sizeof(void*) < 8) {
133 : : options->max_open_files = 64;
134 : : }
135 : : #endif
136 [ - + ]: 12516 : LogDebug(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
137 : : options->max_open_files, default_open_files);
138 : 12516 : }
139 : :
140 : 12516 : static leveldb::Options GetOptions(size_t nCacheSize)
141 : : {
142 : 12516 : leveldb::Options options;
143 : 12516 : options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
144 : 12516 : options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
145 : 12516 : options.filter_policy = leveldb::NewBloomFilterPolicy(10);
146 : 12516 : options.compression = leveldb::kNoCompression;
147 [ - + ]: 12516 : options.info_log = new CBitcoinLevelDBLogger();
148 : 12516 : if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
149 : : // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
150 : : // on corruption in later versions.
151 : 12516 : options.paranoid_checks = true;
152 : : }
153 [ - + ]: 12516 : options.max_file_size = std::max(options.max_file_size, DBWRAPPER_MAX_FILE_SIZE);
154 : 12516 : SetMaxOpenFiles(&options);
155 : 12516 : return options;
156 : : }
157 : :
158 [ + - ]: 6933582 : struct CDBBatch::WriteBatchImpl {
159 : : leveldb::WriteBatch batch;
160 : : };
161 : :
162 : 3466791 : CDBBatch::CDBBatch(const CDBWrapper& _parent)
163 : 3466791 : : parent{_parent},
164 : 3466791 : m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()}
165 : : {
166 [ + - ]: 3466791 : m_key_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
167 [ + - ]: 3466791 : m_value_scratch.reserve(DBWRAPPER_PREALLOC_VALUE_SIZE);
168 [ + - ]: 3466791 : Clear();
169 : 3466791 : };
170 : :
171 : 3466791 : CDBBatch::~CDBBatch() = default;
172 : :
173 : 3466791 : void CDBBatch::Clear()
174 : : {
175 : 3466791 : m_impl_batch->batch.Clear();
176 [ - + - + ]: 3466791 : assert(m_key_scratch.empty());
177 [ - + - + ]: 3466791 : assert(m_value_scratch.empty());
178 : 3466791 : }
179 : :
180 : 8633267 : void CDBBatch::WriteImpl(std::span<const std::byte> key, DataStream& value)
181 : : {
182 : 8633267 : leveldb::Slice slKey(CharCast(key.data()), key.size());
183 [ - + ]: 8633267 : dbwrapper_private::GetObfuscation(parent)(value);
184 [ - + ]: 8633267 : leveldb::Slice slValue(CharCast(value.data()), value.size());
185 : 8633267 : m_impl_batch->batch.Put(slKey, slValue);
186 : 8633267 : }
187 : :
188 : 6743639 : void CDBBatch::EraseImpl(std::span<const std::byte> key)
189 : : {
190 : 6743639 : leveldb::Slice slKey(CharCast(key.data()), key.size());
191 : 6743639 : m_impl_batch->batch.Delete(slKey);
192 : 6743639 : }
193 : :
194 : 279412 : size_t CDBBatch::ApproximateSize() const
195 : : {
196 : 279412 : return m_impl_batch->batch.ApproximateSize();
197 : : }
198 : :
199 : : struct LevelDBContext {
200 : : //! custom environment this database is using (may be nullptr in case of default environment)
201 : : leveldb::Env* penv;
202 : :
203 : : //! database options used
204 : : leveldb::Options options;
205 : :
206 : : //! options used when reading from the database
207 : : leveldb::ReadOptions readoptions;
208 : :
209 : : //! options used when iterating over values of the database
210 : : leveldb::ReadOptions iteroptions;
211 : :
212 : : //! options used when writing to the database
213 : : leveldb::WriteOptions writeoptions;
214 : :
215 : : //! options used when sync writing to the database
216 : : leveldb::WriteOptions syncoptions;
217 : :
218 : : //! the database itself
219 : : leveldb::DB* pdb;
220 : : };
221 : :
222 : 12516 : CDBWrapper::CDBWrapper(const DBParams& params)
223 [ + - - + ]: 62580 : : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}
224 : : {
225 [ + - ]: 12516 : DBContext().penv = nullptr;
226 [ + - ]: 12516 : DBContext().readoptions.verify_checksums = true;
227 [ + - ]: 12516 : DBContext().iteroptions.verify_checksums = true;
228 [ + - ]: 12516 : DBContext().iteroptions.fill_cache = false;
229 [ + - ]: 12516 : DBContext().syncoptions.sync = true;
230 [ + - + - ]: 12516 : DBContext().options = GetOptions(params.cache_bytes);
231 [ + - ]: 12516 : DBContext().options.create_if_missing = true;
232 [ + - ]: 12516 : if (params.memory_only) {
233 [ + - + - : 12516 : DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default());
+ - ]
234 [ + - + - ]: 12516 : DBContext().options.env = DBContext().penv;
235 : : } else {
236 [ # # ]: 0 : if (params.wipe_data) {
237 [ # # # # ]: 0 : LogInfo("Wiping LevelDB in %s", fs::PathToString(params.path));
238 [ # # # # : 0 : leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options);
# # ]
239 [ # # ]: 0 : HandleError(result);
240 : 0 : }
241 [ # # ]: 0 : TryCreateDirectories(params.path);
242 [ # # # # ]: 0 : LogInfo("Opening LevelDB in %s", 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 [ + - - + : 25032 : leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb);
+ - + - ]
249 [ + - ]: 12516 : HandleError(status);
250 [ + - ]: 12516 : LogInfo("Opened LevelDB successfully");
251 : :
252 [ - + ]: 12516 : if (params.options.force_compact) {
253 [ # # # # ]: 0 : LogInfo("Starting database compaction of %s", fs::PathToString(params.path));
254 [ # # # # ]: 0 : DBContext().pdb->CompactRange(nullptr, nullptr);
255 [ # # # # ]: 0 : LogInfo("Finished database compaction of %s", fs::PathToString(params.path));
256 : : }
257 : :
258 [ + - + - : 12516 : if (!Read(OBFUSCATION_KEY, m_obfuscation) && params.obfuscate && IsEmpty()) {
+ + + - +
- ]
259 : : // Generate and write the new obfuscation key.
260 : 5338 : const Obfuscation obfuscation{FastRandomContext{}.randbytes<Obfuscation::KEY_SIZE>()};
261 [ - + ]: 5338 : assert(!m_obfuscation); // Make sure the key is written without obfuscation.
262 [ + - ]: 5338 : Write(OBFUSCATION_KEY, obfuscation);
263 : 5338 : m_obfuscation = obfuscation;
264 [ + - - + : 16014 : LogInfo("Wrote new obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - ]
265 : : }
266 [ + - - + : 37548 : LogInfo("Using obfuscation key for %s: %s", fs::PathToString(params.path), m_obfuscation.HexKey());
+ - - + ]
267 : 12516 : }
268 : :
269 : 12516 : CDBWrapper::~CDBWrapper()
270 : : {
271 [ + - ]: 12516 : delete DBContext().pdb;
272 : 12516 : DBContext().pdb = nullptr;
273 [ + - ]: 12516 : delete DBContext().options.filter_policy;
274 : 12516 : DBContext().options.filter_policy = nullptr;
275 [ + - ]: 12516 : delete DBContext().options.info_log;
276 : 12516 : DBContext().options.info_log = nullptr;
277 [ + - ]: 12516 : delete DBContext().options.block_cache;
278 : 12516 : DBContext().options.block_cache = nullptr;
279 [ + - ]: 12516 : delete DBContext().penv;
280 : 12516 : DBContext().options.env = nullptr;
281 : 12516 : }
282 : :
283 : 3466791 : void CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
284 : : {
285 : 3466791 : const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, util::log::Level::Debug);
286 : 3466791 : double mem_before = 0;
287 [ + + ]: 3466791 : if (log_memory) {
288 : 356 : mem_before = DynamicMemoryUsage() / double(1_MiB);
289 : : }
290 [ + + ]: 3466791 : leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch);
291 [ + - ]: 3466791 : HandleError(status);
292 [ + + ]: 3466791 : if (log_memory) {
293 [ + - ]: 356 : double mem_after{DynamicMemoryUsage() / double(1_MiB)};
294 [ + - + - : 356 : LogDebug(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
+ - ]
295 : : m_name, mem_before, mem_after);
296 : : }
297 : 3466791 : }
298 : :
299 : 712 : size_t CDBWrapper::DynamicMemoryUsage() const
300 : : {
301 [ + - ]: 712 : std::string memory;
302 : 712 : std::optional<size_t> parsed;
303 [ + - + - : 1424 : if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
+ - - + ]
304 [ # # # # : 0 : LogDebug(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
# # ]
305 : 0 : return 0;
306 : : }
307 : 712 : return parsed.value();
308 : 712 : }
309 : :
310 : 7495100 : std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key) const
311 : : {
312 [ + - ]: 7495100 : leveldb::Slice slKey(CharCast(key.data()), key.size());
313 [ + - ]: 7495100 : std::string strValue;
314 [ + - + - : 7495100 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
315 [ + + ]: 7495100 : if (!status.ok()) {
316 [ + - ]: 3774891 : if (status.IsNotFound())
317 : 3774891 : return std::nullopt;
318 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
319 [ # # ]: 0 : HandleError(status);
320 : : }
321 : 3720209 : return strValue;
322 : 7495100 : }
323 : :
324 : 6673 : bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
325 : : {
326 [ + - ]: 6673 : leveldb::Slice slKey(CharCast(key.data()), key.size());
327 : :
328 [ + - ]: 6673 : std::string strValue;
329 [ + - + - : 6673 : leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
+ - ]
330 [ + + ]: 6673 : if (!status.ok()) {
331 [ - + ]: 5514 : if (status.IsNotFound())
332 : : return false;
333 [ # # # # ]: 0 : LogError("LevelDB read failure: %s", status.ToString());
334 [ # # ]: 0 : HandleError(status);
335 : : }
336 : : return true;
337 : 6673 : }
338 : :
339 : 99320 : size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
340 : : {
341 : 99320 : leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
342 : 99320 : leveldb::Slice slKey2(CharCast(key2.data()), key2.size());
343 : 99320 : uint64_t size = 0;
344 : 99320 : leveldb::Range range(slKey1, slKey2);
345 : 99320 : DBContext().pdb->GetApproximateSizes(&range, 1, &size);
346 : 99320 : return size;
347 : : }
348 : :
349 : 5338 : bool CDBWrapper::IsEmpty()
350 : : {
351 [ + - ]: 5338 : std::unique_ptr<CDBIterator> it(NewIterator());
352 [ + - ]: 5338 : it->SeekToFirst();
353 [ + - ]: 10676 : return !(it->Valid());
354 : 5338 : }
355 : :
356 : 108870 : struct CDBIterator::IteratorImpl {
357 : : const std::unique_ptr<leveldb::Iterator> iter;
358 : :
359 : 108870 : explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {}
360 : : };
361 : :
362 : 108870 : CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent),
363 [ + - ]: 108870 : m_impl_iter(std::move(_piter))
364 : : {
365 [ + - ]: 108870 : m_scratch.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
366 : 108870 : }
367 : :
368 : 108870 : CDBIterator* CDBWrapper::NewIterator()
369 : : {
370 [ + - + - : 108870 : return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))};
+ - + - +
- ]
371 : : }
372 : :
373 : 103532 : void CDBIterator::SeekImpl(std::span<const std::byte> key)
374 : : {
375 : 103532 : leveldb::Slice slKey(CharCast(key.data()), key.size());
376 : 103532 : m_impl_iter->iter->Seek(slKey);
377 : 103532 : }
378 : :
379 : 4405720 : std::span<const std::byte> CDBIterator::GetKeyImpl() const
380 : : {
381 : : // The returned span borrows from the current iterator entry and is only
382 : : // valid until the iterator is advanced.
383 : 4405720 : return MakeByteSpan(m_impl_iter->iter->key());
384 : : }
385 : :
386 : 4404466 : std::span<const std::byte> CDBIterator::GetValueImpl() const
387 : : {
388 : 4404466 : return MakeByteSpan(m_impl_iter->iter->value());
389 : : }
390 : :
391 : 108870 : CDBIterator::~CDBIterator() = default;
392 : 4513336 : bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); }
393 : 5338 : void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); }
394 : 4404466 : void CDBIterator::Next() { m_impl_iter->iter->Next(); }
395 : :
396 : : namespace dbwrapper_private {
397 : :
398 : 13037733 : const Obfuscation& GetObfuscation(const CDBWrapper& w)
399 : : {
400 : 13037733 : return w.m_obfuscation;
401 : : }
402 : :
403 : : } // namespace dbwrapper_private
|