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)
19 LogPrintf("%s\n", status.ToString());
20 if (status.IsCorruption())
21 throw leveldb_error("Database corrupted");
22 if (status.IsIOError())
23 throw leveldb_error("Database I/O error");
24 if (status.IsNotFound())
25 throw leveldb_error("Database entry missing");
26 throw leveldb_error("Unknown database error");
29 static leveldb::Options GetOptions(size_t nCacheSize)
31 leveldb::Options options;
32 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
33 options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
34 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
35 options.compression = leveldb::kNoCompression;
36 options.max_open_files = 64;
37 if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
38 // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
39 // on corruption in later versions.
40 options.paranoid_checks = true;
45 CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory, bool fWipe)
48 readoptions.verify_checksums = true;
49 iteroptions.verify_checksums = true;
50 iteroptions.fill_cache = false;
51 syncoptions.sync = true;
52 options = GetOptions(nCacheSize);
53 options.create_if_missing = true;
55 penv = leveldb::NewMemEnv(leveldb::Env::Default());
59 LogPrintf("Wiping LevelDB in %s\n", path.string());
60 leveldb::DestroyDB(path.string(), options);
62 TryCreateDirectory(path);
63 LogPrintf("Opening LevelDB in %s\n", path.string());
65 leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
67 LogPrintf("Opened LevelDB successfully\n");
70 CLevelDBWrapper::~CLevelDBWrapper()
74 delete options.filter_policy;
75 options.filter_policy = NULL;
76 delete options.block_cache;
77 options.block_cache = NULL;
82 bool CLevelDBWrapper::WriteBatch(CLevelDBBatch& batch, bool fSync) throw(leveldb_error)
84 leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);