1 // Copyright (c) 2012-2014 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.
9 #include <boost/filesystem.hpp>
11 #include <leveldb/cache.h>
12 #include <leveldb/env.h>
13 #include <leveldb/filter_policy.h>
17 static leveldb::Options GetOptions(size_t nCacheSize)
19 leveldb::Options options;
20 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
21 options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
22 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
23 options.compression = leveldb::kNoCompression;
24 options.max_open_files = 64;
25 if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
26 // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
27 // on corruption in later versions.
28 options.paranoid_checks = true;
33 CDBWrapper::CDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory, bool fWipe)
36 readoptions.verify_checksums = true;
37 iteroptions.verify_checksums = true;
38 iteroptions.fill_cache = false;
39 syncoptions.sync = true;
40 options = GetOptions(nCacheSize);
41 options.create_if_missing = true;
43 penv = leveldb::NewMemEnv(leveldb::Env::Default());
47 LogPrintf("Wiping LevelDB in %s\n", path.string());
48 leveldb::Status result = leveldb::DestroyDB(path.string(), options);
49 dbwrapper_private::HandleError(result);
51 TryCreateDirectory(path);
52 LogPrintf("Opening LevelDB in %s\n", path.string());
54 leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
55 dbwrapper_private::HandleError(status);
56 LogPrintf("Opened LevelDB successfully\n");
59 CDBWrapper::~CDBWrapper()
63 delete options.filter_policy;
64 options.filter_policy = NULL;
65 delete options.block_cache;
66 options.block_cache = NULL;
71 bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
73 leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
74 dbwrapper_private::HandleError(status);
78 bool CDBWrapper::IsEmpty()
80 boost::scoped_ptr<CDBIterator> it(NewIterator());
82 return !(it->Valid());
85 CDBIterator::~CDBIterator() { delete piter; }
86 bool CDBIterator::Valid() { return piter->Valid(); }
87 void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
88 void CDBIterator::Next() { piter->Next(); }
90 namespace dbwrapper_private {
92 void HandleError(const leveldb::Status& status)
96 LogPrintf("%s\n", status.ToString());
97 if (status.IsCorruption())
98 throw dbwrapper_error("Database corrupted");
99 if (status.IsIOError())
100 throw dbwrapper_error("Database I/O error");
101 if (status.IsNotFound())
102 throw dbwrapper_error("Database entry missing");
103 throw dbwrapper_error("Unknown database error");