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.
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
21 unsigned int nWalletDBUpdated;
22 extern bool fUseMemoryLog;
31 void CDBEnv::EnvShutdown()
37 int ret = dbenv.close(0);
39 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
41 DbEnv(0u).remove(strPath.c_str(), 0);
44 CDBEnv::CDBEnv() : fDetachDB(false), fDbEnvInit(false), fMockDb(false), dbenv(DB_CXX_NO_EXCEPTIONS) { }
56 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
65 boost::filesystem::path pathDataDir = pathEnv;
66 strPath = pathDataDir.string();
67 boost::filesystem::path pathLogDir = pathDataDir / "database";
68 boost::filesystem::create_directory(pathLogDir);
69 boost::filesystem::path pathErrorFile = pathDataDir / "db.log";
70 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
72 unsigned int nEnvFlags = 0;
73 if (GetBoolArg("-privdb", true))
74 nEnvFlags |= DB_PRIVATE;
76 int nDbCache = GetArgInt("-dbcache", 25);
77 dbenv.set_lg_dir(pathLogDir.string().c_str());
78 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
79 dbenv.set_lg_bsize(1048576);
80 dbenv.set_lg_max(10485760);
82 // Bugfix: Bump lk_max_locks default to 537000, to safely handle reorgs with up to 5 blocks reversed
83 // dbenv.set_lk_max_locks(10000);
84 dbenv.set_lk_max_locks(537000);
86 dbenv.set_lk_max_objects(10000);
87 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
88 dbenv.set_flags(DB_AUTO_COMMIT, 1);
89 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
90 #ifdef DB_LOG_AUTO_REMOVE
91 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
93 int ret = dbenv.open(strPath.c_str(),
104 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
112 void CDBEnv::MakeMock()
115 throw runtime_error("CDBEnv::MakeMock(): already initialized");
118 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
120 printf("CDBEnv::MakeMock()\n");
122 dbenv.set_cachesize(1, 0, 1);
123 dbenv.set_lg_bsize(10485760*4);
124 dbenv.set_lg_max(10485760);
125 dbenv.set_lk_max_locks(10000);
126 dbenv.set_lk_max_objects(10000);
127 dbenv.set_flags(DB_AUTO_COMMIT, 1);
128 #ifdef DB_LOG_IN_MEMORY
129 dbenv.log_set_config(DB_LOG_IN_MEMORY, fUseMemoryLog ? 1 : 0);
131 int ret = dbenv.open(NULL,
141 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
147 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
150 assert(mapFileUseCount.count(strFile) == 0);
153 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
156 else if (recoverFunc == NULL)
160 bool fRecovered = (*recoverFunc)(*this, strFile);
161 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
164 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
165 std::vector<CDBEnv::KeyValPair >& vResult)
168 assert(mapFileUseCount.count(strFile) == 0);
170 u_int32_t flags = DB_SALVAGE;
171 if (fAggressive) flags |= DB_AGGRESSIVE;
173 stringstream strDump;
176 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
179 printf("ERROR: db salvage failed\n");
183 // Format of bdb dump is ascii lines:
192 while (!strDump.eof() && strLine != "HEADER=END")
193 getline(strDump, strLine); // Skip past header
195 std::string keyHex, valueHex;
196 while (!strDump.eof() && keyHex != "DATA=END")
198 getline(strDump, keyHex);
199 if (keyHex != "DATA=END")
201 getline(strDump, valueHex);
202 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
206 return (result == 0);
210 void CDBEnv::CheckpointLSN(std::string strFile)
212 dbenv.txn_checkpoint(0, 0, 0);
215 dbenv.lsn_reset(strFile.c_str(), 0);
219 CDB::CDB(const char *pszFile, const char* pszMode) :
220 pdb(NULL), activeTxn(NULL)
226 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
227 bool fCreate = strchr(pszMode, 'c') != NULL;
228 unsigned int nFlags = DB_THREAD;
234 if (!bitdb.Open(GetDataDir()))
235 throw runtime_error("env open failed");
238 ++bitdb.mapFileUseCount[strFile];
239 pdb = bitdb.mapDb[strFile];
242 pdb = new Db(&bitdb.dbenv, 0);
244 bool fMockDb = bitdb.IsMock();
247 DbMpoolFile*mpf = pdb->get_mpf();
248 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
250 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
253 ret = pdb->open(NULL, // Txn pointer
254 fMockDb ? NULL : pszFile, // Filename
255 "main", // Logical db name
256 DB_BTREE, // Database type
264 --bitdb.mapFileUseCount[strFile];
266 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
269 if (fCreate && !Exists(string("version")))
271 bool fTmp = fReadOnly;
273 WriteVersion(CLIENT_VERSION);
277 bitdb.mapDb[strFile] = pdb;
282 static bool IsChainFile(std::string strFile)
284 if (strFile == "blkindex.dat")
299 // Flush database activity from memory pool to disk log
300 unsigned int nMinutes = 0;
303 if (IsChainFile(strFile))
305 if (IsChainFile(strFile) && IsInitialBlockDownload())
308 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArgUInt("-dblogsize", 100)*1024 : 0, nMinutes, 0);
312 --bitdb.mapFileUseCount[strFile];
316 void CDBEnv::CloseDb(const string& strFile)
320 if (mapDb[strFile] != NULL)
322 // Close the database handle
323 Db* pdb = mapDb[strFile];
326 mapDb[strFile] = NULL;
331 bool CDBEnv::RemoveDb(const string& strFile)
333 this->CloseDb(strFile);
336 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
340 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
346 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
348 // Flush log data to the dat file
349 bitdb.CloseDb(strFile);
350 bitdb.CheckpointLSN(strFile);
351 bitdb.mapFileUseCount.erase(strFile);
353 bool fSuccess = true;
354 printf("Rewriting %s...\n", strFile.c_str());
355 string strFileRes = strFile + ".rewrite";
356 { // surround usage of db with extra {}
357 CDB db(strFile.c_str(), "r");
358 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
360 int ret = pdbCopy->open(NULL, // Txn pointer
361 strFileRes.c_str(), // Filename
362 "main", // Logical db name
363 DB_BTREE, // Database type
368 printf("Cannot create database file %s\n", strFileRes.c_str());
372 Dbc* pcursor = db.GetCursor();
376 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
377 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
378 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
379 if (ret == DB_NOTFOUND)
393 size_t pszSkipLen = strlen(pszSkip);
394 if (strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), pszSkipLen)) == 0)
398 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
402 ssValue << CLIENT_VERSION;
404 Dbt datKey(&ssKey[0], ssKey.size());
405 Dbt datValue(&ssValue[0], ssValue.size());
406 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_t 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" PRId64 "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 GetRandBytes((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 (const std::exception&) {
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 //Don't try to resize to a negative number if file is small
547 if ( dataSize < 0 ) dataSize = 0;
548 vector<unsigned char> vchData;
549 vchData.resize(dataSize);
552 // read data and checksum from file
554 filein.read((char *)&vchData[0], dataSize);
557 catch (const std::exception&) {
558 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
562 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
564 // verify stored checksum matches input data
565 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
566 if (hashIn != hashTmp)
567 return error("CAddrman::Read() : checksum mismatch; data corrupted");
569 unsigned char pchMsgTmp[4];
571 // de-serialize file header (pchMessageStart magic number) and
572 ssPeers >> FLATDATA(pchMsgTmp);
574 // verify the network matches ours
575 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
576 return error("CAddrman::Read() : invalid network magic number");
578 // de-serialize address data into one CAddrMan object
581 catch (const std::exception&) {
582 return error("CAddrman::Read() : I/O error or stream data corrupted");