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 <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
20 unsigned int nWalletDBUpdated;
21 extern bool fUseMemoryLog;
30 void CDBEnv::EnvShutdown()
36 int ret = dbenv.close(0);
38 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
40 DbEnv(0u).remove(strPath.c_str(), 0);
43 CDBEnv::CDBEnv() : fDetachDB(false), fDbEnvInit(false), fMockDb(false), dbenv(DB_CXX_NO_EXCEPTIONS) { }
55 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
64 boost::filesystem::path pathDataDir = pathEnv;
65 strPath = pathDataDir.string();
66 boost::filesystem::path pathLogDir = pathDataDir / "database";
67 boost::filesystem::create_directory(pathLogDir);
68 boost::filesystem::path pathErrorFile = pathDataDir / "db.log";
69 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
71 unsigned int nEnvFlags = 0;
72 if (GetBoolArg("-privdb", true))
73 nEnvFlags |= DB_PRIVATE;
75 int nDbCache = GetArgInt("-dbcache", 25);
76 dbenv.set_lg_dir(pathLogDir.string().c_str());
77 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
78 dbenv.set_lg_bsize(1048576);
79 dbenv.set_lg_max(10485760);
81 // Bugfix: Bump lk_max_locks default to 537000, to safely handle reorgs with up to 5 blocks reversed
82 // dbenv.set_lk_max_locks(10000);
83 dbenv.set_lk_max_locks(537000);
85 dbenv.set_lk_max_objects(10000);
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(strPath.c_str(),
103 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
111 void CDBEnv::MakeMock()
114 throw runtime_error("CDBEnv::MakeMock(): already initialized");
117 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
119 printf("CDBEnv::MakeMock()\n");
121 dbenv.set_cachesize(1, 0, 1);
122 dbenv.set_lg_bsize(10485760*4);
123 dbenv.set_lg_max(10485760);
124 dbenv.set_lk_max_locks(10000);
125 dbenv.set_lk_max_objects(10000);
126 dbenv.set_flags(DB_AUTO_COMMIT, 1);
127 #ifdef DB_LOG_IN_MEMORY
128 dbenv.log_set_config(DB_LOG_IN_MEMORY, fUseMemoryLog ? 1 : 0);
130 int ret = dbenv.open(NULL,
140 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
146 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
149 assert(mapFileUseCount.count(strFile) == 0);
152 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
155 else if (recoverFunc == NULL)
159 bool fRecovered = (*recoverFunc)(*this, strFile);
160 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
163 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
164 std::vector<CDBEnv::KeyValPair >& vResult)
167 assert(mapFileUseCount.count(strFile) == 0);
169 u_int32_t flags = DB_SALVAGE;
170 if (fAggressive) flags |= DB_AGGRESSIVE;
172 stringstream strDump;
175 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
178 printf("ERROR: db salvage failed\n");
182 // Format of bdb dump is ascii lines:
191 while (!strDump.eof() && strLine != "HEADER=END")
192 getline(strDump, strLine); // Skip past header
194 std::string keyHex, valueHex;
195 while (!strDump.eof() && keyHex != "DATA=END")
197 getline(strDump, keyHex);
198 if (keyHex != "DATA=END")
200 getline(strDump, valueHex);
201 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
205 return (result == 0);
209 void CDBEnv::CheckpointLSN(std::string strFile)
211 dbenv.txn_checkpoint(0, 0, 0);
214 dbenv.lsn_reset(strFile.c_str(), 0);
218 CDB::CDB(const char *pszFile, const char* pszMode) :
219 pdb(NULL), activeTxn(NULL)
225 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
226 bool fCreate = strchr(pszMode, 'c') != NULL;
227 unsigned int nFlags = DB_THREAD;
233 if (!bitdb.Open(GetDataDir()))
234 throw runtime_error("env open failed");
237 ++bitdb.mapFileUseCount[strFile];
238 pdb = bitdb.mapDb[strFile];
241 pdb = new Db(&bitdb.dbenv, 0);
243 bool fMockDb = bitdb.IsMock();
246 DbMpoolFile*mpf = pdb->get_mpf();
247 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
249 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
252 ret = pdb->open(NULL, // Txn pointer
253 fMockDb ? NULL : pszFile, // Filename
254 "main", // Logical db name
255 DB_BTREE, // Database type
263 --bitdb.mapFileUseCount[strFile];
265 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
268 if (fCreate && !Exists(string("version")))
270 bool fTmp = fReadOnly;
272 WriteVersion(CLIENT_VERSION);
276 bitdb.mapDb[strFile] = pdb;
281 static bool IsChainFile(std::string strFile)
283 if (strFile == "blkindex.dat")
298 // Flush database activity from memory pool to disk log
299 unsigned int nMinutes = 0;
302 if (IsChainFile(strFile))
304 if (IsChainFile(strFile) && IsInitialBlockDownload())
307 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArgUInt("-dblogsize", 100)*1024 : 0, nMinutes, 0);
311 --bitdb.mapFileUseCount[strFile];
315 void CDBEnv::CloseDb(const string& strFile)
319 if (mapDb[strFile] != NULL)
321 // Close the database handle
322 Db* pdb = mapDb[strFile];
325 mapDb[strFile] = NULL;
330 bool CDBEnv::RemoveDb(const string& strFile)
332 this->CloseDb(strFile);
335 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
339 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
345 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
347 // Flush log data to the dat file
348 bitdb.CloseDb(strFile);
349 bitdb.CheckpointLSN(strFile);
350 bitdb.mapFileUseCount.erase(strFile);
352 bool fSuccess = true;
353 printf("Rewriting %s...\n", strFile.c_str());
354 string strFileRes = strFile + ".rewrite";
355 { // surround usage of db with extra {}
356 CDB db(strFile.c_str(), "r");
357 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
359 int ret = pdbCopy->open(NULL, // Txn pointer
360 strFileRes.c_str(), // Filename
361 "main", // Logical db name
362 DB_BTREE, // Database type
367 printf("Cannot create database file %s\n", strFileRes.c_str());
371 Dbc* pcursor = db.GetCursor();
375 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
376 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
377 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
378 if (ret == DB_NOTFOUND)
392 size_t pszSkipLen = strlen(pszSkip);
393 if (strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), pszSkipLen)) == 0)
397 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
401 ssValue << CLIENT_VERSION;
403 Dbt datKey(&ssKey[0], ssKey.size());
404 Dbt datValue(&ssValue[0], ssValue.size());
405 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
413 bitdb.CloseDb(strFile);
414 if (pdbCopy->close(0))
421 Db dbA(&bitdb.dbenv, 0);
422 if (dbA.remove(strFile.c_str(), NULL, 0))
424 Db dbB(&bitdb.dbenv, 0);
425 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
429 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
439 void CDBEnv::Flush(bool fShutdown)
441 int64_t nStart = GetTimeMillis();
442 // Flush log data to the actual data file
443 // on all files that are not in use
444 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
449 map<string, int>::iterator mi = mapFileUseCount.begin();
450 while (mi != mapFileUseCount.end())
452 string strFile = (*mi).first;
453 int nRefCount = (*mi).second;
454 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
457 // Move log data to the dat file
459 printf("%s checkpoint\n", strFile.c_str());
460 dbenv.txn_checkpoint(0, 0, 0);
461 if (!IsChainFile(strFile) || fDetachDB) {
462 printf("%s detach\n", strFile.c_str());
464 dbenv.lsn_reset(strFile.c_str(), 0);
466 printf("%s closed\n", strFile.c_str());
467 mapFileUseCount.erase(mi++);
472 printf("DBFlush(%s)%s ended %15" PRId64 "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
476 if (mapFileUseCount.empty())
478 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
493 pathAddr = GetDataDir() / "peers.dat";
496 bool CAddrDB::Write(const CAddrMan& addr)
498 // Generate random temporary filename
499 unsigned short randv = 0;
500 GetRandBytes((unsigned char *)&randv, sizeof(randv));
501 std::string tmpfn = strprintf("peers.dat.%04x", randv);
503 // serialize addresses, checksum data up to that point, then append csum
504 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
505 ssPeers << FLATDATA(pchMessageStart);
507 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
510 // open temp output file, and associate with CAutoFile
511 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
512 FILE *file = fopen(pathTmp.string().c_str(), "wb");
513 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
515 return error("CAddrman::Write() : open failed");
517 // Write and commit header, data
521 catch (const std::exception&) {
522 return error("CAddrman::Write() : I/O error");
527 // replace existing peers.dat, if any, with new peers.dat.XXXX
528 if (!RenameOver(pathTmp, pathAddr))
529 return error("CAddrman::Write() : Rename-into-place failed");
534 bool CAddrDB::Read(CAddrMan& addr)
536 // open input file, and associate with CAutoFile
537 FILE *file = fopen(pathAddr.string().c_str(), "rb");
538 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
540 return error("CAddrman::Read() : open failed");
542 // use file size to size memory buffer
543 int fileSize = GetFilesize(filein);
544 int dataSize = fileSize - sizeof(uint256);
545 //Don't try to resize to a negative number if file is small
546 if ( dataSize < 0 ) dataSize = 0;
547 vector<unsigned char> vchData;
548 vchData.resize(dataSize);
551 // read data and checksum from file
553 filein.read((char *)&vchData[0], dataSize);
556 catch (const std::exception&) {
557 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
561 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
563 // verify stored checksum matches input data
564 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
565 if (hashIn != hashTmp)
566 return error("CAddrman::Read() : checksum mismatch; data corrupted");
568 unsigned char pchMsgTmp[4];
570 // de-serialize file header (pchMessageStart magic number) and
571 ssPeers >> FLATDATA(pchMsgTmp);
573 // verify the network matches ours
574 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
575 return error("CAddrman::Read() : invalid network magic number");
577 // de-serialize address data into one CAddrMan object
580 catch (const std::exception&) {
581 return error("CAddrman::Read() : I/O error or stream data corrupted");