Merge pull request #6599
[bitcoinplatinum.git] / src / leveldbwrapper.cpp
blob26cacf95ae91909642f2babf208d8fc468d5d11b
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.
5 #include "leveldbwrapper.h"
7 #include "util.h"
9 #include <boost/filesystem.hpp>
11 #include <leveldb/cache.h>
12 #include <leveldb/env.h>
13 #include <leveldb/filter_policy.h>
14 #include <memenv.h>
16 void HandleError(const leveldb::Status& status) throw(leveldb_error)
18 if (status.ok())
19 return;
20 LogPrintf("%s\n", status.ToString());
21 if (status.IsCorruption())
22 throw leveldb_error("Database corrupted");
23 if (status.IsIOError())
24 throw leveldb_error("Database I/O error");
25 if (status.IsNotFound())
26 throw leveldb_error("Database entry missing");
27 throw leveldb_error("Unknown database error");
30 static leveldb::Options GetOptions(size_t nCacheSize)
32 leveldb::Options options;
33 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
34 options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
35 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
36 options.compression = leveldb::kNoCompression;
37 options.max_open_files = 64;
38 if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
39 // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
40 // on corruption in later versions.
41 options.paranoid_checks = true;
43 return options;
46 CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory, bool fWipe)
48 penv = NULL;
49 readoptions.verify_checksums = true;
50 iteroptions.verify_checksums = true;
51 iteroptions.fill_cache = false;
52 syncoptions.sync = true;
53 options = GetOptions(nCacheSize);
54 options.create_if_missing = true;
55 if (fMemory) {
56 penv = leveldb::NewMemEnv(leveldb::Env::Default());
57 options.env = penv;
58 } else {
59 if (fWipe) {
60 LogPrintf("Wiping LevelDB in %s\n", path.string());
61 leveldb::Status result = leveldb::DestroyDB(path.string(), options);
62 HandleError(result);
64 TryCreateDirectory(path);
65 LogPrintf("Opening LevelDB in %s\n", path.string());
67 leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
68 HandleError(status);
69 LogPrintf("Opened LevelDB successfully\n");
72 CLevelDBWrapper::~CLevelDBWrapper()
74 delete pdb;
75 pdb = NULL;
76 delete options.filter_policy;
77 options.filter_policy = NULL;
78 delete options.block_cache;
79 options.block_cache = NULL;
80 delete penv;
81 options.env = NULL;
84 bool CLevelDBWrapper::WriteBatch(CLevelDBBatch& batch, bool fSync) throw(leveldb_error)
86 leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
87 HandleError(status);
88 return true;