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