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 "ui_interface.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
22 unsigned int nWalletDBUpdated;
23 extern bool fUseMemoryLog;
32 void CDBEnv::EnvShutdown()
38 int ret = dbenv.close(0);
40 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
42 DbEnv(0u).remove(strPath.c_str(), 0);
45 CDBEnv::CDBEnv() : fDetachDB(false), fDbEnvInit(false), fMockDb(false), dbenv(DB_CXX_NO_EXCEPTIONS) { }
57 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
66 boost::filesystem::path pathDataDir = pathEnv;
67 strPath = pathDataDir.string();
68 boost::filesystem::path pathLogDir = pathDataDir / "database";
69 boost::filesystem::create_directory(pathLogDir);
70 boost::filesystem::path pathErrorFile = pathDataDir / "db.log";
71 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
73 unsigned int nEnvFlags = 0;
74 if (GetBoolArg("-privdb", true))
75 nEnvFlags |= DB_PRIVATE;
77 int nDbCache = GetArgInt("-dbcache", 25);
78 dbenv.set_lg_dir(pathLogDir.string().c_str());
79 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
80 dbenv.set_lg_bsize(1048576);
81 dbenv.set_lg_max(10485760);
83 // Bugfix: Bump lk_max_locks default to 537000, to safely handle reorgs with up to 5 blocks reversed
84 // dbenv.set_lk_max_locks(10000);
85 dbenv.set_lk_max_locks(537000);
87 dbenv.set_lk_max_objects(10000);
88 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
89 dbenv.set_flags(DB_AUTO_COMMIT, 1);
90 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
91 #ifdef DB_LOG_AUTO_REMOVE
92 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
94 int ret = dbenv.open(strPath.c_str(),
105 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
111 // Check that the number of locks is sufficient (to prevent chain fork possibility, read http://bitcoin.org/may15 for more info)
113 if (!dbenv.get_lk_max_locks(&nMaxLocks))
115 int nBlocks, nDeepReorg;
116 std::string strMessage;
118 nBlocks = nMaxLocks / 48768;
119 nDeepReorg = (nBlocks - 1) / 2;
121 printf("Final lk_max_locks is %u, sufficient for (worst case) %d block%s in a single transaction (up to a %d-deep reorganization)\n", nMaxLocks, nBlocks, (nBlocks == 1) ? "" : "s", nDeepReorg);
125 strMessage = strprintf(_("Warning: DB_CONFIG has set_lk_max_locks %u, which may be too low for a single block. If this limit is reached, NovaCoin may stop working."), nMaxLocks);
127 strMessage = strprintf(_("Warning: DB_CONFIG has set_lk_max_locks %u, which may be too low for a common blockchain reorganization. If this limit is reached, NovaCoin may stop working."), nMaxLocks);
129 strMiscWarning = strMessage;
130 printf("*** %s\n", strMessage.c_str());
138 void CDBEnv::MakeMock()
141 throw runtime_error("CDBEnv::MakeMock(): already initialized");
144 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
146 printf("CDBEnv::MakeMock()\n");
148 dbenv.set_cachesize(1, 0, 1);
149 dbenv.set_lg_bsize(10485760*4);
150 dbenv.set_lg_max(10485760);
151 dbenv.set_lk_max_locks(10000);
152 dbenv.set_lk_max_objects(10000);
153 dbenv.set_flags(DB_AUTO_COMMIT, 1);
154 #ifdef DB_LOG_IN_MEMORY
155 dbenv.log_set_config(DB_LOG_IN_MEMORY, fUseMemoryLog ? 1 : 0);
157 int ret = dbenv.open(NULL,
167 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
173 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
176 assert(mapFileUseCount.count(strFile) == 0);
179 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
182 else if (recoverFunc == NULL)
186 bool fRecovered = (*recoverFunc)(*this, strFile);
187 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
190 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
191 std::vector<CDBEnv::KeyValPair >& vResult)
194 assert(mapFileUseCount.count(strFile) == 0);
196 u_int32_t flags = DB_SALVAGE;
197 if (fAggressive) flags |= DB_AGGRESSIVE;
199 stringstream strDump;
202 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
205 printf("ERROR: db salvage failed\n");
209 // Format of bdb dump is ascii lines:
218 while (!strDump.eof() && strLine != "HEADER=END")
219 getline(strDump, strLine); // Skip past header
221 std::string keyHex, valueHex;
222 while (!strDump.eof() && keyHex != "DATA=END")
224 getline(strDump, keyHex);
225 if (keyHex != "DATA=END")
227 getline(strDump, valueHex);
228 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
232 return (result == 0);
236 void CDBEnv::CheckpointLSN(std::string strFile)
238 dbenv.txn_checkpoint(0, 0, 0);
241 dbenv.lsn_reset(strFile.c_str(), 0);
245 CDB::CDB(const char *pszFile, const char* pszMode) :
246 pdb(NULL), activeTxn(NULL)
252 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
253 bool fCreate = strchr(pszMode, 'c') != NULL;
254 unsigned int nFlags = DB_THREAD;
260 if (!bitdb.Open(GetDataDir()))
261 throw runtime_error("env open failed");
264 ++bitdb.mapFileUseCount[strFile];
265 pdb = bitdb.mapDb[strFile];
268 pdb = new Db(&bitdb.dbenv, 0);
270 bool fMockDb = bitdb.IsMock();
273 DbMpoolFile*mpf = pdb->get_mpf();
274 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
276 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
279 ret = pdb->open(NULL, // Txn pointer
280 fMockDb ? NULL : pszFile, // Filename
281 "main", // Logical db name
282 DB_BTREE, // Database type
290 --bitdb.mapFileUseCount[strFile];
292 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
295 if (fCreate && !Exists(string("version")))
297 bool fTmp = fReadOnly;
299 WriteVersion(CLIENT_VERSION);
303 bitdb.mapDb[strFile] = pdb;
308 static bool IsChainFile(std::string strFile)
310 if (strFile == "blkindex.dat")
325 // Flush database activity from memory pool to disk log
326 unsigned int nMinutes = 0;
329 if (IsChainFile(strFile))
331 if (IsChainFile(strFile) && IsInitialBlockDownload())
334 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArgUInt("-dblogsize", 100)*1024 : 0, nMinutes, 0);
338 --bitdb.mapFileUseCount[strFile];
342 void CDBEnv::CloseDb(const string& strFile)
346 if (mapDb[strFile] != NULL)
348 // Close the database handle
349 Db* pdb = mapDb[strFile];
352 mapDb[strFile] = NULL;
357 bool CDBEnv::RemoveDb(const string& strFile)
359 this->CloseDb(strFile);
362 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
366 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
372 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
374 // Flush log data to the dat file
375 bitdb.CloseDb(strFile);
376 bitdb.CheckpointLSN(strFile);
377 bitdb.mapFileUseCount.erase(strFile);
379 bool fSuccess = true;
380 printf("Rewriting %s...\n", strFile.c_str());
381 string strFileRes = strFile + ".rewrite";
382 { // surround usage of db with extra {}
383 CDB db(strFile.c_str(), "r");
384 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
386 int ret = pdbCopy->open(NULL, // Txn pointer
387 strFileRes.c_str(), // Filename
388 "main", // Logical db name
389 DB_BTREE, // Database type
394 printf("Cannot create database file %s\n", strFileRes.c_str());
398 Dbc* pcursor = db.GetCursor();
402 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
403 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
404 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
405 if (ret == DB_NOTFOUND)
419 size_t pszSkipLen = strlen(pszSkip);
420 if (strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), pszSkipLen)) == 0)
424 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
428 ssValue << CLIENT_VERSION;
430 Dbt datKey(&ssKey[0], ssKey.size());
431 Dbt datValue(&ssValue[0], ssValue.size());
432 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
440 bitdb.CloseDb(strFile);
441 if (pdbCopy->close(0))
448 Db dbA(&bitdb.dbenv, 0);
449 if (dbA.remove(strFile.c_str(), NULL, 0))
451 Db dbB(&bitdb.dbenv, 0);
452 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
456 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
466 void CDBEnv::Flush(bool fShutdown)
468 int64_t nStart = GetTimeMillis();
469 // Flush log data to the actual data file
470 // on all files that are not in use
471 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
476 map<string, int>::iterator mi = mapFileUseCount.begin();
477 while (mi != mapFileUseCount.end())
479 string strFile = (*mi).first;
480 int nRefCount = (*mi).second;
481 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
484 // Move log data to the dat file
486 printf("%s checkpoint\n", strFile.c_str());
487 dbenv.txn_checkpoint(0, 0, 0);
488 if (!IsChainFile(strFile) || fDetachDB) {
489 printf("%s detach\n", strFile.c_str());
491 dbenv.lsn_reset(strFile.c_str(), 0);
493 printf("%s closed\n", strFile.c_str());
494 mapFileUseCount.erase(mi++);
499 printf("DBFlush(%s)%s ended %15" PRId64 "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
503 if (mapFileUseCount.empty())
505 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
520 pathAddr = GetDataDir() / "peers.dat";
523 bool CAddrDB::Write(const CAddrMan& addr)
525 // Generate random temporary filename
526 unsigned short randv = 0;
527 RAND_bytes((unsigned char *)&randv, sizeof(randv));
528 std::string tmpfn = strprintf("peers.dat.%04x", randv);
530 // serialize addresses, checksum data up to that point, then append csum
531 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
532 ssPeers << FLATDATA(pchMessageStart);
534 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
537 // open temp output file, and associate with CAutoFile
538 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
539 FILE *file = fopen(pathTmp.string().c_str(), "wb");
540 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
542 return error("CAddrman::Write() : open failed");
544 // Write and commit header, data
548 catch (const std::exception&) {
549 return error("CAddrman::Write() : I/O error");
554 // replace existing peers.dat, if any, with new peers.dat.XXXX
555 if (!RenameOver(pathTmp, pathAddr))
556 return error("CAddrman::Write() : Rename-into-place failed");
561 bool CAddrDB::Read(CAddrMan& addr)
563 // open input file, and associate with CAutoFile
564 FILE *file = fopen(pathAddr.string().c_str(), "rb");
565 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
567 return error("CAddrman::Read() : open failed");
569 // use file size to size memory buffer
570 int fileSize = GetFilesize(filein);
571 int dataSize = fileSize - sizeof(uint256);
572 //Don't try to resize to a negative number if file is small
573 if ( dataSize < 0 ) dataSize = 0;
574 vector<unsigned char> vchData;
575 vchData.resize(dataSize);
578 // read data and checksum from file
580 filein.read((char *)&vchData[0], dataSize);
583 catch (const std::exception&) {
584 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
588 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
590 // verify stored checksum matches input data
591 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
592 if (hashIn != hashTmp)
593 return error("CAddrman::Read() : checksum mismatch; data corrupted");
595 unsigned char pchMsgTmp[4];
597 // de-serialize file header (pchMessageStart magic number) and
598 ssPeers >> FLATDATA(pchMsgTmp);
600 // verify the network matches ours
601 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
602 return error("CAddrman::Read() : invalid network magic number");
604 // de-serialize address data into one CAddrMan object
607 catch (const std::exception&) {
608 return error("CAddrman::Read() : I/O error or stream data corrupted");