Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
dbwrapper.cpp
Go to the documentation of this file.
1// Copyright (c) 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#include <compat/byteswap.h>
7#include <random.h>
8#include <sync.h>
10#include <test/fuzz/fuzz.h>
11#include <test/fuzz/util.h>
12#include <test/util/random.h>
14#include <util/byte_units.h>
15#include <util/check.h>
16#include <util/threadpool.h>
17
18#include <leveldb/env.h>
19#include <leveldb/helpers/memenv/memenv.h>
20
21#include <algorithm>
22#include <cstdint>
23#include <deque>
24#include <functional>
25#include <future>
26#include <latch>
27#include <map>
28#include <memory>
29#include <numeric>
30#include <optional>
31#include <set>
32#include <span>
33#include <string>
34#include <tuple>
35#include <vector>
36
37namespace {
38
59class DeterministicEnv final : public leveldb::EnvWrapper
60{
61 using WorkFunction = void (*)(void*);
62
63 struct Work {
64 WorkFunction function;
65 void* arg;
66 };
67
68 Mutex m_mutex;
69 std::deque<Work> m_queue GUARDED_BY(m_mutex);
70
71public:
72 explicit DeterministicEnv(leveldb::Env* base) : EnvWrapper(base) {}
73
74 void Schedule(WorkFunction function, void* arg) override EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
75 {
76 LOCK(m_mutex);
77 m_queue.push_back({function, arg});
78 }
79
82 bool RunOne() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
83 {
84 Work work;
85 {
86 LOCK(m_mutex);
87 if (m_queue.empty()) return false;
88 work = m_queue.front();
89 m_queue.pop_front();
90 }
91 work.function(work.arg);
92 return true;
93 }
94
96 void DrainWork() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { while (RunOne()) {} }
97};
98
99constexpr size_t MAX_VALUE_LEN{4096};
100constexpr uint8_t MAX_VALUE_MULTIPLIER{8};
101constexpr size_t WRITE_BATCH_HEADER{12}; // See kHeader in db/write_batch.cc
102
105const std::string OBFUSCATION_KEY{"\000obfuscate_key", 14};
106
110std::vector<uint8_t> MakeValue(uint16_t key, uint32_t size)
111{
112 std::vector<uint8_t> v(size);
113 std::iota(v.begin(), v.end(), static_cast<uint8_t>(key ^ (key >> 8)));
114 return v;
115}
116
119struct LevelDBBytewiseU16Cmp {
120 bool operator()(uint16_t a, uint16_t b) const { return internal_bswap_16(a) < internal_bswap_16(b); }
121};
122
124using Oracle = std::map<uint16_t, uint32_t, LevelDBBytewiseU16Cmp>;
125
126struct FailUnserialize {
127 template <typename Stream>
128 void Unserialize(Stream&) { throw std::ios_base::failure{"always fail"}; }
129};
130
133{
136 return static_cast<uint32_t>(len) * multiplier;
137}
138
142 bool obfuscate, std::optional<uint16_t> seek_key = std::nullopt)
143{
144 const std::unique_ptr<CDBIterator> it{dbw.NewIterator()};
145 auto oracle_it{seek_key ? oracle.lower_bound(*seek_key) : oracle.begin()};
146 if (seek_key) {
147 it->Seek(*seek_key);
148 } else {
149 it->SeekToFirst();
150 }
151 for (; it->Valid(); it->Next()) {
153 assert(it->GetKey(db_key));
154 if (oracle_it != oracle.end() && db_key == oracle_it->first) {
155 std::vector<uint8_t> db_value;
156 assert(it->GetValue(db_value));
158 ++oracle_it;
159 } else {
160 assert(obfuscate);
161 std::string key_str;
162 assert(it->GetKey(key_str));
163 assert(key_str == OBFUSCATION_KEY);
164 }
165 }
166 assert(oracle_it == oracle.end());
167}
168
170constexpr size_t MAX_READ_WORKERS{8};
171
173constexpr size_t MAX_READ_QUERIES_PER_WORKER{128};
174
175ThreadPool g_read_pool{"dbfuzz"};
176
178{
179 if (!g_read_pool.WorkersCount()) g_read_pool.Start(MAX_READ_WORKERS);
180}
181
183DBParams ConsumeDBParams(FuzzedDataProvider& provider, leveldb::Env* testing_env,
184 bool obfuscate, DBOptions options = {})
185{
186 return DBParams{
187 .path = "dbwrapper_fuzz",
188 .cache_bytes = provider.ConsumeIntegralInRange<size_t>(64 << 10, 1_MiB),
189 .obfuscate = obfuscate,
190 .bloom_filter = provider.ConsumeBool(),
191 .options = options,
192 .testing_env = testing_env,
193 .max_file_size = provider.ConsumeBool()
196 };
197}
198
199template <typename DrainWorkFn, typename RunOneFn>
201 leveldb::Env* testing_env,
205{
207
208 const bool obfuscate{provider.ConsumeBool()};
209
210 const auto make_db{[&](DBOptions options = {}) {
211 return std::make_unique<CDBWrapper>(ConsumeDBParams(provider, testing_env, obfuscate, options));
212 }};
213 std::unique_ptr<CDBWrapper> dbw{make_db()};
214
215 // Oracle: key → value size. Content is reconstructed via MakeValue().
217
219 CallOneOf(
220 provider,
221 // --- Mutations ---
222 [&] {
223 const auto key{ConsumeKey(provider)};
224 const auto size{ConsumeValueSize(provider)};
225 drain_work();
226 dbw->Write(key, MakeValue(key, size), /*fSync=*/provider.ConsumeBool());
227 oracle[key] = size;
228 },
229 [&] {
230 const auto key{ConsumeKey(provider)};
231 drain_work();
232 dbw->Erase(key, /*fSync=*/provider.ConsumeBool());
233 oracle.erase(key);
234 },
235 [&] {
236 CDBBatch batch{*dbw};
237 std::map<uint16_t, uint32_t> batch_writes;
238 std::set<uint16_t> batch_erases;
239 const auto fill{[&] {
241 const auto key{ConsumeKey(provider)};
242 if (provider.ConsumeBool()) {
243 const auto size{ConsumeValueSize(provider)};
244 batch.Write(key, MakeValue(key, size));
245 batch_writes[key] = size;
246 batch_erases.erase(key);
247 } else {
248 batch.Erase(key);
249 batch_erases.insert(key);
250 batch_writes.erase(key);
251 }
252 }
253 }};
254 fill();
255 if (provider.ConsumeBool()) {
256 assert(batch.ApproximateSize() >= WRITE_BATCH_HEADER);
257 batch.Clear();
258 assert(batch.ApproximateSize() == WRITE_BATCH_HEADER);
259 batch_writes.clear();
260 batch_erases.clear();
261 fill();
262 }
263 drain_work();
264 dbw->WriteBatch(batch, /*fSync=*/provider.ConsumeBool());
265 for (const auto& [k, v] : batch_writes) oracle[k] = v;
266 for (const auto& k : batch_erases) oracle.erase(k);
267 },
268 [&] {
269 drain_work();
270 dbw.reset();
271 DBOptions options{};
273 options.force_compact = true;
274 }
275 dbw = make_db(options);
276 VerifyIterator(*dbw, oracle, obfuscate);
277 },
278 // --- Reads ---
279 [&] {
280 const auto key{ConsumeKey(provider)};
281 std::vector<uint8_t> value;
282 const bool found{dbw->Read(key, value)};
283 if (const auto it{oracle.find(key)}; it != oracle.end()) {
284 assert(found && value == MakeValue(key, it->second));
285 } else {
286 assert(!found);
287 }
288 },
289 [&] {
290 const auto key{ConsumeKey(provider)};
291 assert(dbw->Exists(key) == oracle.contains(key));
292 },
293 [&] {
294 uint16_t key{};
295 if (!oracle.empty() && provider.ConsumeBool()) {
296 auto it{oracle.begin()};
297 std::advance(it, provider.ConsumeIntegralInRange<size_t>(0, oracle.size() - 1));
298 key = it->first;
299 } else {
300 key = ConsumeKey(provider);
301 }
302 FailUnserialize wrong_type;
303 assert(!dbw->Read(key, wrong_type));
304 },
305 [&] {
306 const auto seek_key{provider.ConsumeBool()
307 ? std::optional<uint16_t>{ConsumeKey(provider)}
308 : std::nullopt};
309 VerifyIterator(*dbw, oracle, obfuscate, seek_key);
310 },
311 // --- Stats ---
312 [&] {
313 assert(dbw->IsEmpty() == (oracle.empty() && !obfuscate));
314 },
315 [&] {
316 const auto [k1, k2]{std::minmax({ConsumeKey(provider), ConsumeKey(provider)}, LevelDBBytewiseU16Cmp{})};
317 const size_t estimate_size{dbw->EstimateSize(k1, k2)};
318 if (k1 == k2) assert(estimate_size == 0);
319 },
320 [&] {
321 (void)dbw->DynamicMemoryUsage();
322 },
323 // --- Compaction control (no-op when run_one is no-op) ---
324 [&] {
325 run_one();
326 });
327 }
328
329 VerifyIterator(*dbw, oracle, obfuscate);
330 drain_work();
331}
332
333} // namespace
334
335FUZZ_TARGET(dbwrapper, .init = [] { static auto setup{MakeNoLogFileContext<>()}; })
336{
337 FuzzedDataProvider provider{buffer.data(), buffer.size()};
338
339 const auto memenv{std::unique_ptr<leveldb::Env>{leveldb::NewMemEnv(leveldb::Env::Default())}};
340 DeterministicEnv det_env{memenv.get()};
343 [&] { det_env.DrainWork(); },
344 [&] { return det_env.RunOne(); },
345 /*allow_force_compact=*/false);
346}
347
349{
350 FuzzedDataProvider provider{buffer.data(), buffer.size()};
351
352 const auto memenv{std::unique_ptr<leveldb::Env>{leveldb::NewMemEnv(leveldb::Env::Default())}};
354 provider, memenv.get(),
355 /*drain_work=*/[] {},
356 /*run_one=*/[] { return false; },
357 /*allow_force_compact=*/true);
358}
359
361{
364
365 FuzzedDataProvider provider{buffer.data(), buffer.size()};
366
367 const auto memenv{std::unique_ptr<leveldb::Env>{leveldb::NewMemEnv(leveldb::Env::Default())}};
368 DeterministicEnv det_env{memenv.get()};
369
371
372 // Seed the DB. Drain work after small batches so we don't deadlock on a
373 // scheduled compaction.
374 const size_t num_entries{provider.ConsumeIntegralInRange<size_t>(100, 5'000)};
375 std::vector<uint16_t> keys;
378 constexpr size_t SEED_BATCH_SIZE{400};
379 for (size_t start{0}; start < num_entries; start += SEED_BATCH_SIZE) {
380 CDBBatch batch{db};
381 const size_t end{std::min(start + SEED_BATCH_SIZE, num_entries)};
382 for (size_t i{start}; i < end; ++i) {
383 const auto k{ConsumeKey(provider)};
384 const auto size{ConsumeValueSize(provider)};
385 batch.Write(k, MakeValue(k, size));
386 keys.push_back(k);
387 oracle[k] = size;
388 }
389 det_env.DrainWork();
390 db.WriteBatch(batch, /*fSync=*/true);
391 }
392
393 while (provider.ConsumeBool() && det_env.RunOne()) {}
394
395 // Build query list from seeded and random keys.
396 const size_t num_queries{provider.ConsumeIntegralInRange<size_t>(1, 2'000)};
397 enum class ReadOp { Read, Exists, IteratorSeek };
398 std::vector<std::tuple<ReadOp, uint16_t>> queries;
400 for (size_t i{0}; i < num_queries; ++i) {
402 const uint16_t key{provider.ConsumeBool()
403 ? keys[provider.ConsumeIntegralInRange<size_t>(0, keys.size() - 1)]
405 queries.emplace_back(op, key);
406 }
407
408
409 // Workers + main thread synchronize on the latch so all reads start together.
410 std::latch start_latch{static_cast<ptrdiff_t>(MAX_READ_WORKERS + 1)};
411 std::vector<std::function<void()>> tasks(MAX_READ_WORKERS);
413 std::ranges::generate(tasks, [&] {
414 return [&, seed = rng.rand256()] {
416 std::vector<size_t> order(queries.size());
417 std::iota(order.begin(), order.end(), size_t{0});
418 std::ranges::shuffle(order, thread_rng);
419 const size_t queries_to_run{std::min(queries.size(), MAX_READ_QUERIES_PER_WORKER)};
420 std::vector<uint8_t> v;
421 std::string key_str;
422 start_latch.arrive_and_wait();
423 const std::unique_ptr<CDBIterator> it{db.NewIterator()};
424 // Every read must agree with the oracle, the source of truth.
425 for (const auto i : std::span{order}.first(queries_to_run)) {
426 const auto& [op, key] = queries[i];
427 switch (op) {
428 case ReadOp::Read:
429 if (const auto oit{oracle.find(key)}; oit != oracle.end()) {
430 assert(db.Read(key, v) && v == MakeValue(key, oit->second));
431 } else {
432 assert(!db.Read(key, v));
433 }
434 break;
435 case ReadOp::Exists:
436 assert(db.Exists(key) == oracle.contains(key));
437 break;
439 it->Seek(key);
440 // Skip the obfuscation metadata entry (a non-uint16_t key) if we land
441 // on it, so the result matches the oracle, which only tracks user keys.
442 if (it->Valid() && it->GetKey(key_str) && key_str == OBFUSCATION_KEY) it->Next();
443 if (const auto oit{oracle.lower_bound(key)}; oit != oracle.end()) {
444 assert(it->Valid());
446 assert(it->GetKey(actual_key) && actual_key == oit->first);
447 assert(it->GetValue(v) && v == MakeValue(actual_key, oit->second));
448 } else {
449 assert(!it->Valid());
450 }
451 break;
452 }
453 }
454 };
455 });
456 auto futures{*Assert(g_read_pool.Submit(std::move(tasks)))};
457
458 // Release the workers and immediately run the queued compaction on this
459 // thread, so compaction races against the concurrent reads.
460 start_latch.arrive_and_wait();
461 det_env.DrainWork();
462
463 for (auto& fut : futures) fut.get();
464 det_env.DrainWork();
465}
constexpr uint16_t internal_bswap_16(uint16_t x)
Definition byteswap.h:28
#define Assert(val)
Identity function.
Definition check.h:119
Batch of changes queued to be written to a CDBWrapper.
Definition dbwrapper.h:90
void Write(const K &key, const V &value)
Definition dbwrapper.h:114
bool Read(const K &key, V &value) const
Wrapper around TryRead() that preserves the original Read() semantics: returns true on success,...
Definition dbwrapper.h:288
CDBIterator * NewIterator()
bool Exists(const K &key) const
Definition dbwrapper.h:308
void WriteBatch(CDBBatch &batch, bool fSync=false)
void Write(const K &key, const V &value, bool fSync=false)
Definition dbwrapper.h:300
Fast randomness source.
Definition random.h:386
T ConsumeIntegralInRange(T min, T max)
T PickValueInArray(const T(&array)[size])
uint256 rand256() noexcept
generate a random uint256.
Definition random.h:317
Fixed-size thread pool for running arbitrary tasks concurrently.
Definition threadpool.h:48
void Start(int num_workers) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start worker threads.
Definition threadpool.h:105
constexpr size_t DBWRAPPER_MAX_FILE_SIZE
Definition dbwrapper.h:34
#define FUZZ_TARGET(...)
Definition fuzz.h:35
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition fuzz.h:22
Definition basic.cpp:11
void Unserialize(Stream &, V)=delete
User-controlled performance and debug options.
Definition dbwrapper.h:37
bool force_compact
Compact database on startup.
Definition dbwrapper.h:39
Application-specific storage settings.
Definition dbwrapper.h:43
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition dbwrapper.h:45
#define LOCK(cs)
Definition sync.h:268
det_env DrainWork()
std::vector< uint16_t > keys
Oracle oracle
CDBWrapper db
TestDbWrapper(provider, &det_env, [&] { det_env.DrainWork();}, [&] { return det_env.RunOne();}, false)
DeterministicEnv det_env
constexpr size_t SEED_BATCH_SIZE
const size_t num_entries
std::vector< std::function< void()> > tasks(MAX_READ_WORKERS)
ReadOp
@ IteratorSeek
FastRandomContext rng
std::latch start_latch
const size_t num_queries
auto futures
std::vector< std::tuple< ReadOp, uint16_t > > queries
SeedRandomStateForTest(SeedRand::ZEROS)
const auto memenv
FuzzedDataProvider provider
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:196
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition util.h:38
@ ZEROS
Seed with a compile time constant of zeros.
static int setup(void)
Definition tests.c:8289
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())