-
Notifications
You must be signed in to change notification settings - Fork 172
/
dbwrapper.h
439 lines (351 loc) · 13.7 KB
/
dbwrapper.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright (c) 2009-2012 The Bitcoin Developers.
// Authored by Google, Inc.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or https://opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_DBWRAPPER_H
#define BITCOIN_DBWRAPPER_H
#include "clientversion.h"
#include "main.h"
#include "streams.h"
#include <string>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
// Note in Bitcoin these are in txdb.h, and we will eventually move them there when the db code is refactored.
//! -dbcache default (MiB). This is for both bdb (the wallet) and leveldb (the transaction db).
static const int64_t nDefaultDbCache = 100;
//! max. -dbcache (MiB)
//! Note that Bitcoin uses sizeof(void*) > 4 ? 16384 : 1024, but this includes the mempool. In Gridcoin it does not,
//! so we use 1024 as the max.
static const int64_t nMaxDbCache = 1024;
//! min. -dbcache (MiB)
static const int64_t nMinDbCache = 4;
//! Max memory allocated to block tree DB (leveldb) cache. There is little performance gain over 1024 MB.
static const int64_t nMaxTxIndexCache = 1024;
// Class that provides access to a LevelDB. Note that this class is frequently
// instantiated on the stack and then destroyed again, so instantiation has to
// be very cheap. Unfortunately that means, a CTxDB instance is actually just a
// wrapper around some global state.
//
// A LevelDB is a key/value store that is optimized for fast usage on hard
// disks. It prefers long read/writes to seeks and is based on a series of
// sorted key/value mapping files that are stacked on top of each other, with
// newer files overriding older files. A background thread compacts them
// together when too many files stack up.
//
// Learn more: http://code.google.com/p/leveldb/
class CTxDB
{
public:
CTxDB(const char* pszMode="r+");
~CTxDB() {
// Note that this is not the same as Close() because it deletes only
// data scoped to this TxDB object.
delete activeBatch;
}
// Destroys the underlying shared global state accessed by this TxDB.
void Close();
private:
leveldb::DB *pdb; // Points to the global instance.
// A batch stores up writes and deletes for atomic application. When this
// field is non-nullptr, writes/deletes go there instead of directly to disk.
leveldb::WriteBatch *activeBatch;
leveldb::Options options;
bool fReadOnly;
int nVersion;
protected:
// Returns true and sets (value,false) if activeBatch contains the given key
// or leaves value alone and sets deleted = true if activeBatch contains a
// delete for it.
bool ScanBatch(const CDataStream &key, std::string *value, bool *deleted) const;
template<typename K, typename T>
bool Read(const K& key, T& value)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
std::string strValue;
bool readFromDb = true;
if (activeBatch) {
// First we must search for it in the currently pending set of
// changes to the db. If not found in the batch, go on to read disk.
bool deleted = false;
readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false;
if (deleted) {
return false;
}
}
if (readFromDb) {
leveldb::Status status = pdb->Get(leveldb::ReadOptions(),
ssKey.str(), &strValue);
if (!status.ok()) {
if (status.IsNotFound())
return false;
// Some unexpected error.
LogPrintf("LevelDB read failure: %s", status.ToString());
return false;
}
}
// Unserialize value
try {
CDataStream ssValue(MakeByteSpan(strValue), SER_DISK, CLIENT_VERSION);
ssValue >> value;
}
catch (std::exception &e) {
return false;
}
return true;
}
template<typename K, typename T>
bool Write(const K& key, const T& value)
{
if (fReadOnly)
assert(!"Write called on database in read-only mode");
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(90000);
ssValue << value;
if (activeBatch) {
activeBatch->Put(ssKey.str(), ssValue.str());
return true;
}
leveldb::Status status = pdb->Put(leveldb::WriteOptions(), ssKey.str(), ssValue.str());
if (!status.ok()) {
LogPrintf("LevelDB write failure: %s", status.ToString());
return false;
}
return true;
}
template<typename K>
bool Erase(const K& key)
{
if (!pdb)
return false;
if (fReadOnly)
assert(!"Erase called on database in read-only mode");
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
if (activeBatch) {
activeBatch->Delete(ssKey.str());
return true;
}
leveldb::Status status = pdb->Delete(leveldb::WriteOptions(), ssKey.str());
return (status.ok() || status.IsNotFound());
}
template<typename K>
bool Exists(const K& key)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
std::string unused;
if (activeBatch) {
bool deleted;
if (ScanBatch(ssKey, &unused, &deleted) && !deleted) {
return true;
}
}
leveldb::Status status = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused);
return status.IsNotFound() == false;
}
public:
bool TxnBegin();
bool TxnCommit();
bool TxnAbort()
{
delete activeBatch;
activeBatch = nullptr;
return true;
}
bool ReadVersion(int& nVersion)
{
nVersion = 0;
return Read(std::string("version"), nVersion);
}
bool WriteVersion(int nVersion)
{
return Write(std::string("version"), nVersion);
}
bool ReadTxIndex(uint256 hash, CTxIndex& txindex);
bool UpdateTxIndex(uint256 hash, const CTxIndex& txindex);
bool AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight);
bool EraseTxIndex(const CTransaction& tx);
bool ContainsTx(uint256 hash);
bool ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex);
bool ReadDiskTx(uint256 hash, CTransaction& tx);
bool ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex);
bool ReadDiskTx(COutPoint outpoint, CTransaction& tx);
bool ReadBlockIndex(uint256 hash, CDiskBlockIndex& blockindex);
bool WriteBlockIndex(const CDiskBlockIndex& blockindex);
bool ReadHashBestChain(uint256& hashBestChain);
bool WriteHashBestChain(uint256 hashBestChain);
bool ReadSyncCheckpoint(uint256& hashCheckpoint);
bool WriteSyncCheckpoint(uint256 hashCheckpoint);
bool ReadCheckpointPubKey(std::string& strPubKey);
bool WriteCheckpointPubKey(const std::string& strPubKey);
bool ReadGenericData(std::string KeyName, std::string& strValue);
bool WriteGenericData(const std::string& strKey,const std::string& strData);
template <typename K, typename V>
bool ReadGenericSerializable(K& key, V& serialized_data)
{
return Read(key, serialized_data);
}
template <typename K, typename V>
bool WriteGenericSerializable(K& key, const V& serializable_data)
{
return Write(key, serializable_data);
}
template <typename K>
bool EraseGenericSerializable(K& key)
{
return Erase(key);
}
template <typename T, typename K, typename V>
bool ReadGenericSerializablesToMap(T& key_type, std::map<K, V>& map, K& start_key_hint)
{
bool status = true;
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
std::pair<T, K> start_key = std::make_pair(key_type, start_key_hint);
ssStartKey << start_key;
iterator->Seek(ssStartKey.str());
while (iterator->Valid())
{
try
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(MakeByteSpan(iterator->key()));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(MakeByteSpan(iterator->value()));
T str_key_type;
ssKey >> str_key_type;
// Did we reach the end of the data to read?
if (str_key_type != key_type) break;
K map_key;
ssKey >> map_key;
V map_element;
ssValue >> map_element;
map[map_key] = map_element;
}
catch (const std::exception& e)
{
LogPrintf("ERROR: %s: Error %s occurred during retrieval of value during map load from LevelDB.",
__func__, e.what());
status = false;
}
iterator->Next();
}
delete iterator;
LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Loaded %u elements from LevelDB into map.", __func__, map.size());
return status;
}
//------- key type -- primary key --- map key --- value
template <typename T, typename K, typename K2, typename V>
bool ReadGenericSerializablesToMapWithForeignKey(T& key_type, std::map<K2, V>& map, K& start_key_hint)
{
bool status = true;
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
std::pair<T, K> start_key = std::make_pair(key_type, start_key_hint);
ssStartKey << start_key;
iterator->Seek(ssStartKey.str());
while (iterator->Valid())
{
try
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(MakeByteSpan(iterator->key()));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(MakeByteSpan(iterator->value()));
T str_key_type;
ssKey >> str_key_type;
// Did we reach the end of the data to read?
if (str_key_type != key_type) break;
// The actual LevelDB key is not used.
std::pair<K2, V> map_key_value_pair;
V map_element;
ssValue >> map_key_value_pair;
map[map_key_value_pair.first] = map_key_value_pair.second;
}
catch (const std::exception& e)
{
LogPrintf("ERROR: %s: Error %s occurred during retrieval of value during map load from LevelDB.",
__func__, e.what());
status = false;
}
iterator->Next();
}
delete iterator;
LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Loaded %u elements from LevelDB into map.", __func__, map.size());
return status;
}
template <typename T, typename K, typename V>
bool WriteGenericSerializablesFromMap(T& key_type, std::map<K, V>& map)
{
bool status = true;
for (const auto& iter : map)
{
std::pair<T, K> key = std::make_pair(key_type, iter.first);
status &= Write(key, iter.second);
}
LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Stored %u elements from map into LevelDB.", __func__, map.size());
return status;
}
//------- key type -- primary key --- map key --- value
template <typename T, typename K, typename K2, typename V>
bool WriteGenericSerializablesFromMapWithForeignKey(T& key_type, std::map<K2, V>& map, K& primary_key_example)
{
bool status = true;
for (const auto& iter : map)
{
std::pair<T, K> key = std::make_pair(key_type, iter.first);
status &= Write(key, std::make_pair(iter.first, iter.second));
}
LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Stored %u elements from map into LevelDB.", __func__, map.size());
return status;
}
template <typename T, typename K>
bool EraseGenericSerializablesByKeyType(T& key_type, K& start_key_hint)
{
bool status = true;
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
std::pair<T, K> start_key = std::make_pair(key_type, start_key_hint);
ssStartKey << start_key;
iterator->Seek(ssStartKey.str());
unsigned int number_erased = 0;
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(MakeByteSpan(iterator->key()));
T str_key_type;
ssKey >> str_key_type;
// Did we reach the end of the data to read?
if (str_key_type != key_type) break;
K map_key;
ssKey >> map_key;
std::pair<T, K> key = std::make_pair(str_key_type, map_key);
status &= Erase(key);
number_erased += status;
iterator->Next();
}
delete iterator;
LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Erased %u elements from LevelDB.",
__func__,
number_erased
);
return status;
}
bool LoadBlockIndex();
private:
bool LoadBlockIndexGuts();
};
#endif // BITCOIN_DBWRAPPER_H