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