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)
414 ssKey >> strType >> hashItem >> pos;
416 ssValue >> nItemHeight;
419 if (strType != "owner" || hashItem != hash160)
421 if (nItemHeight >= nMinHeight)
423 vtx.resize(vtx.size()+1);
424 if (!vtx.back().ReadFromDisk(pos))
436 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
440 if (!ReadTxIndex(hash, txindex))
442 return (tx.ReadFromDisk(txindex.pos));
445 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
448 return ReadDiskTx(hash, tx, txindex);
451 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
453 return ReadDiskTx(outpoint.hash, tx, txindex);
456 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
459 return ReadDiskTx(outpoint.hash, tx, txindex);
462 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
464 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
467 bool CTxDB::EraseBlockIndex(uint256 hash)
469 return Erase(make_pair(string("blockindex"), hash));
472 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
474 return Read(string("hashBestChain"), hashBestChain);
477 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
479 return Write(string("hashBestChain"), hashBestChain);
482 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
484 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
487 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
489 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
492 CBlockIndex static * InsertBlockIndex(uint256 hash)
498 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
499 if (mi != mapBlockIndex.end())
503 CBlockIndex* pindexNew = new CBlockIndex();
505 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
506 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
507 pindexNew->phashBlock = &((*mi).first);
512 bool CTxDB::LoadBlockIndex()
514 // Get database cursor
515 Dbc* pcursor = GetCursor();
519 // Load mapBlockIndex
520 unsigned int fFlags = DB_SET_RANGE;
524 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
525 if (fFlags == DB_SET_RANGE)
526 ssKey << make_pair(string("blockindex"), uint256(0));
527 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
528 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
530 if (ret == DB_NOTFOUND)
538 if (strType == "blockindex" && !fRequestShutdown)
540 CDiskBlockIndex diskindex;
541 ssValue >> diskindex;
543 // Construct block index object
544 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
545 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
546 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
547 pindexNew->nFile = diskindex.nFile;
548 pindexNew->nBlockPos = diskindex.nBlockPos;
549 pindexNew->nHeight = diskindex.nHeight;
550 pindexNew->nVersion = diskindex.nVersion;
551 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
552 pindexNew->nTime = diskindex.nTime;
553 pindexNew->nBits = diskindex.nBits;
554 pindexNew->nNonce = diskindex.nNonce;
556 // Watch for genesis block
557 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
558 pindexGenesisBlock = pindexNew;
560 if (!pindexNew->CheckIndex())
561 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
565 break; // if shutdown requested or finished loading block index
570 if (fRequestShutdown)
573 // Calculate bnChainWork
574 vector<pair<int, CBlockIndex*> > vSortedByHeight;
575 vSortedByHeight.reserve(mapBlockIndex.size());
576 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
578 CBlockIndex* pindex = item.second;
579 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
581 sort(vSortedByHeight.begin(), vSortedByHeight.end());
582 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
584 CBlockIndex* pindex = item.second;
585 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
588 // Load hashBestChain pointer to end of best chain
589 if (!ReadHashBestChain(hashBestChain))
591 if (pindexGenesisBlock == NULL)
593 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
595 if (!mapBlockIndex.count(hashBestChain))
596 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
597 pindexBest = mapBlockIndex[hashBestChain];
598 nBestHeight = pindexBest->nHeight;
599 bnBestChainWork = pindexBest->bnChainWork;
600 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
602 // Load bnBestInvalidWork, OK if it doesn't exist
603 ReadBestInvalidWork(bnBestInvalidWork);
605 // Verify blocks in the best chain
606 int nCheckLevel = GetArg("-checklevel", 1);
607 int nCheckDepth = GetArg( "-checkblocks", 2500);
608 if (nCheckDepth == 0)
609 nCheckDepth = 1000000000; // suffices until the year 19000
610 if (nCheckDepth > nBestHeight)
611 nCheckDepth = nBestHeight;
612 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
613 CBlockIndex* pindexFork = NULL;
614 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
615 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
617 if (pindex->nHeight < nBestHeight-nCheckDepth)
620 if (!block.ReadFromDisk(pindex))
621 return error("LoadBlockIndex() : block.ReadFromDisk failed");
622 // check level 1: verify block validity
623 if (nCheckLevel>0 && !block.CheckBlock())
625 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
626 pindexFork = pindex->pprev;
628 // check level 2: verify transaction index validity
631 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
632 mapBlockPos[pos] = pindex;
633 BOOST_FOREACH(const CTransaction &tx, block.vtx)
635 uint256 hashTx = tx.GetHash();
637 if (ReadTxIndex(hashTx, txindex))
639 // check level 3: checker transaction hashes
640 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
642 // either an error or a duplicate transaction
643 CTransaction txFound;
644 if (!txFound.ReadFromDisk(txindex.pos))
646 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
647 pindexFork = pindex->pprev;
650 if (txFound.GetHash() != hashTx) // not a duplicate tx
652 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
653 pindexFork = pindex->pprev;
656 // check level 4: check whether spent txouts were spent within the main chain
657 unsigned int nOutput = 0;
660 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
664 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
665 if (!mapBlockPos.count(posFind))
667 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
668 pindexFork = pindex->pprev;
670 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
673 CTransaction txSpend;
674 if (!txSpend.ReadFromDisk(txpos))
676 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
677 pindexFork = pindex->pprev;
679 else if (!txSpend.CheckTransaction())
681 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
682 pindexFork = pindex->pprev;
687 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
688 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
692 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
693 pindexFork = pindex->pprev;
702 // check level 5: check whether all prevouts are marked spent
705 BOOST_FOREACH(const CTxIn &txin, tx.vin)
708 if (ReadTxIndex(txin.prevout.hash, txindex))
709 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
711 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
712 pindexFork = pindex->pprev;
721 // Reorg back to the fork
722 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
724 if (!block.ReadFromDisk(pindexFork))
725 return error("LoadBlockIndex() : block.ReadFromDisk failed");
727 block.SetBestChain(txdb, pindexFork);
741 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
743 return Write(string("addrman"), addrman);
746 bool CAddrDB::LoadAddresses()
748 if (Read(string("addrman"), addrman))
750 printf("Loaded %i addresses\n", addrman.size());
754 // Read pre-0.6 addr records
756 vector<CAddress> vAddr;
757 vector<vector<unsigned char> > vDelete;
760 Dbc* pcursor = GetCursor();
767 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
768 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
769 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
770 if (ret == DB_NOTFOUND)
778 if (strType == "addr")
782 vAddr.push_back(addr);
787 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
788 printf("Loaded %i addresses\n", addrman.size());
790 // Note: old records left; we ran into hangs-on-startup
791 // bugs for some users who (we think) were running after
792 // an unclean shutdown.
799 return CAddrDB("cr+").LoadAddresses();