1 // Copyright (c) 2012-2014 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include "leveldbwrapper.h"
9 #include <boost/filesystem.hpp>
10 #include <leveldb/cache.h>
11 #include <leveldb/env.h>
12 #include <leveldb/filter_policy.h>
15 void HandleError(const leveldb::Status &status) throw(leveldb_error) {
18 LogPrintf("%s\n", status.ToString());
19 if (status.IsCorruption())
20 throw leveldb_error("Database corrupted");
21 if (status.IsIOError())
22 throw leveldb_error("Database I/O error");
23 if (status.IsNotFound())
24 throw leveldb_error("Database entry missing");
25 throw leveldb_error("Unknown database error");
28 static leveldb::Options GetOptions(size_t nCacheSize) {
29 leveldb::Options options;
30 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
31 options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
32 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
33 options.compression = leveldb::kNoCompression;
34 options.max_open_files = 64;
35 if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
36 // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
37 // on corruption in later versions.
38 options.paranoid_checks = true;
43 CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {
45 readoptions.verify_checksums = true;
46 iteroptions.verify_checksums = true;
47 iteroptions.fill_cache = false;
48 syncoptions.sync = true;
49 options = GetOptions(nCacheSize);
50 options.create_if_missing = true;
52 penv = leveldb::NewMemEnv(leveldb::Env::Default());
56 LogPrintf("Wiping LevelDB in %s\n", path.string());
57 leveldb::DestroyDB(path.string(), options);
59 TryCreateDirectory(path);
60 LogPrintf("Opening LevelDB in %s\n", path.string());
62 leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
64 LogPrintf("Opened LevelDB successfully\n");
67 CLevelDBWrapper::~CLevelDBWrapper() {
70 delete options.filter_policy;
71 options.filter_policy = NULL;
72 delete options.block_cache;
73 options.block_cache = NULL;
78 bool CLevelDBWrapper::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {
79 leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);