Bitcoin ABC  0.22.13
P2P Digital Currency
dbwrapper.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2016 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.
4 
5 #include <dbwrapper.h>
6 
7 #include <random.h>
8 
9 #include <leveldb/cache.h>
10 #include <leveldb/env.h>
11 #include <leveldb/filter_policy.h>
12 #include <memenv.h>
13 
14 #include <algorithm>
15 #include <cstdint>
16 #include <memory>
17 
18 class CBitcoinLevelDBLogger : public leveldb::Logger {
19 public:
20  // This code is adapted from posix_logger.h, which is why it is using
21  // vsprintf.
22  // Please do not do this in normal code
23  void Logv(const char *format, va_list ap) override {
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  } else {
35  bufsize = 30000;
36  base = new char[bufsize];
37  }
38  char *p = base;
39  char *limit = base + bufsize;
40 
41  // Print the message
42  if (p < limit) {
43  va_list backup_ap;
44  va_copy(backup_ap, ap);
45  // Do not use vsnprintf elsewhere in bitcoin source code, see
46  // 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  } else {
56  p = limit - 1;
57  }
58  }
59 
60  // Add newline if necessary
61  if (p == base || p[-1] != '\n') {
62  *p++ = '\n';
63  }
64 
65  assert(p <= limit);
66  base[std::min(bufsize - 1, (int)(p - base))] = '\0';
67  LogPrintfToBeContinued("leveldb: %s", base);
68  if (base != buffer) {
69  delete[] base;
70  }
71  break;
72  }
73  }
74 };
75 
76 static void SetMaxOpenFiles(leveldb::Options *options) {
77  // On most platforms the default setting of max_open_files (which is 1000)
78  // is optimal. On Windows using a large file count is OK because the handles
79  // do not interfere with select() loops. On 64-bit Unix hosts this value is
80  // also OK, because up to that amount LevelDB will use an mmap
81  // implementation that does not use extra file descriptors (the fds are
82  // closed after being mmaped).
83  //
84  // Increasing the value beyond the default is dangerous because LevelDB will
85  // fall back to a non-mmap implementation when the file count is too large.
86  // On 32-bit Unix host we should decrease the value because the handles use
87  // up real fds, and we want to avoid fd exhaustion issues.
88  //
89  // See PR #12495 for further discussion.
90 
91  int default_open_files = options->max_open_files;
92 #ifndef WIN32
93  if (sizeof(void *) < 8) {
94  options->max_open_files = 64;
95  }
96 #endif
97  LogPrint(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
98  options->max_open_files, default_open_files);
99 }
100 
101 static leveldb::Options GetOptions(size_t nCacheSize) {
102  leveldb::Options options;
103  options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
104  // up to two write buffers may be held in memory simultaneously
105  options.write_buffer_size = nCacheSize / 4;
106  options.filter_policy = leveldb::NewBloomFilterPolicy(10);
107  options.compression = leveldb::kNoCompression;
108  options.info_log = new CBitcoinLevelDBLogger();
109  if (leveldb::kMajorVersion > 1 ||
110  (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
111  // LevelDB versions before 1.16 consider short writes to be corruption.
112  // Only trigger error on corruption in later versions.
113  options.paranoid_checks = true;
114  }
115  SetMaxOpenFiles(&options);
116  return options;
117 }
118 
119 CDBWrapper::CDBWrapper(const fs::path &path, size_t nCacheSize, bool fMemory,
120  bool fWipe, bool obfuscate)
121  : m_name{path.stem().string()} {
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);
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<uint8_t>(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 existing,
158  // non-obfuscated data.
159  std::vector<uint8_t> 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(),
166  HexStr(obfuscate_key));
167  }
168 
169  LogPrintf("Using obfuscation key for %s: %s\n", path.string(),
170  HexStr(obfuscate_key));
171 }
172 
174  delete pdb;
175  pdb = nullptr;
176  delete options.filter_policy;
177  options.filter_policy = nullptr;
178  delete options.info_log;
179  options.info_log = nullptr;
180  delete options.block_cache;
181  options.block_cache = nullptr;
182  delete penv;
183  options.env = nullptr;
184 }
185 
186 bool CDBWrapper::WriteBatch(CDBBatch &batch, bool fSync) {
187  const bool log_memory = LogAcceptCategory(BCLog::LEVELDB);
188  double mem_before = 0;
189  if (log_memory) {
190  mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
191  }
192  leveldb::Status status =
193  pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
195  if (log_memory) {
196  double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
197  LogPrint(
199  "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
200  m_name, mem_before, mem_after);
201  }
202  return true;
203 }
204 
206  std::string memory;
207  if (!pdb->GetProperty("leveldb.approximate-memory-usage", &memory)) {
209  "Failed to get approximate-memory-usage property\n");
210  return 0;
211  }
212  return stoul(memory);
213 }
214 
215 // Prefixed with null character to avoid collisions with other keys
216 //
217 // We must use a string constructor which specifies length so that we copy past
218 // the null-terminator.
219 const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
220 
221 const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
222 
227 std::vector<uint8_t> CDBWrapper::CreateObfuscateKey() const {
228  uint8_t buff[OBFUSCATE_KEY_NUM_BYTES];
230  return std::vector<uint8_t>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);
231 }
232 
234  std::unique_ptr<CDBIterator> it(NewIterator());
235  it->SeekToFirst();
236  return !(it->Valid());
237 }
238 
240  delete piter;
241 }
242 bool CDBIterator::Valid() const {
243  return piter->Valid();
244 }
246  piter->SeekToFirst();
247 }
249  piter->Next();
250 }
251 
252 namespace dbwrapper_private {
253 
254 void HandleError(const leveldb::Status &status) {
255  if (status.ok()) {
256  return;
257  }
258  const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
259  LogPrintf("%s\n", errmsg);
260  LogPrintf("You can use -debug=leveldb to get more complete diagnostic "
261  "messages\n");
262  throw dbwrapper_error(errmsg);
263 }
264 
265 const std::vector<uint8_t> &GetObfuscateKey(const CDBWrapper &w) {
266  return w.obfuscate_key;
267 }
268 }; // namespace dbwrapper_private
These should be considered an implementation detail of the specific database.
Definition: dbwrapper.cpp:252
#define LogPrintfToBeContinued
These are aliases used to explicitly state that the message should not end with a newline character...
Definition: logging.h:204
#define LogPrint(category,...)
Definition: logging.h:192
void SeekToFirst()
Definition: dbwrapper.cpp:245
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:48
CDBWrapper(const fs::path &path, size_t nCacheSize, bool fMemory=false, bool fWipe=false, bool obfuscate=false)
Definition: dbwrapper.cpp:119
const std::vector< uint8_t > & GetObfuscateKey(const CDBWrapper &w)
Work around circular dependency, as well as for testing in dbwrapper_tests.
Definition: dbwrapper.cpp:265
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: system.cpp:1106
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:174
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:498
std::vector< uint8_t > obfuscate_key
a key used for optional XOR-obfuscation of the database
Definition: dbwrapper.h:202
void HandleError(const leveldb::Status &status)
Handle database error by throwing dbwrapper_error exception.
Definition: dbwrapper.cpp:254
leveldb::WriteBatch batch
Definition: dbwrapper.h:53
CDBIterator * NewIterator()
Definition: dbwrapper.h:297
leveldb::ReadOptions readoptions
options used when reading from the database
Definition: dbwrapper.h:184
void GetRandBytes(uint8_t *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:625
std::vector< uint8_t > CreateObfuscateKey() const
Returns a string (consisting of 8 random bytes) suitable for use as an obfuscating XOR key...
Definition: dbwrapper.cpp:227
size_t DynamicMemoryUsage() const
Definition: dbwrapper.cpp:205
void Logv(const char *format, va_list ap) override
Definition: dbwrapper.cpp:23
leveldb::WriteOptions syncoptions
options used when sync writing to the database
Definition: dbwrapper.h:193
leveldb::DB * pdb
the database itself
Definition: dbwrapper.h:196
leveldb::ReadOptions iteroptions
options used when iterating over values of the database
Definition: dbwrapper.h:187
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:1111
leveldb::WriteOptions writeoptions
options used when writing to the database
Definition: dbwrapper.h:190
bool IsEmpty()
Return true if the database managed by this class contains no entries.
Definition: dbwrapper.cpp:233
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:230
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:163
void Next()
Definition: dbwrapper.cpp:248
static const unsigned int OBFUSCATE_KEY_NUM_BYTES
the length of the obfuscate key in number of bytes
Definition: dbwrapper.h:208
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:256
std::string m_name
the name of this database
Definition: dbwrapper.h:199
leveldb::Env * penv
custom environment this database is using (may be nullptr in case of default environment) ...
Definition: dbwrapper.h:178
static const std::string OBFUSCATE_KEY_KEY
the key under which the obfuscation key is stored
Definition: dbwrapper.h:205
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
ArgsManager gArgs
Definition: system.cpp:76
static void SetMaxOpenFiles(leveldb::Options *options)
Definition: dbwrapper.cpp:76
bool Valid() const
Definition: dbwrapper.cpp:242
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:186
static leveldb::Options GetOptions(size_t nCacheSize)
Definition: dbwrapper.cpp:101
leveldb::Options options
database options used
Definition: dbwrapper.h:181