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.
10 #include "checkpoints.h"
11 #include <boost/version.hpp>
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
23 unsigned int nWalletDBUpdated;
33 void CDBEnv::EnvShutdown()
39 int ret = dbenv.close(0);
41 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
43 DbEnv(0).remove(GetDataDir().string().c_str(), 0);
46 CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
60 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
69 filesystem::path pathDataDir = pathEnv;
70 filesystem::path pathLogDir = pathDataDir / "database";
71 filesystem::create_directory(pathLogDir);
72 filesystem::path pathErrorFile = pathDataDir / "db.log";
73 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
75 unsigned int nEnvFlags = 0;
76 if (GetBoolArg("-privdb", true))
77 nEnvFlags |= DB_PRIVATE;
79 int nDbCache = GetArg("-dbcache", 25);
80 dbenv.set_lg_dir(pathLogDir.string().c_str());
81 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
82 dbenv.set_lg_bsize(1048576);
83 dbenv.set_lg_max(10485760);
84 dbenv.set_lk_max_locks(40000);
85 dbenv.set_lk_max_objects(40000);
86 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
87 dbenv.set_flags(DB_AUTO_COMMIT, 1);
88 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
89 #ifdef DB_LOG_AUTO_REMOVE
90 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
92 int ret = dbenv.open(pathDataDir.string().c_str(),
103 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
110 void CDBEnv::MakeMock()
113 throw runtime_error("CDBEnv::MakeMock(): already initialized");
116 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
118 printf("CDBEnv::MakeMock()\n");
120 dbenv.set_cachesize(1, 0, 1);
121 dbenv.set_lg_bsize(10485760*4);
122 dbenv.set_lg_max(10485760);
123 dbenv.set_lk_max_locks(10000);
124 dbenv.set_lk_max_objects(10000);
125 dbenv.set_flags(DB_AUTO_COMMIT, 1);
126 #ifdef DB_LOG_IN_MEMORY
127 dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
129 int ret = dbenv.open(NULL,
139 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
145 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
148 assert(mapFileUseCount.count(strFile) == 0);
151 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
154 else if (recoverFunc == NULL)
158 bool fRecovered = (*recoverFunc)(*this, strFile);
159 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
162 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
163 std::vector<CDBEnv::KeyValPair >& vResult)
166 assert(mapFileUseCount.count(strFile) == 0);
168 u_int32_t flags = DB_SALVAGE;
169 if (fAggressive) flags |= DB_AGGRESSIVE;
171 stringstream strDump;
174 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
177 printf("ERROR: db salvage failed\n");
181 // Format of bdb dump is ascii lines:
190 while (!strDump.eof() && strLine != "HEADER=END")
191 getline(strDump, strLine); // Skip past header
193 std::string keyHex, valueHex;
194 while (!strDump.eof() && keyHex != "DATA=END")
196 getline(strDump, keyHex);
197 if (keyHex != "DATA_END")
199 getline(strDump, valueHex);
200 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
204 return (result == 0);
208 void CDBEnv::CheckpointLSN(std::string strFile)
210 dbenv.txn_checkpoint(0, 0, 0);
213 dbenv.lsn_reset(strFile.c_str(), 0);
217 CDB::CDB(const char *pszFile, const char* pszMode) :
218 pdb(NULL), activeTxn(NULL)
224 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
225 bool fCreate = strchr(pszMode, 'c');
226 unsigned int nFlags = DB_THREAD;
232 if (!bitdb.Open(GetDataDir()))
233 throw runtime_error("env open failed");
236 ++bitdb.mapFileUseCount[strFile];
237 pdb = bitdb.mapDb[strFile];
240 pdb = new Db(&bitdb.dbenv, 0);
242 bool fMockDb = bitdb.IsMock();
245 DbMpoolFile*mpf = pdb->get_mpf();
246 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
248 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
251 ret = pdb->open(NULL, // Txn pointer
252 fMockDb ? NULL : pszFile, // Filename
253 fMockDb ? pszFile : "main", // Logical db name
254 DB_BTREE, // Database type
262 --bitdb.mapFileUseCount[strFile];
264 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
267 if (fCreate && !Exists(string("version")))
269 bool fTmp = fReadOnly;
271 WriteVersion(CLIENT_VERSION);
275 bitdb.mapDb[strFile] = pdb;
280 static bool IsChainFile(std::string strFile)
282 if (strFile == "coins.dat" || strFile == "blktree.dat")
293 // Flush database activity from memory pool to disk log
294 unsigned int nMinutes = 0;
297 if (IsChainFile(strFile))
299 if (IsChainFile(strFile) && IsInitialBlockDownload())
302 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
318 --bitdb.mapFileUseCount[strFile];
322 void CDBEnv::CloseDb(const string& strFile)
326 if (mapDb[strFile] != NULL)
328 // Close the database handle
329 Db* pdb = mapDb[strFile];
332 mapDb[strFile] = NULL;
337 bool CDBEnv::RemoveDb(const string& strFile)
339 this->CloseDb(strFile);
342 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
346 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
352 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
354 // Flush log data to the dat file
355 bitdb.CloseDb(strFile);
356 bitdb.CheckpointLSN(strFile);
357 bitdb.mapFileUseCount.erase(strFile);
359 bool fSuccess = true;
360 printf("Rewriting %s...\n", strFile.c_str());
361 string strFileRes = strFile + ".rewrite";
362 { // surround usage of db with extra {}
363 CDB db(strFile.c_str(), "r");
364 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
366 int ret = pdbCopy->open(NULL, // Txn pointer
367 strFileRes.c_str(), // Filename
368 "main", // Logical db name
369 DB_BTREE, // Database type
374 printf("Cannot create database file %s\n", strFileRes.c_str());
378 Dbc* pcursor = db.GetCursor();
382 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
383 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
384 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
385 if (ret == DB_NOTFOUND)
397 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
399 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
403 ssValue << CLIENT_VERSION;
405 Dbt datKey(&ssKey[0], ssKey.size());
406 Dbt datValue(&ssValue[0], ssValue.size());
407 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
414 bitdb.CloseDb(strFile);
415 if (pdbCopy->close(0))
422 Db dbA(&bitdb.dbenv, 0);
423 if (dbA.remove(strFile.c_str(), NULL, 0))
425 Db dbB(&bitdb.dbenv, 0);
426 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
430 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
440 void CDBEnv::Flush(bool fShutdown)
442 int64 nStart = GetTimeMillis();
443 // Flush log data to the actual data file
444 // on all files that are not in use
445 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
450 map<string, int>::iterator mi = mapFileUseCount.begin();
451 while (mi != mapFileUseCount.end())
453 string strFile = (*mi).first;
454 int nRefCount = (*mi).second;
455 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
458 // Move log data to the dat file
460 printf("%s checkpoint\n", strFile.c_str());
461 dbenv.txn_checkpoint(0, 0, 0);
462 if (!IsChainFile(strFile) || fDetachDB) {
463 printf("%s detach\n", strFile.c_str());
465 dbenv.lsn_reset(strFile.c_str(), 0);
467 printf("%s closed\n", strFile.c_str());
468 mapFileUseCount.erase(mi++);
473 printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
477 if (mapFileUseCount.empty())
479 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
494 pathAddr = GetDataDir() / "peers.dat";
497 bool CAddrDB::Write(const CAddrMan& addr)
499 // Generate random temporary filename
500 unsigned short randv = 0;
501 RAND_bytes((unsigned char *)&randv, sizeof(randv));
502 std::string tmpfn = strprintf("peers.dat.%04x", randv);
504 // serialize addresses, checksum data up to that point, then append csum
505 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
506 ssPeers << FLATDATA(pchMessageStart);
508 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
511 // open temp output file, and associate with CAutoFile
512 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
513 FILE *file = fopen(pathTmp.string().c_str(), "wb");
514 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
516 return error("CAddrman::Write() : open failed");
518 // Write and commit header, data
522 catch (std::exception &e) {
523 return error("CAddrman::Write() : I/O error");
528 // replace existing peers.dat, if any, with new peers.dat.XXXX
529 if (!RenameOver(pathTmp, pathAddr))
530 return error("CAddrman::Write() : Rename-into-place failed");
535 bool CAddrDB::Read(CAddrMan& addr)
537 // open input file, and associate with CAutoFile
538 FILE *file = fopen(pathAddr.string().c_str(), "rb");
539 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
541 return error("CAddrman::Read() : open failed");
543 // use file size to size memory buffer
544 int fileSize = GetFilesize(filein);
545 int dataSize = fileSize - sizeof(uint256);
546 vector<unsigned char> vchData;
547 vchData.resize(dataSize);
550 // read data and checksum from file
552 filein.read((char *)&vchData[0], dataSize);
555 catch (std::exception &e) {
556 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
560 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
562 // verify stored checksum matches input data
563 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
564 if (hashIn != hashTmp)
565 return error("CAddrman::Read() : checksum mismatch; data corrupted");
567 // de-serialize address data
568 unsigned char pchMsgTmp[4];
570 ssPeers >> FLATDATA(pchMsgTmp);
573 catch (std::exception &e) {
574 return error("CAddrman::Read() : I/O error or stream data corrupted");
577 // finally, verify the network matches ours
578 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
579 return error("CAddrman::Read() : invalid network magic number");