Bitcoin ABC 0.30.7
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#include <util/fs_helpers.h>
9
10#include <leveldb/cache.h>
11#include <leveldb/env.h>
12#include <leveldb/filter_policy.h>
13#include <memenv.h>
14
15#include <algorithm>
16#include <cstdint>
17#include <memory>
18
19class CBitcoinLevelDBLogger : public leveldb::Logger {
20public:
21 // This code is adapted from posix_logger.h, which is why it is using
22 // vsprintf.
23 // Please do not do this in normal code
24 void Logv(const char *format, va_list ap) override {
26 return;
27 }
28 char buffer[500];
29 for (int iter = 0; iter < 2; iter++) {
30 char *base;
31 int bufsize;
32 if (iter == 0) {
33 bufsize = sizeof(buffer);
34 base = buffer;
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 bitcoin source code, see
47 // above.
48 p += vsnprintf(p, limit - p, format, backup_ap);
49 va_end(backup_ap);
50 }
51
52 // Truncate to available space if necessary
53 if (p >= limit) {
54 if (iter == 0) {
55 continue; // Try again with larger buffer
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';
69 "%s", base);
70 if (base != buffer) {
71 delete[] base;
72 }
73 break;
74 }
75 }
76};
77
78static void SetMaxOpenFiles(leveldb::Options *options) {
79 // On most platforms the default setting of max_open_files (which is 1000)
80 // is optimal. On Windows using a large file count is OK because the handles
81 // do not interfere with select() loops. On 64-bit Unix hosts this value is
82 // also OK, because up to that amount LevelDB will use an mmap
83 // implementation that does not use extra file descriptors (the fds are
84 // closed after being mmaped).
85 //
86 // Increasing the value beyond the default is dangerous because LevelDB will
87 // fall back to a non-mmap implementation when the file count is too large.
88 // On 32-bit Unix host we should decrease the value because the handles use
89 // up real fds, and we want to avoid fd exhaustion issues.
90 //
91 // See PR #12495 for further discussion.
92
93 int default_open_files = options->max_open_files;
94#ifndef WIN32
95 if (sizeof(void *) < 8) {
96 options->max_open_files = 64;
97 }
98#endif
99 LogPrint(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
100 options->max_open_files, default_open_files);
101}
102
103static leveldb::Options GetOptions(size_t nCacheSize) {
104 leveldb::Options options;
105 options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
106 // up to two write buffers may be held in memory simultaneously
107 options.write_buffer_size = nCacheSize / 4;
108 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
109 options.compression = leveldb::kNoCompression;
110 options.info_log = new CBitcoinLevelDBLogger();
111 if (leveldb::kMajorVersion > 1 ||
112 (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
113 // LevelDB versions before 1.16 consider short writes to be corruption.
114 // Only trigger error on corruption in later versions.
115 options.paranoid_checks = true;
116 }
117 SetMaxOpenFiles(&options);
118 return options;
119}
120
122 : m_name{fs::PathToString(params.path.stem())}, m_path{params.path},
123 m_is_memory{params.memory_only} {
124 penv = nullptr;
125 readoptions.verify_checksums = true;
126 iteroptions.verify_checksums = true;
127 iteroptions.fill_cache = false;
128 syncoptions.sync = true;
130 options.create_if_missing = true;
131 if (params.memory_only) {
132 penv = leveldb::NewMemEnv(leveldb::Env::Default());
133 options.env = penv;
134 } else {
135 if (params.wipe_data) {
136 LogPrintf("Wiping LevelDB in %s\n", fs::PathToString(params.path));
137 leveldb::Status result =
138 leveldb::DestroyDB(fs::PathToString(params.path), options);
140 }
142 LogPrintf("Opening LevelDB in %s\n", fs::PathToString(params.path));
143 }
144 // PathToString() return value is safe to pass to leveldb open function,
145 // because on POSIX leveldb passes the byte string directly to ::open(), and
146 // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW
147 // (see env_posix.cc and env_windows.cc).
148 leveldb::Status status =
149 leveldb::DB::Open(options, fs::PathToString(params.path), &pdb);
151 LogPrintf("Opened LevelDB successfully\n");
152
153 if (params.options.force_compact) {
154 LogPrintf("Starting database compaction of %s\n",
155 fs::PathToString(params.path));
156 pdb->CompactRange(nullptr, nullptr);
157 LogPrintf("Finished database compaction of %s\n",
158 fs::PathToString(params.path));
159 }
160
161 // The base-case obfuscation key, which is a noop.
162 obfuscate_key = std::vector<uint8_t>(OBFUSCATE_KEY_NUM_BYTES, '\000');
163
164 bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
165
166 if (!key_exists && params.obfuscate && IsEmpty()) {
167 // Initialize non-degenerate obfuscation if it won't upset existing,
168 // non-obfuscated data.
169 std::vector<uint8_t> new_key = CreateObfuscateKey();
170
171 // Write `new_key` so we don't obfuscate the key with itself
172 Write(OBFUSCATE_KEY_KEY, new_key);
173 obfuscate_key = new_key;
174
175 LogPrintf("Wrote new obfuscate key for %s: %s\n",
177 }
178
179 LogPrintf("Using obfuscation key for %s: %s\n",
181}
182
184 delete pdb;
185 pdb = nullptr;
186 delete options.filter_policy;
187 options.filter_policy = nullptr;
188 delete options.info_log;
189 options.info_log = nullptr;
190 delete options.block_cache;
191 options.block_cache = nullptr;
192 delete penv;
193 options.env = nullptr;
194}
195
196bool CDBWrapper::WriteBatch(CDBBatch &batch, bool fSync) {
197 const bool log_memory =
199 double mem_before = 0;
200 if (log_memory) {
201 mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
202 }
203 leveldb::Status status =
204 pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
206 if (log_memory) {
207 double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
208 LogPrint(
210 "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
211 m_name, mem_before, mem_after);
212 }
213 return true;
214}
215
217 std::string memory;
218 if (!pdb->GetProperty("leveldb.approximate-memory-usage", &memory)) {
220 "Failed to get approximate-memory-usage property\n");
221 return 0;
222 }
223 return stoul(memory);
224}
225
226// Prefixed with null character to avoid collisions with other keys
227//
228// We must use a string constructor which specifies length so that we copy past
229// the null-terminator.
230const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
231
232const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
233
238std::vector<uint8_t> CDBWrapper::CreateObfuscateKey() const {
239 std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES);
240 GetRandBytes(ret);
241 return ret;
242}
243
245 std::unique_ptr<CDBIterator> it(NewIterator());
246 it->SeekToFirst();
247 return !(it->Valid());
249
251 delete piter;
252}
253bool CDBIterator::Valid() const {
254 return piter->Valid();
255}
257 piter->SeekToFirst();
258}
260 piter->Next();
261}
262
264
265void HandleError(const leveldb::Status &status) {
266 if (status.ok()) {
267 return;
268 }
269 const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
270 LogPrintf("%s\n", errmsg);
271 LogPrintf("You can use -debug=leveldb to get more complete diagnostic "
272 "messages\n");
273 throw dbwrapper_error(errmsg);
274}
275
276const std::vector<uint8_t> &GetObfuscateKey(const CDBWrapper &w) {
277 return w.obfuscate_key;
278}
279}; // namespace dbwrapper_private
void Logv(const char *format, va_list ap) override
Definition: dbwrapper.cpp:24
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:78
leveldb::WriteBatch batch
Definition: dbwrapper.h:83
leveldb::Iterator * piter
Definition: dbwrapper.h:148
bool Valid() const
Definition: dbwrapper.cpp:253
void SeekToFirst()
Definition: dbwrapper.cpp:256
void Next()
Definition: dbwrapper.cpp:259
size_t DynamicMemoryUsage() const
Definition: dbwrapper.cpp:216
leveldb::Env * penv
custom environment this database is using (may be nullptr in case of default environment)
Definition: dbwrapper.h:207
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:196
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:254
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:238
CDBIterator * NewIterator()
Definition: dbwrapper.h:320
std::string m_name
the name of this database
Definition: dbwrapper.h:228
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:279
std::vector< uint8_t > obfuscate_key
a key used for optional XOR-obfuscation of the database
Definition: dbwrapper.h:231
CDBWrapper(const DBParams &params)
Definition: dbwrapper.cpp:121
leveldb::Options options
database options used
Definition: dbwrapper.h:210
static const unsigned int OBFUSCATE_KEY_NUM_BYTES
the length of the obfuscate key in number of bytes
Definition: dbwrapper.h:237
static const std::string OBFUSCATE_KEY_KEY
the key under which the obfuscation key is stored
Definition: dbwrapper.h:234
leveldb::WriteOptions writeoptions
options used when writing to the database
Definition: dbwrapper.h:219
leveldb::WriteOptions syncoptions
options used when sync writing to the database
Definition: dbwrapper.h:222
leveldb::DB * pdb
the database itself
Definition: dbwrapper.h:225
leveldb::ReadOptions iteroptions
options used when iterating over values of the database
Definition: dbwrapper.h:216
bool IsEmpty()
Return true if the database managed by this class contains no entries.
Definition: dbwrapper.cpp:244
leveldb::ReadOptions readoptions
options used when reading from the database
Definition: dbwrapper.h:213
static leveldb::Options GetOptions(size_t nCacheSize)
Definition: dbwrapper.cpp:103
static void SetMaxOpenFiles(leveldb::Options *options)
Definition: dbwrapper.cpp:78
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:287
#define LogPrintLevelToBeContinued
Definition: logging.h:261
#define LogPrint(category,...)
Definition: logging.h:238
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:186
#define LogPrintf(...)
Definition: logging.h:227
@ LEVELDB
Definition: logging.h:60
These should be considered an implementation detail of the specific database.
Definition: dbwrapper.cpp:263
void HandleError(const leveldb::Status &status)
Handle database error by throwing dbwrapper_error exception.
Definition: dbwrapper.cpp:265
const std::vector< uint8_t > & GetObfuscateKey(const CDBWrapper &w)
Work around circular dependency, as well as for testing in dbwrapper_tests.
Definition: dbwrapper.cpp:276
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
bool force_compact
Compact database on startup.
Definition: dbwrapper.h:28
Application-specific storage settings.
Definition: dbwrapper.h:32
DBOptions options
Passed-through options.
Definition: dbwrapper.h:45
bool obfuscate
If true, store data obfuscated via simple XOR.
Definition: dbwrapper.h:43
bool wipe_data
If true, remove all existing data.
Definition: dbwrapper.h:40
size_t cache_bytes
Configures various leveldb cache settings.
Definition: dbwrapper.h:36
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:34
bool memory_only
If true, use leveldb's memory environment.
Definition: dbwrapper.h:38
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
assert(!tx.IsCoinBase())