Replace CCoinsDB and CBlockTreeDB with LevelDB based implementations.
[novacoin.git] / src / leveldb.cpp
1 // Copyright (c) 2012 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.
4
5 #include "leveldb.h"
6 #include "util.h"
7
8 #include <leveldb/env.h>
9 #include <leveldb/cache.h>
10 #include <leveldb/filter_policy.h>
11 #include <memenv/memenv.h>
12
13 #include <boost/filesystem.hpp>
14
15 static leveldb::Options GetOptions() {
16     leveldb::Options options;
17     int nCacheSizeMB = GetArg("-dbcache", 25);
18     options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
19     options.filter_policy = leveldb::NewBloomFilterPolicy(10);
20     options.compression = leveldb::kNoCompression;
21     return options;
22 }
23
24 CLevelDB::CLevelDB(const boost::filesystem::path &path, bool fMemory) {
25     penv = NULL;
26     readoptions.verify_checksums = true;
27     iteroptions.verify_checksums = true;
28     iteroptions.fill_cache = false;
29     syncoptions.sync = true;
30     options = GetOptions();
31     options.create_if_missing = true;
32     if (fMemory) {
33         penv = leveldb::NewMemEnv(leveldb::Env::Default());
34         options.env = penv;
35     } else {
36         boost::filesystem::create_directory(path);
37         printf("Opening LevelDB in %s\n", path.string().c_str());
38     }
39     leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
40     if (!status.ok())
41         throw std::runtime_error(strprintf("CLevelDB(): error opening database environment %s", status.ToString().c_str()));
42     printf("Opened LevelDB successfully\n");
43 }
44
45 CLevelDB::~CLevelDB() {
46     delete pdb;
47     pdb = NULL;
48     delete options.filter_policy;
49     options.filter_policy = NULL;
50     delete options.block_cache;
51     options.block_cache = NULL;
52     delete penv;
53     options.env = NULL;
54 }
55
56 bool CLevelDB::WriteBatch(CLevelDBBatch &batch, bool fSync) {
57     leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
58     if (!status.ok()) {
59         printf("LevelDB write failure: %s\n", status.ToString().c_str());
60         return false;
61     }
62     return true;
63 }
64