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"
12 #include <boost/filesystem.hpp>
20 uint32_t nWalletDBUpdated;
21 extern bool fUseMemoryLog;
29 void CDBEnv::EnvShutdown()
35 int ret = dbenv.close(0);
37 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
39 DbEnv(0).remove(strPath.c_str(), 0);
42 CDBEnv::CDBEnv() : fDetachDB(false), fDbEnvInit(false), fMockDb(false), dbenv(DB_CXX_NO_EXCEPTIONS) { }
54 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
63 boost::filesystem::path pathDataDir = pathEnv;
64 strPath = pathDataDir.string();
65 boost::filesystem::path pathLogDir = pathDataDir / "database";
66 boost::filesystem::create_directory(pathLogDir);
67 boost::filesystem::path pathErrorFile = pathDataDir / "db.log";
68 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
70 uint32_t nEnvFlags = 0;
71 if (GetBoolArg("-privdb", true))
72 nEnvFlags |= DB_PRIVATE;
74 int nDbCache = GetArgInt("-dbcache", 25);
75 dbenv.set_lg_dir(pathLogDir.string().c_str());
76 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
77 dbenv.set_lg_bsize(1048576);
78 dbenv.set_lg_max(10485760);
80 // Bugfix: Bump lk_max_locks default to 537000, to safely handle reorgs with up to 5 blocks reversed
81 // dbenv.set_lk_max_locks(10000);
82 dbenv.set_lk_max_locks(537000);
84 dbenv.set_lk_max_objects(10000);
85 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
86 dbenv.set_flags(DB_AUTO_COMMIT, 1);
87 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
88 #ifdef DB_LOG_AUTO_REMOVE
89 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
91 int ret = dbenv.open(strPath.c_str(),
102 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
108 // Check that the number of locks is sufficient (to prevent chain fork possibility, read http://bitcoin.org/may15 for more info)
110 if (!dbenv.get_lk_max_locks(&nMaxLocks))
112 int nBlocks, nDeepReorg;
115 nBlocks = nMaxLocks / 48768;
116 nDeepReorg = (nBlocks - 1) / 2;
118 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);
122 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);
124 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);
126 strMiscWarning = strMessage;
127 printf("*** %s\n", strMessage.c_str());
135 CDBEnv::VerifyResult CDBEnv::Verify(string strFile, bool (*recoverFunc)(CDBEnv& dbenv, string strFile))
138 assert(mapFileUseCount.count(strFile) == 0);
141 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
144 else if (recoverFunc == NULL)
148 bool fRecovered = (*recoverFunc)(*this, strFile);
149 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
152 bool CDBEnv::Salvage(string strFile, bool fAggressive,
153 vector<CDBEnv::KeyValPair >& vResult)
156 assert(mapFileUseCount.count(strFile) == 0);
158 u_int32_t flags = DB_SALVAGE;
159 if (fAggressive) flags |= DB_AGGRESSIVE;
161 stringstream strDump;
164 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
167 printf("ERROR: db salvage failed\n");
171 // Format of bdb dump is ascii lines:
180 while (!strDump.eof() && strLine != "HEADER=END")
181 getline(strDump, strLine); // Skip past header
183 string keyHex, valueHex;
184 while (!strDump.eof() && keyHex != "DATA=END")
186 getline(strDump, keyHex);
187 if (keyHex != "DATA=END")
189 getline(strDump, valueHex);
190 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
194 return (result == 0);
198 void CDBEnv::CheckpointLSN(string strFile)
200 dbenv.txn_checkpoint(0, 0, 0);
203 dbenv.lsn_reset(strFile.c_str(), 0);
207 CDB::CDB(const char *pszFile, const char* pszMode) :
208 pdb(NULL), activeTxn(NULL)
214 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
215 bool fCreate = strchr(pszMode, 'c') != NULL;
216 uint32_t nFlags = DB_THREAD;
222 if (!bitdb.Open(GetDataDir()))
223 throw runtime_error("env open failed");
226 ++bitdb.mapFileUseCount[strFile];
227 pdb = bitdb.mapDb[strFile];
230 pdb = new Db(&bitdb.dbenv, 0);
232 ret = pdb->open(NULL, // Txn pointer
234 "main", // Logical db name
235 DB_BTREE, // Database type
243 --bitdb.mapFileUseCount[strFile];
245 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
248 if (fCreate && !Exists(string("version")))
250 bool fTmp = fReadOnly;
252 WriteVersion(CLIENT_VERSION);
256 bitdb.mapDb[strFile] = pdb;
261 static bool IsChainFile(string strFile)
263 if (strFile == "blkindex.dat")
278 // Flush database activity from memory pool to disk log
279 uint32_t nMinutes = 0;
282 if (IsChainFile(strFile))
284 if (IsChainFile(strFile) && IsInitialBlockDownload())
287 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArgUInt("-dblogsize", 100)*1024 : 0, nMinutes, 0);
291 --bitdb.mapFileUseCount[strFile];
295 void CDBEnv::CloseDb(const string& strFile)
299 if (mapDb[strFile] != NULL)
301 // Close the database handle
302 Db* pdb = mapDb[strFile];
305 mapDb[strFile] = NULL;
310 bool CDBEnv::RemoveDb(const string& strFile)
312 this->CloseDb(strFile);
315 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
319 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
325 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
327 // Flush log data to the dat file
328 bitdb.CloseDb(strFile);
329 bitdb.CheckpointLSN(strFile);
330 bitdb.mapFileUseCount.erase(strFile);
332 bool fSuccess = true;
333 printf("Rewriting %s...\n", strFile.c_str());
334 string strFileRes = strFile + ".rewrite";
335 { // surround usage of db with extra {}
336 CDB db(strFile.c_str(), "r");
337 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
339 int ret = pdbCopy->open(NULL, // Txn pointer
340 strFileRes.c_str(), // Filename
341 "main", // Logical db name
342 DB_BTREE, // Database type
347 printf("Cannot create database file %s\n", strFileRes.c_str());
351 Dbc* pcursor = db.GetCursor();
355 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
356 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
357 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
358 if (ret == DB_NOTFOUND)
372 size_t pszSkipLen = strlen(pszSkip);
373 if (strncmp(&ssKey[0], pszSkip, min(ssKey.size(), pszSkipLen)) == 0)
377 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
381 ssValue << CLIENT_VERSION;
383 Dbt datKey(&ssKey[0], ssKey.size());
384 Dbt datValue(&ssValue[0], ssValue.size());
385 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
393 bitdb.CloseDb(strFile);
394 if (pdbCopy->close(0))
401 Db dbA(&bitdb.dbenv, 0);
402 if (dbA.remove(strFile.c_str(), NULL, 0))
404 Db dbB(&bitdb.dbenv, 0);
405 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
409 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
419 void CDBEnv::Flush(bool fShutdown)
421 int64_t nStart = GetTimeMillis();
422 // Flush log data to the actual data file
423 // on all files that are not in use
424 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
429 auto mi = mapFileUseCount.begin();
430 while (mi != mapFileUseCount.end())
432 string strFile = (*mi).first;
433 int nRefCount = (*mi).second;
434 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
437 // Move log data to the dat file
439 printf("%s checkpoint\n", strFile.c_str());
440 dbenv.txn_checkpoint(0, 0, 0);
441 if (!IsChainFile(strFile) || fDetachDB) {
442 printf("%s detach\n", strFile.c_str());
444 dbenv.lsn_reset(strFile.c_str(), 0);
446 printf("%s closed\n", strFile.c_str());
447 mapFileUseCount.erase(mi++);
452 printf("DBFlush(%s)%s ended %15" PRId64 "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
456 if (mapFileUseCount.empty())
458 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
473 pathAddr = GetDataDir() / "peers.dat";
476 bool CAddrDB::Write(const CAddrMan& addr)
478 // Generate random temporary filename
479 unsigned short randv = 0;
480 RAND_bytes((unsigned char *)&randv, sizeof(randv));
481 string tmpfn = strprintf("peers.dat.%04x", randv);
483 // serialize addresses, checksum data up to that point, then append csum
484 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
485 ssPeers << nNetworkID;
487 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
490 // open temp output file, and associate with CAutoFile
491 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
492 FILE *file = fopen(pathTmp.string().c_str(), "wb");
493 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
495 return error("CAddrman::Write() : open failed");
497 // Write and commit header, data
501 catch (const exception&) {
502 return error("CAddrman::Write() : I/O error");
507 // replace existing peers.dat, if any, with new peers.dat.XXXX
508 if (!RenameOver(pathTmp, pathAddr))
509 return error("CAddrman::Write() : Rename-into-place failed");
514 bool CAddrDB::Read(CAddrMan& addr)
516 // open input file, and associate with CAutoFile
517 FILE *file = fopen(pathAddr.string().c_str(), "rb");
518 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
520 return error("CAddrman::Read() : open failed");
522 // use file size to size memory buffer
523 int fileSize = GetFilesize(filein);
524 int dataSize = fileSize - sizeof(uint256);
525 //Don't try to resize to a negative number if file is small
526 if ( dataSize < 0 ) dataSize = 0;
527 vector<unsigned char> vchData;
528 vchData.resize(dataSize);
531 // read data and checksum from file
533 filein.read((char *)&vchData[0], dataSize);
536 catch (const exception&) {
537 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
541 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
543 // verify stored checksum matches input data
544 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
545 if (hashIn != hashTmp)
546 return error("CAddrman::Read() : checksum mismatch; data corrupted");
550 // de-serialize file header (pchMessageStart magic number) and
551 ssPeers >> nMsgNetID;
552 // verify the network matches ours
553 if (nMsgNetID != nNetworkID)
554 return error("CAddrman::Read() : invalid network magic number");
555 // de-serialize address data into one CAddrMan object
558 catch (const exception&) {
559 return error("CAddrman::Read() : I/O error or stream data corrupted");