Update CMakeLists.txt - play with openssl
[novacoin.git] / src / db.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_DB_H
6 #define BITCOIN_DB_H
7
8 #include "sync.h"
9 #include "serialize.h"
10 #include "script.h"
11 #include "streams.h"
12
13 #include <boost/filesystem/path.hpp>
14
15 #include <map>
16 #include <string>
17 #include <vector>
18
19 #include <db_cxx.h>
20
21 class CAddress;
22 class CAddrMan;
23 class CBlockLocator;
24 class CDiskBlockIndex;
25 class CDiskTxPos;
26 class CMasterKey;
27 class COutPoint;
28 class CTxIndex;
29 class CWallet;
30 class CWalletTx;
31
32 extern unsigned int nWalletDBUpdated;
33
34 void ThreadFlushWalletDB(void* parg);
35 bool DumpWallet(CWallet* pwallet, const std::string& strDest);
36 bool ImportWallet(CWallet* pwallet, const std::string& strLocation);
37
38 class CDBEnv
39 {
40 private:
41     bool fDbEnvInit;
42     bool fMockDb;
43     boost::filesystem::path pathEnv;
44     std::string strPath;
45
46     void EnvShutdown();
47
48 public:
49     mutable CCriticalSection cs_db;
50     DbEnv dbenv;
51     std::map<std::string, int> mapFileUseCount;
52     std::map<std::string, Db*> mapDb;
53
54     CDBEnv();
55     ~CDBEnv();
56     void MakeMock();
57     bool IsMock() { return fMockDb; };
58
59     /*
60      * Verify that database file strFile is OK. If it is not,
61      * call the callback to try to recover.
62      * This must be called BEFORE strFile is opened.
63      * Returns true if strFile is OK.
64      */
65     enum VerifyResult { VERIFY_OK, RECOVER_OK, RECOVER_FAIL };
66     VerifyResult Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile));
67     /*
68      * Salvage data from a file that Verify says is bad.
69      * fAggressive sets the DB_AGGRESSIVE flag (see berkeley DB->verify() method documentation).
70      * Appends binary key/value pairs to vResult, returns true if successful.
71      * NOTE: reads the entire database into memory, so cannot be used
72      * for huge databases.
73      */
74     typedef std::pair<std::vector<unsigned char>, std::vector<unsigned char> > KeyValPair;
75     bool Salvage(std::string strFile, bool fAggressive, std::vector<KeyValPair>& vResult);
76
77     bool Open(boost::filesystem::path pathEnv_);
78     void Close();
79     void Flush(bool fShutdown);
80     void CheckpointLSN(std::string strFile);
81
82     void CloseDb(const std::string& strFile);
83     bool RemoveDb(const std::string& strFile);
84
85     DbTxn *TxnBegin(int flags=DB_TXN_WRITE_NOSYNC)
86     {
87         DbTxn* ptxn = NULL;
88         int ret = dbenv.txn_begin(NULL, &ptxn, flags);
89         if (!ptxn || ret != 0)
90             return NULL;
91         return ptxn;
92     }
93 };
94
95 extern CDBEnv bitdb;
96
97
98 /** RAII class that provides access to a Berkeley database */
99 class CDB
100 {
101 protected:
102     Db* pdb;
103     std::string strFile;
104     DbTxn *activeTxn;
105     bool fReadOnly;
106
107     explicit CDB(const char* pszFile, const char* pszMode="r+");
108     ~CDB() { Close(); }
109 public:
110     void Close();
111 private:
112     CDB(const CDB&);
113     void operator=(const CDB&);
114
115 protected:
116     template<typename K, typename T>
117     bool Read(const K& key, T& value)
118     {
119         if (!pdb)
120             return false;
121
122         // Key
123         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
124         ssKey.reserve(1000);
125         ssKey << key;
126         Dbt datKey(&ssKey[0], (uint32_t)ssKey.size());
127
128         // Read
129         Dbt datValue;
130         datValue.set_flags(DB_DBT_MALLOC);
131         int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
132         memset(datKey.get_data(), 0, datKey.get_size());
133         if (datValue.get_data() == NULL)
134             return false;
135
136         // Unserialize value
137         try {
138             CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
139             ssValue >> value;
140         }
141         catch (const std::exception&) {
142             return false;
143         }
144
145         // Clear and free memory
146         memset(datValue.get_data(), 0, datValue.get_size());
147         free(datValue.get_data());
148         return (ret == 0);
149     }
150
151     template<typename K, typename T>
152     bool Write(const K& key, const T& value, bool fOverwrite=true)
153     {
154         if (!pdb)
155             return false;
156         if (fReadOnly)
157             assert(!"Write called on database in read-only mode");
158
159         // Key
160         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
161         ssKey.reserve(1000);
162         ssKey << key;
163         Dbt datKey(&ssKey[0], (uint32_t)ssKey.size());
164
165         // Value
166         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
167         ssValue.reserve(10000);
168         ssValue << value;
169         Dbt datValue(&ssValue[0], (uint32_t)ssValue.size());
170
171         // Write
172         int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
173
174         // Clear memory in case it was a private key
175         memset(datKey.get_data(), 0, datKey.get_size());
176         memset(datValue.get_data(), 0, datValue.get_size());
177         return (ret == 0);
178     }
179
180     template<typename K>
181     bool Erase(const K& key)
182     {
183         if (!pdb)
184             return false;
185         if (fReadOnly)
186             assert(!"Erase called on database in read-only mode");
187
188         // Key
189         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
190         ssKey.reserve(1000);
191         ssKey << key;
192         Dbt datKey(&ssKey[0], (uint32_t)ssKey.size());
193
194         // Erase
195         int ret = pdb->del(activeTxn, &datKey, 0);
196
197         // Clear memory
198         memset(datKey.get_data(), 0, datKey.get_size());
199         return (ret == 0 || ret == DB_NOTFOUND);
200     }
201
202     template<typename K>
203     bool Exists(const K& key)
204     {
205         if (!pdb)
206             return false;
207
208         // Key
209         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
210         ssKey.reserve(1000);
211         ssKey << key;
212         Dbt datKey(&ssKey[0], (uint32_t)ssKey.size());
213
214         // Exists
215         int ret = pdb->exists(activeTxn, &datKey, 0);
216
217         // Clear memory
218         memset(datKey.get_data(), 0, datKey.get_size());
219         return (ret == 0);
220     }
221
222     Dbc* GetCursor()
223     {
224         if (!pdb)
225             return NULL;
226         Dbc* pcursor = NULL;
227         int ret = pdb->cursor(NULL, &pcursor, 0);
228         if (ret != 0)
229             return NULL;
230         return pcursor;
231     }
232
233     int ReadAtCursor(Dbc* pcursor, CDataStream& ssKey, CDataStream& ssValue, unsigned int fFlags=DB_NEXT)
234     {
235         // Read at cursor
236         Dbt datKey;
237         if (fFlags == DB_SET || fFlags == DB_SET_RANGE || fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
238         {
239             datKey.set_data(&ssKey[0]);
240             datKey.set_size((uint32_t)ssKey.size());
241         }
242         Dbt datValue;
243         if (fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
244         {
245             datValue.set_data(&ssValue[0]);
246             datValue.set_size((uint32_t)ssValue.size());
247         }
248         datKey.set_flags(DB_DBT_MALLOC);
249         datValue.set_flags(DB_DBT_MALLOC);
250         int ret = pcursor->get(&datKey, &datValue, fFlags);
251         if (ret != 0)
252             return ret;
253         else if (datKey.get_data() == NULL || datValue.get_data() == NULL)
254             return 99999;
255
256         // Convert to streams
257         ssKey.SetType(SER_DISK);
258         ssKey.clear();
259         ssKey.write((char*)datKey.get_data(), datKey.get_size());
260         ssValue.SetType(SER_DISK);
261         ssValue.clear();
262         ssValue.write((char*)datValue.get_data(), datValue.get_size());
263
264         // Clear and free memory
265         memset(datKey.get_data(), 0, datKey.get_size());
266         memset(datValue.get_data(), 0, datValue.get_size());
267         free(datKey.get_data());
268         free(datValue.get_data());
269         return 0;
270     }
271
272 public:
273     bool TxnBegin()
274     {
275         if (!pdb || activeTxn)
276             return false;
277         DbTxn* ptxn = bitdb.TxnBegin();
278         if (!ptxn)
279             return false;
280         activeTxn = ptxn;
281         return true;
282     }
283
284     bool TxnCommit()
285     {
286         if (!pdb || !activeTxn)
287             return false;
288         int ret = activeTxn->commit(0);
289         activeTxn = NULL;
290         return (ret == 0);
291     }
292
293     bool TxnAbort()
294     {
295         if (!pdb || !activeTxn)
296             return false;
297         int ret = activeTxn->abort();
298         activeTxn = NULL;
299         return (ret == 0);
300     }
301
302     bool ReadVersion(int& nVersion)
303     {
304         nVersion = 0;
305         return Read(std::string("version"), nVersion);
306     }
307
308     bool WriteVersion(int nVersion)
309     {
310         return Write(std::string("version"), nVersion);
311     }
312
313     bool static Rewrite(const std::string& strFile, const char* pszSkip = NULL);
314 };
315
316
317 /** Access to the (IP) address database (peers.dat) */
318 class CAddrDB
319 {
320 private:
321     boost::filesystem::path pathAddr;
322     static unsigned char pchMessageStart[4];
323 public:
324     CAddrDB();
325     bool Write(const CAddrMan& addr);
326     bool Read(CAddrMan& addr);
327     static void SetMessageStart(unsigned char _pchMessageStart[]) { memcpy(CAddrDB::pchMessageStart, _pchMessageStart, sizeof(CAddrDB::pchMessageStart)); }
328 };
329
330 #endif // BITCOIN_DB_H