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 license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include <boost/version.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
18 using namespace boost;
21 unsigned int nWalletDBUpdated;
29 CCriticalSection cs_db;
30 static bool fDbEnvInit = false;
31 bool fDetachDB = false;
33 map<string, int> mapFileUseCount;
34 static map<string, Db*> mapDb;
36 static void EnvShutdown()
46 catch (const DbException& e)
48 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
50 DbEnv(0).remove(GetDataDir().string().c_str(), 0);
67 CDB::CDB(const char *pszFile, const char* pszMode) : pdb(NULL)
73 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
74 bool fCreate = strchr(pszMode, 'c');
75 unsigned int nFlags = DB_THREAD;
85 filesystem::path pathDataDir = GetDataDir();
86 filesystem::path pathLogDir = pathDataDir / "database";
87 filesystem::create_directory(pathLogDir);
88 filesystem::path pathErrorFile = pathDataDir / "db.log";
89 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
91 int nDbCache = GetArg("-dbcache", 25);
92 dbenv.set_lg_dir(pathLogDir.string().c_str());
93 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
94 dbenv.set_lg_bsize(1048576);
95 dbenv.set_lg_max(10485760);
96 dbenv.set_lk_max_locks(10000);
97 dbenv.set_lk_max_objects(10000);
98 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
99 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
100 dbenv.set_flags(DB_AUTO_COMMIT, 1);
101 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
102 ret = dbenv.open(pathDataDir.string().c_str(),
112 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
117 ++mapFileUseCount[strFile];
118 pdb = mapDb[strFile];
121 pdb = new Db(&dbenv, 0);
123 ret = pdb->open(NULL, // Txn pointer
125 "main", // Logical db name
126 DB_BTREE, // Database type
136 --mapFileUseCount[strFile];
139 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
142 if (fCreate && !Exists(string("version")))
144 bool fTmp = fReadOnly;
146 WriteVersion(CLIENT_VERSION);
150 mapDb[strFile] = pdb;
160 vTxn.front()->abort();
164 // Flush database activity from memory pool to disk log
165 unsigned int nMinutes = 0;
168 if (strFile == "addr.dat")
170 if (strFile == "blkindex.dat")
172 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
175 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
179 --mapFileUseCount[strFile];
183 void CloseDb(const string& strFile)
187 if (mapDb[strFile] != NULL)
189 // Close the database handle
190 Db* pdb = mapDb[strFile];
193 mapDb[strFile] = NULL;
198 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
204 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
206 // Flush log data to the dat file
208 dbenv.txn_checkpoint(0, 0, 0);
209 dbenv.lsn_reset(strFile.c_str(), 0);
210 mapFileUseCount.erase(strFile);
212 bool fSuccess = true;
213 printf("Rewriting %s...\n", strFile.c_str());
214 string strFileRes = strFile + ".rewrite";
215 { // surround usage of db with extra {}
216 CDB db(strFile.c_str(), "r");
217 Db* pdbCopy = new Db(&dbenv, 0);
219 int ret = pdbCopy->open(NULL, // Txn pointer
220 strFileRes.c_str(), // Filename
221 "main", // Logical db name
222 DB_BTREE, // Database type
227 printf("Cannot create database file %s\n", strFileRes.c_str());
231 Dbc* pcursor = db.GetCursor();
235 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
236 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
237 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
238 if (ret == DB_NOTFOUND)
250 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
252 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
256 ssValue << CLIENT_VERSION;
258 Dbt datKey(&ssKey[0], ssKey.size());
259 Dbt datValue(&ssValue[0], ssValue.size());
260 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
268 if (pdbCopy->close(0))
276 if (dbA.remove(strFile.c_str(), NULL, 0))
279 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
283 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
293 void DBFlush(bool fShutdown)
295 // Flush log data to the actual data file
296 // on all files that are not in use
297 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
302 map<string, int>::iterator mi = mapFileUseCount.begin();
303 while (mi != mapFileUseCount.end())
305 string strFile = (*mi).first;
306 int nRefCount = (*mi).second;
307 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
310 // Move log data to the dat file
312 printf("%s checkpoint\n", strFile.c_str());
313 dbenv.txn_checkpoint(0, 0, 0);
314 if ((strFile != "blkindex.dat" && strFile != "addr.dat") || fDetachDB) {
315 printf("%s detach\n", strFile.c_str());
316 dbenv.lsn_reset(strFile.c_str(), 0);
318 printf("%s closed\n", strFile.c_str());
319 mapFileUseCount.erase(mi++);
327 if (mapFileUseCount.empty())
329 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
345 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
349 return Read(make_pair(string("tx"), hash), txindex);
352 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
355 return Write(make_pair(string("tx"), hash), txindex);
358 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
363 uint256 hash = tx.GetHash();
364 CTxIndex txindex(pos, tx.vout.size());
365 return Write(make_pair(string("tx"), hash), txindex);
368 bool CTxDB::EraseTxIndex(const CTransaction& tx)
371 uint256 hash = tx.GetHash();
373 return Erase(make_pair(string("tx"), hash));
376 bool CTxDB::ContainsTx(uint256 hash)
379 return Exists(make_pair(string("tx"), hash));
382 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
388 Dbc* pcursor = GetCursor();
392 unsigned int fFlags = DB_SET_RANGE;
396 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
397 if (fFlags == DB_SET_RANGE)
398 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
399 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
400 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
402 if (ret == DB_NOTFOUND)
417 ssKey >> strType >> hashItem >> pos;
418 ssValue >> nItemHeight;
420 catch (std::exception &e) {
421 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
425 if (strType != "owner" || hashItem != hash160)
427 if (nItemHeight >= nMinHeight)
429 vtx.resize(vtx.size()+1);
430 if (!vtx.back().ReadFromDisk(pos))
442 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
446 if (!ReadTxIndex(hash, txindex))
448 return (tx.ReadFromDisk(txindex.pos));
451 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
454 return ReadDiskTx(hash, tx, txindex);
457 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
459 return ReadDiskTx(outpoint.hash, tx, txindex);
462 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
465 return ReadDiskTx(outpoint.hash, tx, txindex);
468 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
470 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
473 bool CTxDB::EraseBlockIndex(uint256 hash)
475 return Erase(make_pair(string("blockindex"), hash));
478 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
480 return Read(string("hashBestChain"), hashBestChain);
483 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
485 return Write(string("hashBestChain"), hashBestChain);
488 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
490 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
493 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
495 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
498 CBlockIndex static * InsertBlockIndex(uint256 hash)
504 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
505 if (mi != mapBlockIndex.end())
509 CBlockIndex* pindexNew = new CBlockIndex();
511 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
512 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
513 pindexNew->phashBlock = &((*mi).first);
518 bool CTxDB::LoadBlockIndex()
520 // Get database cursor
521 Dbc* pcursor = GetCursor();
525 // Load mapBlockIndex
526 unsigned int fFlags = DB_SET_RANGE;
530 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
531 if (fFlags == DB_SET_RANGE)
532 ssKey << make_pair(string("blockindex"), uint256(0));
533 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
534 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
536 if (ret == DB_NOTFOUND)
546 if (strType == "blockindex" && !fRequestShutdown)
548 CDiskBlockIndex diskindex;
549 ssValue >> diskindex;
551 // Construct block index object
552 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
553 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
554 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
555 pindexNew->nFile = diskindex.nFile;
556 pindexNew->nBlockPos = diskindex.nBlockPos;
557 pindexNew->nHeight = diskindex.nHeight;
558 pindexNew->nVersion = diskindex.nVersion;
559 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
560 pindexNew->nTime = diskindex.nTime;
561 pindexNew->nBits = diskindex.nBits;
562 pindexNew->nNonce = diskindex.nNonce;
564 // Watch for genesis block
565 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
566 pindexGenesisBlock = pindexNew;
568 if (!pindexNew->CheckIndex())
569 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
573 break; // if shutdown requested or finished loading block index
576 catch (std::exception &e) {
577 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
582 if (fRequestShutdown)
585 // Calculate bnChainWork
586 vector<pair<int, CBlockIndex*> > vSortedByHeight;
587 vSortedByHeight.reserve(mapBlockIndex.size());
588 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
590 CBlockIndex* pindex = item.second;
591 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
593 sort(vSortedByHeight.begin(), vSortedByHeight.end());
594 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
596 CBlockIndex* pindex = item.second;
597 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
600 // Load hashBestChain pointer to end of best chain
601 if (!ReadHashBestChain(hashBestChain))
603 if (pindexGenesisBlock == NULL)
605 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
607 if (!mapBlockIndex.count(hashBestChain))
608 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
609 pindexBest = mapBlockIndex[hashBestChain];
610 nBestHeight = pindexBest->nHeight;
611 bnBestChainWork = pindexBest->bnChainWork;
612 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
614 // Load bnBestInvalidWork, OK if it doesn't exist
615 ReadBestInvalidWork(bnBestInvalidWork);
617 // Verify blocks in the best chain
618 int nCheckLevel = GetArg("-checklevel", 1);
619 int nCheckDepth = GetArg( "-checkblocks", 2500);
620 if (nCheckDepth == 0)
621 nCheckDepth = 1000000000; // suffices until the year 19000
622 if (nCheckDepth > nBestHeight)
623 nCheckDepth = nBestHeight;
624 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
625 CBlockIndex* pindexFork = NULL;
626 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
627 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
629 if (pindex->nHeight < nBestHeight-nCheckDepth)
632 if (!block.ReadFromDisk(pindex))
633 return error("LoadBlockIndex() : block.ReadFromDisk failed");
634 // check level 1: verify block validity
635 if (nCheckLevel>0 && !block.CheckBlock())
637 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
638 pindexFork = pindex->pprev;
640 // check level 2: verify transaction index validity
643 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
644 mapBlockPos[pos] = pindex;
645 BOOST_FOREACH(const CTransaction &tx, block.vtx)
647 uint256 hashTx = tx.GetHash();
649 if (ReadTxIndex(hashTx, txindex))
651 // check level 3: checker transaction hashes
652 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
654 // either an error or a duplicate transaction
655 CTransaction txFound;
656 if (!txFound.ReadFromDisk(txindex.pos))
658 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
659 pindexFork = pindex->pprev;
662 if (txFound.GetHash() != hashTx) // not a duplicate tx
664 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
665 pindexFork = pindex->pprev;
668 // check level 4: check whether spent txouts were spent within the main chain
669 unsigned int nOutput = 0;
672 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
676 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
677 if (!mapBlockPos.count(posFind))
679 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
680 pindexFork = pindex->pprev;
682 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
685 CTransaction txSpend;
686 if (!txSpend.ReadFromDisk(txpos))
688 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
689 pindexFork = pindex->pprev;
691 else if (!txSpend.CheckTransaction())
693 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
694 pindexFork = pindex->pprev;
699 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
700 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
704 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
705 pindexFork = pindex->pprev;
714 // check level 5: check whether all prevouts are marked spent
717 BOOST_FOREACH(const CTxIn &txin, tx.vin)
720 if (ReadTxIndex(txin.prevout.hash, txindex))
721 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
723 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
724 pindexFork = pindex->pprev;
733 // Reorg back to the fork
734 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
736 if (!block.ReadFromDisk(pindexFork))
737 return error("LoadBlockIndex() : block.ReadFromDisk failed");
739 block.SetBestChain(txdb, pindexFork);
753 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
755 return Write(string("addrman"), addrman);
758 bool CAddrDB::LoadAddresses()
760 if (Read(string("addrman"), addrman))
762 printf("Loaded %i addresses\n", addrman.size());
766 // Read pre-0.6 addr records
768 vector<CAddress> vAddr;
769 vector<vector<unsigned char> > vDelete;
772 Dbc* pcursor = GetCursor();
779 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
780 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
781 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
782 if (ret == DB_NOTFOUND)
790 if (strType == "addr")
794 vAddr.push_back(addr);
799 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
800 printf("Loaded %i addresses\n", addrman.size());
802 // Note: old records left; we ran into hangs-on-startup
803 // bugs for some users who (we think) were running after
804 // an unclean shutdown.
811 return CAddrDB("cr+").LoadAddresses();