You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.h 8.4KB

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