Bitcoin ABC  0.26.3
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{fs::PathToString(path.stem())}, m_path{path}, m_is_memory{
122  fMemory} {
123  penv = nullptr;
124  readoptions.verify_checksums = true;
125  iteroptions.verify_checksums = true;
126  iteroptions.fill_cache = false;
127  syncoptions.sync = true;
128  options = GetOptions(nCacheSize);
129  options.create_if_missing = true;
130  if (fMemory) {
131  penv = leveldb::NewMemEnv(leveldb::Env::Default());
132  options.env = penv;
133  } else {
134  if (fWipe) {
135  LogPrintf("Wiping LevelDB in %s\n", fs::PathToString(path));
136  leveldb::Status result =
137  leveldb::DestroyDB(fs::PathToString(path), options);
139  }
140  TryCreateDirectories(path);
141  LogPrintf("Opening LevelDB in %s\n", fs::PathToString(path));
142  }
143  // PathToString() return value is safe to pass to leveldb open function,
144  // because on POSIX leveldb passes the byte string directly to ::open(), and
145  // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW
146  // (see env_posix.cc and env_windows.cc).
147  leveldb::Status status =
148  leveldb::DB::Open(options, fs::PathToString(path), &pdb);
150  LogPrintf("Opened LevelDB successfully\n");
151 
152  if (gArgs.GetBoolArg("-forcecompactdb", false)) {
153  LogPrintf("Starting database compaction of %s\n",
154  fs::PathToString(path));
155  pdb->CompactRange(nullptr, nullptr);
156  LogPrintf("Finished database compaction of %s\n",
157  fs::PathToString(path));
158  }
159 
160  // The base-case obfuscation key, which is a noop.
161  obfuscate_key = std::vector<uint8_t>(OBFUSCATE_KEY_NUM_BYTES, '\000');
162 
163  bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
164 
165  if (!key_exists && obfuscate && IsEmpty()) {
166  // Initialize non-degenerate obfuscation if it won't upset existing,
167  // non-obfuscated data.
168  std::vector<uint8_t> new_key = CreateObfuscateKey();
169 
170  // Write `new_key` so we don't obfuscate the key with itself
171  Write(OBFUSCATE_KEY_KEY, new_key);
172  obfuscate_key = new_key;
173 
174  LogPrintf("Wrote new obfuscate key for %s: %s\n",
176  }
177 
178  LogPrintf("Using obfuscation key for %s: %s\n", fs::PathToString(path),
180 }
181 
183  delete pdb;
184  pdb = nullptr;
185  delete options.filter_policy;
186  options.filter_policy = nullptr;
187  delete options.info_log;
188  options.info_log = nullptr;
189  delete options.block_cache;
190  options.block_cache = nullptr;
191  delete penv;
192  options.env = nullptr;
193 }
194 
195 bool CDBWrapper::WriteBatch(CDBBatch &batch, bool fSync) {
196  const bool log_memory = LogAcceptCategory(BCLog::LEVELDB);
197  double mem_before = 0;
198  if (log_memory) {
199  mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
200  }
201  leveldb::Status status =
202  pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
204  if (log_memory) {
205  double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
206  LogPrint(
208  "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
209  m_name, mem_before, mem_after);
210  }
211  return true;
212 }
213 
215  std::string memory;
216  if (!pdb->GetProperty("leveldb.approximate-memory-usage", &memory)) {
218  "Failed to get approximate-memory-usage property\n");
219  return 0;
220  }
221  return stoul(memory);
222 }
223 
224 // Prefixed with null character to avoid collisions with other keys
225 //
226 // We must use a string constructor which specifies length so that we copy past
227 // the null-terminator.
228 const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
229 
230 const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
231 
236 std::vector<uint8_t> CDBWrapper::CreateObfuscateKey() const {
237  std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES);
238  GetRandBytes(ret);
239  return ret;
240 }
241 
243  std::unique_ptr<CDBIterator> it(NewIterator());
244  it->SeekToFirst();
245  return !(it->Valid());
246 }
247 
249  delete piter;
250 }
251 bool CDBIterator::Valid() const {
252  return piter->Valid();
253 }
255  piter->SeekToFirst();
256 }
258  piter->Next();
259 }
260 
261 namespace dbwrapper_private {
262 
263 void HandleError(const leveldb::Status &status) {
264  if (status.ok()) {
265  return;
266  }
267  const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
268  LogPrintf("%s\n", errmsg);
269  LogPrintf("You can use -debug=leveldb to get more complete diagnostic "
270  "messages\n");
271  throw dbwrapper_error(errmsg);
272 }
273 
274 const std::vector<uint8_t> &GetObfuscateKey(const CDBWrapper &w) {
275  return w.obfuscate_key;
276 }
277 }; // namespace dbwrapper_private
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:665
void Logv(const char *format, va_list ap) override
Definition: dbwrapper.cpp:23
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:54
leveldb::WriteBatch batch
Definition: dbwrapper.h:59
leveldb::Iterator * piter
Definition: dbwrapper.h:124
bool Valid() const
Definition: dbwrapper.cpp:251
void SeekToFirst()
Definition: dbwrapper.cpp:254
void Next()
Definition: dbwrapper.cpp:257
CDBIterator * NewIterator()
Definition: dbwrapper.h:307
size_t DynamicMemoryUsage() const
Definition: dbwrapper.cpp:214
leveldb::Env * penv
custom environment this database is using (may be nullptr in case of default environment)
Definition: dbwrapper.h:183
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:195
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:241
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:236
std::string m_name
the name of this database
Definition: dbwrapper.h:204
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:266
std::vector< uint8_t > obfuscate_key
a key used for optional XOR-obfuscation of the database
Definition: dbwrapper.h:207
leveldb::Options options
database options used
Definition: dbwrapper.h:186
static const unsigned int OBFUSCATE_KEY_NUM_BYTES
the length of the obfuscate key in number of bytes
Definition: dbwrapper.h:213
static const std::string OBFUSCATE_KEY_KEY
the key under which the obfuscation key is stored
Definition: dbwrapper.h:210
leveldb::WriteOptions writeoptions
options used when writing to the database
Definition: dbwrapper.h:195
leveldb::WriteOptions syncoptions
options used when sync writing to the database
Definition: dbwrapper.h:198
CDBWrapper(const fs::path &path, size_t nCacheSize, bool fMemory=false, bool fWipe=false, bool obfuscate=false)
Definition: dbwrapper.cpp:119
leveldb::DB * pdb
the database itself
Definition: dbwrapper.h:201
leveldb::ReadOptions iteroptions
options used when iterating over values of the database
Definition: dbwrapper.h:192
bool IsEmpty()
Return true if the database managed by this class contains no entries.
Definition: dbwrapper.cpp:242
leveldb::ReadOptions readoptions
options used when reading from the database
Definition: dbwrapper.h:189
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
static leveldb::Options GetOptions(size_t nCacheSize)
Definition: dbwrapper.cpp:101
static void SetMaxOpenFiles(leveldb::Options *options)
Definition: dbwrapper.cpp:76
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:176
#define LogPrint(category,...)
Definition: logging.h:210
#define LogPrintfToBeContinued
These are aliases used to explicitly state that the message should not end with a newline character.
Definition: logging.h:222
#define LogPrintf(...)
Definition: logging.h:206
@ LEVELDB
Definition: logging.h:60
These should be considered an implementation detail of the specific database.
Definition: dbwrapper.cpp:261
void HandleError(const leveldb::Status &status)
Handle database error by throwing dbwrapper_error exception.
Definition: dbwrapper.cpp:263
const std::vector< uint8_t > & GetObfuscateKey(const CDBWrapper &w)
Work around circular dependency, as well as for testing in dbwrapper_tests.
Definition: dbwrapper.cpp:274
Filesystem operations and types.
Definition: fs.h:20
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
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:1112
void GetRandBytes(Span< uint8_t > bytes) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:639
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: system.cpp:1217
ArgsManager gArgs
Definition: system.cpp:80
assert(!tx.IsCoinBase())