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;
32 map<string, int> mapFileUseCount;
33 static map<string, Db*> mapDb;
35 static void EnvShutdown()
45 catch (const DbException& e)
47 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
49 DbEnv(0).remove(GetDataDir().string().c_str(), 0);
66 CDB::CDB(const char *pszFile, const char* pszMode) : pdb(NULL)
72 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
73 bool fCreate = strchr(pszMode, 'c');
74 unsigned int nFlags = DB_THREAD;
84 filesystem::path pathDataDir = GetDataDir();
85 filesystem::path pathLogDir = pathDataDir / "database";
86 filesystem::create_directory(pathLogDir);
87 filesystem::path pathErrorFile = pathDataDir / "db.log";
88 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
90 int nDbCache = GetArg("-dbcache", 25);
91 dbenv.set_lg_dir(pathLogDir.string().c_str());
92 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
93 dbenv.set_lg_bsize(1048576);
94 dbenv.set_lg_max(10485760);
95 dbenv.set_lk_max_locks(10000);
96 dbenv.set_lk_max_objects(10000);
97 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
98 dbenv.set_flags(DB_AUTO_COMMIT, 1);
99 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
100 ret = dbenv.open(pathDataDir.string().c_str(),
110 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
115 ++mapFileUseCount[strFile];
116 pdb = mapDb[strFile];
119 pdb = new Db(&dbenv, 0);
121 ret = pdb->open(NULL, // Txn pointer
123 "main", // Logical db name
124 DB_BTREE, // Database type
134 --mapFileUseCount[strFile];
137 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
140 if (fCreate && !Exists(string("version")))
142 bool fTmp = fReadOnly;
144 WriteVersion(CLIENT_VERSION);
148 mapDb[strFile] = pdb;
158 vTxn.front()->abort();
162 // Flush database activity from memory pool to disk log
163 unsigned int nMinutes = 0;
166 if (strFile == "addr.dat")
168 if (strFile == "blkindex.dat")
170 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
173 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
177 --mapFileUseCount[strFile];
181 void CloseDb(const string& strFile)
185 if (mapDb[strFile] != NULL)
187 // Close the database handle
188 Db* pdb = mapDb[strFile];
191 mapDb[strFile] = NULL;
196 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
202 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
204 // Flush log data to the dat file
206 dbenv.txn_checkpoint(0, 0, 0);
207 dbenv.lsn_reset(strFile.c_str(), 0);
208 mapFileUseCount.erase(strFile);
210 bool fSuccess = true;
211 printf("Rewriting %s...\n", strFile.c_str());
212 string strFileRes = strFile + ".rewrite";
213 { // surround usage of db with extra {}
214 CDB db(strFile.c_str(), "r");
215 Db* pdbCopy = new Db(&dbenv, 0);
217 int ret = pdbCopy->open(NULL, // Txn pointer
218 strFileRes.c_str(), // Filename
219 "main", // Logical db name
220 DB_BTREE, // Database type
225 printf("Cannot create database file %s\n", strFileRes.c_str());
229 Dbc* pcursor = db.GetCursor();
233 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
234 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
235 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
236 if (ret == DB_NOTFOUND)
248 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
250 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
254 ssValue << CLIENT_VERSION;
256 Dbt datKey(&ssKey[0], ssKey.size());
257 Dbt datValue(&ssValue[0], ssValue.size());
258 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
266 if (pdbCopy->close(0))
274 if (dbA.remove(strFile.c_str(), NULL, 0))
277 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
281 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
291 void DBFlush(bool fShutdown)
293 // Flush log data to the actual data file
294 // on all files that are not in use
295 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
300 map<string, int>::iterator mi = mapFileUseCount.begin();
301 while (mi != mapFileUseCount.end())
303 string strFile = (*mi).first;
304 int nRefCount = (*mi).second;
305 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
308 // Move log data to the dat file
310 dbenv.txn_checkpoint(0, 0, 0);
311 printf("%s flush\n", strFile.c_str());
312 dbenv.lsn_reset(strFile.c_str(), 0);
313 mapFileUseCount.erase(mi++);
321 if (mapFileUseCount.empty())
323 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
339 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
343 return Read(make_pair(string("tx"), hash), txindex);
346 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
349 return Write(make_pair(string("tx"), hash), txindex);
352 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
357 uint256 hash = tx.GetHash();
358 CTxIndex txindex(pos, tx.vout.size());
359 return Write(make_pair(string("tx"), hash), txindex);
362 bool CTxDB::EraseTxIndex(const CTransaction& tx)
365 uint256 hash = tx.GetHash();
367 return Erase(make_pair(string("tx"), hash));
370 bool CTxDB::ContainsTx(uint256 hash)
373 return Exists(make_pair(string("tx"), hash));
376 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
382 Dbc* pcursor = GetCursor();
386 unsigned int fFlags = DB_SET_RANGE;
390 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
391 if (fFlags == DB_SET_RANGE)
392 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
393 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
394 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
396 if (ret == DB_NOTFOUND)
408 ssKey >> strType >> hashItem >> pos;
410 ssValue >> nItemHeight;
413 if (strType != "owner" || hashItem != hash160)
415 if (nItemHeight >= nMinHeight)
417 vtx.resize(vtx.size()+1);
418 if (!vtx.back().ReadFromDisk(pos))
430 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
434 if (!ReadTxIndex(hash, txindex))
436 return (tx.ReadFromDisk(txindex.pos));
439 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
442 return ReadDiskTx(hash, tx, txindex);
445 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
447 return ReadDiskTx(outpoint.hash, tx, txindex);
450 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
453 return ReadDiskTx(outpoint.hash, tx, txindex);
456 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
458 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
461 bool CTxDB::EraseBlockIndex(uint256 hash)
463 return Erase(make_pair(string("blockindex"), hash));
466 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
468 return Read(string("hashBestChain"), hashBestChain);
471 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
473 return Write(string("hashBestChain"), hashBestChain);
476 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
478 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
481 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
483 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
486 CBlockIndex static * InsertBlockIndex(uint256 hash)
492 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
493 if (mi != mapBlockIndex.end())
497 CBlockIndex* pindexNew = new CBlockIndex();
499 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
500 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
501 pindexNew->phashBlock = &((*mi).first);
506 bool CTxDB::LoadBlockIndex()
508 // Get database cursor
509 Dbc* pcursor = GetCursor();
513 // Load mapBlockIndex
514 unsigned int fFlags = DB_SET_RANGE;
518 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
519 if (fFlags == DB_SET_RANGE)
520 ssKey << make_pair(string("blockindex"), uint256(0));
521 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
522 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
524 if (ret == DB_NOTFOUND)
532 if (strType == "blockindex" && !fRequestShutdown)
534 CDiskBlockIndex diskindex;
535 ssValue >> diskindex;
537 // Construct block index object
538 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
539 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
540 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
541 pindexNew->nFile = diskindex.nFile;
542 pindexNew->nBlockPos = diskindex.nBlockPos;
543 pindexNew->nHeight = diskindex.nHeight;
544 pindexNew->nVersion = diskindex.nVersion;
545 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
546 pindexNew->nTime = diskindex.nTime;
547 pindexNew->nBits = diskindex.nBits;
548 pindexNew->nNonce = diskindex.nNonce;
550 // Watch for genesis block
551 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
552 pindexGenesisBlock = pindexNew;
554 if (!pindexNew->CheckIndex())
555 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
559 break; // if shutdown requested or finished loading block index
564 if (fRequestShutdown)
567 // Calculate bnChainWork
568 vector<pair<int, CBlockIndex*> > vSortedByHeight;
569 vSortedByHeight.reserve(mapBlockIndex.size());
570 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
572 CBlockIndex* pindex = item.second;
573 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
575 sort(vSortedByHeight.begin(), vSortedByHeight.end());
576 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
578 CBlockIndex* pindex = item.second;
579 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
582 // Load hashBestChain pointer to end of best chain
583 if (!ReadHashBestChain(hashBestChain))
585 if (pindexGenesisBlock == NULL)
587 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
589 if (!mapBlockIndex.count(hashBestChain))
590 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
591 pindexBest = mapBlockIndex[hashBestChain];
592 nBestHeight = pindexBest->nHeight;
593 bnBestChainWork = pindexBest->bnChainWork;
594 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
596 // Load bnBestInvalidWork, OK if it doesn't exist
597 ReadBestInvalidWork(bnBestInvalidWork);
599 // Verify blocks in the best chain
600 int nCheckLevel = GetArg("-checklevel", 1);
601 int nCheckDepth = GetArg( "-checkblocks", 2500);
602 if (nCheckDepth == 0)
603 nCheckDepth = 1000000000; // suffices until the year 19000
604 if (nCheckDepth > nBestHeight)
605 nCheckDepth = nBestHeight;
606 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
607 CBlockIndex* pindexFork = NULL;
608 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
609 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
611 if (pindex->nHeight < nBestHeight-nCheckDepth)
614 if (!block.ReadFromDisk(pindex))
615 return error("LoadBlockIndex() : block.ReadFromDisk failed");
616 // check level 1: verify block validity
617 if (nCheckLevel>0 && !block.CheckBlock())
619 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
620 pindexFork = pindex->pprev;
622 // check level 2: verify transaction index validity
625 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
626 mapBlockPos[pos] = pindex;
627 BOOST_FOREACH(const CTransaction &tx, block.vtx)
629 uint256 hashTx = tx.GetHash();
631 if (ReadTxIndex(hashTx, txindex))
633 // check level 3: checker transaction hashes
634 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
636 // either an error or a duplicate transaction
637 CTransaction txFound;
638 if (!txFound.ReadFromDisk(txindex.pos))
640 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
641 pindexFork = pindex->pprev;
644 if (txFound.GetHash() != hashTx) // not a duplicate tx
646 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
647 pindexFork = pindex->pprev;
650 // check level 4: check whether spent txouts were spent within the main chain
654 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
658 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
659 if (!mapBlockPos.count(posFind))
661 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
662 pindexFork = pindex->pprev;
664 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
667 CTransaction txSpend;
668 if (!txSpend.ReadFromDisk(txpos))
670 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
671 pindexFork = pindex->pprev;
673 else if (!txSpend.CheckTransaction())
675 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
676 pindexFork = pindex->pprev;
681 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
682 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
686 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
687 pindexFork = pindex->pprev;
696 // check level 5: check whether all prevouts are marked spent
699 BOOST_FOREACH(const CTxIn &txin, tx.vin)
702 if (ReadTxIndex(txin.prevout.hash, txindex))
703 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
705 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
706 pindexFork = pindex->pprev;
715 // Reorg back to the fork
716 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
718 if (!block.ReadFromDisk(pindexFork))
719 return error("LoadBlockIndex() : block.ReadFromDisk failed");
721 block.SetBestChain(txdb, pindexFork);
735 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
737 return Write(string("addrman"), addrman);
740 bool CAddrDB::LoadAddresses()
742 if (Read(string("addrman"), addrman))
744 printf("Loaded %i addresses\n", addrman.size());
748 // Read pre-0.6 addr records
750 vector<CAddress> vAddr;
751 vector<vector<unsigned char> > vDelete;
754 Dbc* pcursor = GetCursor();
761 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
762 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
763 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
764 if (ret == DB_NOTFOUND)
772 if (strType == "addr")
776 vAddr.push_back(addr);
781 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
782 printf("Loaded %i addresses\n", addrman.size());
784 // Note: old records left; we ran into hangs-on-startup
785 // bugs for some users who (we think) were running after
786 // an unclean shutdown.
793 return CAddrDB("cr+").LoadAddresses();