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_AUTO_COMMIT, 1);
100 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
101 ret = dbenv.open(pathDataDir.string().c_str(),
111 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
116 ++mapFileUseCount[strFile];
117 pdb = mapDb[strFile];
120 pdb = new Db(&dbenv, 0);
122 ret = pdb->open(NULL, // Txn pointer
124 "main", // Logical db name
125 DB_BTREE, // Database type
135 --mapFileUseCount[strFile];
138 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
141 if (fCreate && !Exists(string("version")))
143 bool fTmp = fReadOnly;
145 WriteVersion(CLIENT_VERSION);
149 mapDb[strFile] = pdb;
159 vTxn.front()->abort();
163 // Flush database activity from memory pool to disk log
164 unsigned int nMinutes = 0;
167 if (strFile == "addr.dat")
169 if (strFile == "blkindex.dat")
171 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
174 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
178 --mapFileUseCount[strFile];
182 void CloseDb(const string& strFile)
186 if (mapDb[strFile] != NULL)
188 // Close the database handle
189 Db* pdb = mapDb[strFile];
192 mapDb[strFile] = NULL;
197 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
203 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
205 // Flush log data to the dat file
207 dbenv.txn_checkpoint(0, 0, 0);
208 dbenv.lsn_reset(strFile.c_str(), 0);
209 mapFileUseCount.erase(strFile);
211 bool fSuccess = true;
212 printf("Rewriting %s...\n", strFile.c_str());
213 string strFileRes = strFile + ".rewrite";
214 { // surround usage of db with extra {}
215 CDB db(strFile.c_str(), "r");
216 Db* pdbCopy = new Db(&dbenv, 0);
218 int ret = pdbCopy->open(NULL, // Txn pointer
219 strFileRes.c_str(), // Filename
220 "main", // Logical db name
221 DB_BTREE, // Database type
226 printf("Cannot create database file %s\n", strFileRes.c_str());
230 Dbc* pcursor = db.GetCursor();
234 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
235 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
236 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
237 if (ret == DB_NOTFOUND)
249 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
251 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
255 ssValue << CLIENT_VERSION;
257 Dbt datKey(&ssKey[0], ssKey.size());
258 Dbt datValue(&ssValue[0], ssValue.size());
259 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
267 if (pdbCopy->close(0))
275 if (dbA.remove(strFile.c_str(), NULL, 0))
278 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
282 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
292 void DBFlush(bool fShutdown)
294 // Flush log data to the actual data file
295 // on all files that are not in use
296 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
301 map<string, int>::iterator mi = mapFileUseCount.begin();
302 while (mi != mapFileUseCount.end())
304 string strFile = (*mi).first;
305 int nRefCount = (*mi).second;
306 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
309 // Move log data to the dat file
311 printf("%s checkpoint\n", strFile.c_str());
312 dbenv.txn_checkpoint(0, 0, 0);
313 if ((strFile != "blkindex.dat" && strFile != "addr.dat") || fDetachDB) {
314 printf("%s detach\n", strFile.c_str());
315 dbenv.lsn_reset(strFile.c_str(), 0);
317 printf("%s closed\n", strFile.c_str());
318 mapFileUseCount.erase(mi++);
326 if (mapFileUseCount.empty())
328 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
344 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
348 return Read(make_pair(string("tx"), hash), txindex);
351 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
354 return Write(make_pair(string("tx"), hash), txindex);
357 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
362 uint256 hash = tx.GetHash();
363 CTxIndex txindex(pos, tx.vout.size());
364 return Write(make_pair(string("tx"), hash), txindex);
367 bool CTxDB::EraseTxIndex(const CTransaction& tx)
370 uint256 hash = tx.GetHash();
372 return Erase(make_pair(string("tx"), hash));
375 bool CTxDB::ContainsTx(uint256 hash)
378 return Exists(make_pair(string("tx"), hash));
381 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
387 Dbc* pcursor = GetCursor();
391 unsigned int fFlags = DB_SET_RANGE;
395 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
396 if (fFlags == DB_SET_RANGE)
397 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
398 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
399 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
401 if (ret == DB_NOTFOUND)
413 ssKey >> strType >> hashItem >> pos;
415 ssValue >> nItemHeight;
418 if (strType != "owner" || hashItem != hash160)
420 if (nItemHeight >= nMinHeight)
422 vtx.resize(vtx.size()+1);
423 if (!vtx.back().ReadFromDisk(pos))
435 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
439 if (!ReadTxIndex(hash, txindex))
441 return (tx.ReadFromDisk(txindex.pos));
444 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
447 return ReadDiskTx(hash, tx, txindex);
450 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
452 return ReadDiskTx(outpoint.hash, tx, txindex);
455 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
458 return ReadDiskTx(outpoint.hash, tx, txindex);
461 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
463 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
466 bool CTxDB::EraseBlockIndex(uint256 hash)
468 return Erase(make_pair(string("blockindex"), hash));
471 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
473 return Read(string("hashBestChain"), hashBestChain);
476 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
478 return Write(string("hashBestChain"), hashBestChain);
481 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
483 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
486 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
488 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
491 CBlockIndex static * InsertBlockIndex(uint256 hash)
497 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
498 if (mi != mapBlockIndex.end())
502 CBlockIndex* pindexNew = new CBlockIndex();
504 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
505 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
506 pindexNew->phashBlock = &((*mi).first);
511 bool CTxDB::LoadBlockIndex()
513 // Get database cursor
514 Dbc* pcursor = GetCursor();
518 // Load mapBlockIndex
519 unsigned int fFlags = DB_SET_RANGE;
523 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
524 if (fFlags == DB_SET_RANGE)
525 ssKey << make_pair(string("blockindex"), uint256(0));
526 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
527 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
529 if (ret == DB_NOTFOUND)
537 if (strType == "blockindex" && !fRequestShutdown)
539 CDiskBlockIndex diskindex;
540 ssValue >> diskindex;
542 // Construct block index object
543 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
544 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
545 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
546 pindexNew->nFile = diskindex.nFile;
547 pindexNew->nBlockPos = diskindex.nBlockPos;
548 pindexNew->nHeight = diskindex.nHeight;
549 pindexNew->nVersion = diskindex.nVersion;
550 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
551 pindexNew->nTime = diskindex.nTime;
552 pindexNew->nBits = diskindex.nBits;
553 pindexNew->nNonce = diskindex.nNonce;
555 // Watch for genesis block
556 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
557 pindexGenesisBlock = pindexNew;
559 if (!pindexNew->CheckIndex())
560 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
564 break; // if shutdown requested or finished loading block index
569 if (fRequestShutdown)
572 // Calculate bnChainWork
573 vector<pair<int, CBlockIndex*> > vSortedByHeight;
574 vSortedByHeight.reserve(mapBlockIndex.size());
575 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
577 CBlockIndex* pindex = item.second;
578 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
580 sort(vSortedByHeight.begin(), vSortedByHeight.end());
581 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
583 CBlockIndex* pindex = item.second;
584 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
587 // Load hashBestChain pointer to end of best chain
588 if (!ReadHashBestChain(hashBestChain))
590 if (pindexGenesisBlock == NULL)
592 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
594 if (!mapBlockIndex.count(hashBestChain))
595 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
596 pindexBest = mapBlockIndex[hashBestChain];
597 nBestHeight = pindexBest->nHeight;
598 bnBestChainWork = pindexBest->bnChainWork;
599 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
601 // Load bnBestInvalidWork, OK if it doesn't exist
602 ReadBestInvalidWork(bnBestInvalidWork);
604 // Verify blocks in the best chain
605 int nCheckLevel = GetArg("-checklevel", 1);
606 int nCheckDepth = GetArg( "-checkblocks", 2500);
607 if (nCheckDepth == 0)
608 nCheckDepth = 1000000000; // suffices until the year 19000
609 if (nCheckDepth > nBestHeight)
610 nCheckDepth = nBestHeight;
611 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
612 CBlockIndex* pindexFork = NULL;
613 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
614 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
616 if (pindex->nHeight < nBestHeight-nCheckDepth)
619 if (!block.ReadFromDisk(pindex))
620 return error("LoadBlockIndex() : block.ReadFromDisk failed");
621 // check level 1: verify block validity
622 if (nCheckLevel>0 && !block.CheckBlock())
624 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
625 pindexFork = pindex->pprev;
627 // check level 2: verify transaction index validity
630 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
631 mapBlockPos[pos] = pindex;
632 BOOST_FOREACH(const CTransaction &tx, block.vtx)
634 uint256 hashTx = tx.GetHash();
636 if (ReadTxIndex(hashTx, txindex))
638 // check level 3: checker transaction hashes
639 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
641 // either an error or a duplicate transaction
642 CTransaction txFound;
643 if (!txFound.ReadFromDisk(txindex.pos))
645 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
646 pindexFork = pindex->pprev;
649 if (txFound.GetHash() != hashTx) // not a duplicate tx
651 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
652 pindexFork = pindex->pprev;
655 // check level 4: check whether spent txouts were spent within the main chain
656 unsigned int nOutput = 0;
659 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
663 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
664 if (!mapBlockPos.count(posFind))
666 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
667 pindexFork = pindex->pprev;
669 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
672 CTransaction txSpend;
673 if (!txSpend.ReadFromDisk(txpos))
675 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
676 pindexFork = pindex->pprev;
678 else if (!txSpend.CheckTransaction())
680 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
681 pindexFork = pindex->pprev;
686 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
687 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
691 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
692 pindexFork = pindex->pprev;
701 // check level 5: check whether all prevouts are marked spent
704 BOOST_FOREACH(const CTxIn &txin, tx.vin)
707 if (ReadTxIndex(txin.prevout.hash, txindex))
708 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
710 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
711 pindexFork = pindex->pprev;
720 // Reorg back to the fork
721 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
723 if (!block.ReadFromDisk(pindexFork))
724 return error("LoadBlockIndex() : block.ReadFromDisk failed");
726 block.SetBestChain(txdb, pindexFork);
740 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
742 return Write(string("addrman"), addrman);
745 bool CAddrDB::LoadAddresses()
747 if (Read(string("addrman"), addrman))
749 printf("Loaded %i addresses\n", addrman.size());
753 // Read pre-0.6 addr records
755 vector<CAddress> vAddr;
756 vector<vector<unsigned char> > vDelete;
759 Dbc* pcursor = GetCursor();
766 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
767 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
768 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
769 if (ret == DB_NOTFOUND)
777 if (strType == "addr")
781 vAddr.push_back(addr);
786 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
787 printf("Loaded %i addresses\n", addrman.size());
789 // Note: old records left; we ran into hangs-on-startup
790 // bugs for some users who (we think) were running after
791 // an unclean shutdown.
798 return CAddrDB("cr+").LoadAddresses();