Raven Core  3.0.0
P2P Digital Currency
dbwrapper.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2016 The Bitcoin Core developers
2 // Copyright (c) 2017-2019 The Raven Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "dbwrapper.h"
7 
8 #include "fs.h"
9 #include "util.h"
10 #include "random.h"
11 
12 #include <leveldb/cache.h>
13 #include <leveldb/env.h>
14 #include <leveldb/filter_policy.h>
15 #include <memenv.h>
16 #include <stdint.h>
17 #include <algorithm>
18 
19 class CRavenLevelDBLogger : public leveldb::Logger {
20 public:
21  // This code is adapted from posix_logger.h, which is why it is using vsprintf.
22  // Please do not do this in normal code
23  void Logv(const char * format, va_list ap) override {
24  if (!LogAcceptCategory(BCLog::LEVELDB)) {
25  return;
26  }
27  char buffer[500];
28  for (int iter = 0; iter < 2; iter++) {
29  char* base;
30  int bufsize;
31  if (iter == 0) {
32  bufsize = sizeof(buffer);
33  base = buffer;
34  }
35  else {
36  bufsize = 30000;
37  base = new char[bufsize];
38  }
39  char* p = base;
40  char* limit = base + bufsize;
41 
42  // Print the message
43  if (p < limit) {
44  va_list backup_ap;
45  va_copy(backup_ap, ap);
46  // Do not use vsnprintf elsewhere in raven source code, see above.
47  p += vsnprintf(p, limit - p, format, backup_ap);
48  va_end(backup_ap);
49  }
50 
51  // Truncate to available space if necessary
52  if (p >= limit) {
53  if (iter == 0) {
54  continue; // Try again with larger buffer
55  }
56  else {
57  p = limit - 1;
58  }
59  }
60 
61  // Add newline if necessary
62  if (p == base || p[-1] != '\n') {
63  *p++ = '\n';
64  }
65 
66  assert(p <= limit);
67  base[std::min(bufsize - 1, (int)(p - base))] = '\0';
68  LogPrintStr(base);
69  if (base != buffer) {
70  delete[] base;
71  }
72  break;
73  }
74  }
75 };
76 
77 static void SetMaxOpenFiles(leveldb::Options *options) {
78  // On most platforms the default setting of max_open_files (which is 1000)
79  // is optimal. On Windows using a large file count is OK because the handles
80  // do not interfere with select() loops. On 64-bit Unix hosts this value is
81  // also OK, because up to that amount LevelDB will use an mmap
82  // implementation that does not use extra file descriptors (the fds are
83  // closed after being mmaped).
84  //
85  // Increasing the value beyond the default is dangerous because LevelDB will
86  // fall back to a non-mmap implementation when the file count is too large.
87  // On 32-bit Unix host we should decrease the value because the handles use
88  // up real fds, and we want to avoid fd exhaustion issues.
89  //
90  // See PR #12495 for further discussion.
91 
92  int default_open_files = options->max_open_files;
93 #ifndef WIN32
94  if (sizeof(void*) < 8) {
95  options->max_open_files = 64;
96  }
97 #endif
98  LogPrint(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
99  options->max_open_files, default_open_files);
100 }
101 
102 static leveldb::Options GetOptions(size_t nCacheSize, size_t maxFileSize)
103 {
104  leveldb::Options options;
105  options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
106  options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
107  options.filter_policy = leveldb::NewBloomFilterPolicy(10);
108  options.compression = leveldb::kNoCompression;
109  options.info_log = new CRavenLevelDBLogger();
110  options.max_file_size = maxFileSize;
111  if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
112  // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
113  // on corruption in later versions.
114  options.paranoid_checks = true;
115  }
116  SetMaxOpenFiles(&options);
117  return options;
118 }
119 
120 CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate, size_t maxFileSize)
121 {
122  penv = nullptr;
123  readoptions.verify_checksums = true;
124  iteroptions.verify_checksums = true;
125  iteroptions.fill_cache = false;
126  syncoptions.sync = true;
127  options = GetOptions(nCacheSize, maxFileSize);
128  options.create_if_missing = true;
129  if (fMemory) {
130  penv = leveldb::NewMemEnv(leveldb::Env::Default());
131  options.env = penv;
132  } else {
133  if (fWipe) {
134  LogPrintf("Wiping LevelDB in %s\n", path.string());
135  leveldb::Status result = leveldb::DestroyDB(path.string(), options);
137  }
138  TryCreateDirectories(path);
139  LogPrintf("Opening LevelDB in %s\n", path.string());
140  }
141  leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
143  LogPrintf("Opened LevelDB successfully\n");
144 
145  if (gArgs.GetBoolArg("-forcecompactdb", false)) {
146  LogPrintf("Starting database compaction of %s\n", path.string());
147  pdb->CompactRange(nullptr, nullptr);
148  LogPrintf("Finished database compaction of %s\n", path.string());
149  }
150 
151  // The base-case obfuscation key, which is a noop.
152  obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
153 
154  bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
155 
156  if (!key_exists && obfuscate && IsEmpty()) {
157  // Initialize non-degenerate obfuscation if it won't upset
158  // existing, non-obfuscated data.
159  std::vector<unsigned char> new_key = CreateObfuscateKey();
160 
161  // Write `new_key` so we don't obfuscate the key with itself
162  Write(OBFUSCATE_KEY_KEY, new_key);
163  obfuscate_key = new_key;
164 
165  LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
166  }
167 
168  LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
169 }
170 
172 {
173  delete pdb;
174  pdb = nullptr;
175  delete options.filter_policy;
176  options.filter_policy = nullptr;
177  delete options.info_log;
178  options.info_log = nullptr;
179  delete options.block_cache;
180  options.block_cache = nullptr;
181  delete penv;
182  options.env = nullptr;
183 }
184 
185 bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
186 {
187  leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
189  return true;
190 }
191 
192 // Prefixed with null character to avoid collisions with other keys
193 //
194 // We must use a string constructor which specifies length so that we copy
195 // past the null-terminator.
196 const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
197 
198 const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
199 
204 std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
205 {
206  unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
207  GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
208  return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);
209 
210 }
211 
213 {
214  std::unique_ptr<CDBIterator> it(NewIterator());
215  it->SeekToFirst();
216  return !(it->Valid());
217 }
218 
219 CDBIterator::~CDBIterator() { delete piter; }
220 bool CDBIterator::Valid() const { return piter->Valid(); }
221 void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
222 void CDBIterator::Next() { piter->Next(); }
223 
224 namespace dbwrapper_private {
225 
226 void HandleError(const leveldb::Status& status)
227 {
228  if (status.ok())
229  return;
230  LogPrintf("%s\n", status.ToString());
231  if (status.IsCorruption())
232  throw dbwrapper_error("Database corrupted");
233  if (status.IsIOError())
234  throw dbwrapper_error("Database I/O error");
235  if (status.IsNotFound())
236  throw dbwrapper_error("Database entry missing");
237  throw dbwrapper_error("Unknown database error");
238 }
239 
240 const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
241 {
242  return w.obfuscate_key;
243 }
244 
245 } // namespace dbwrapper_private
These should be considered an implementation detail of the specific database.
Definition: dbwrapper.cpp:224
void SeekToFirst()
Definition: dbwrapper.cpp:221
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:48
void Logv(const char *format, va_list ap) override
Definition: dbwrapper.cpp:23
CDBWrapper(const fs::path &path, size_t nCacheSize, bool fMemory=false, bool fWipe=false, bool obfuscate=false, size_t maxFileSize=2<< 20)
Definition: dbwrapper.cpp:120
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:470
void HandleError(const leveldb::Status &status)
Handle database error by throwing dbwrapper_error exception.
Definition: dbwrapper.cpp:226
leveldb::WriteBatch batch
Definition: dbwrapper.h:54
std::vector< unsigned char > CreateObfuscateKey() const
Returns a string (consisting of 8 random bytes) suitable for use as an obfuscating XOR key...
Definition: dbwrapper.cpp:204
#define LogPrintf(...)
Definition: util.h:149
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: util.cpp:684
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:955
bool IsEmpty()
Return true if the database managed by this class contains no entries.
Definition: dbwrapper.cpp:212
const std::vector< unsigned char > & GetObfuscateKey(const CDBWrapper &w)
Work around circular dependency, as well as for testing in dbwrapper_tests.
Definition: dbwrapper.cpp:240
#define LogPrint(category,...)
Definition: util.h:160
void Next()
Definition: dbwrapper.cpp:222
static const unsigned int OBFUSCATE_KEY_NUM_BYTES
the length of the obfuscate key in number of bytes
Definition: dbwrapper.h:209
ArgsManager gArgs
Definition: util.cpp:94
static const std::string OBFUSCATE_KEY_KEY
the key under which the obfuscation key is stored
Definition: dbwrapper.h:206
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:274
bool Valid() const
Definition: dbwrapper.cpp:220
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:185
std::vector< unsigned char > obfuscate_key
a key used for optional XOR-obfuscation of the database
Definition: dbwrapper.h:203
int LogPrintStr(const std::string &str)
Send a string to the log output.
Definition: util.cpp:346