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" && IsInitialBlockDownload())
171 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
175 --mapFileUseCount[strFile];
179 void CloseDb(const string& strFile)
183 if (mapDb[strFile] != NULL)
185 // Close the database handle
186 Db* pdb = mapDb[strFile];
189 mapDb[strFile] = NULL;
194 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
200 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
202 // Flush log data to the dat file
204 dbenv.txn_checkpoint(0, 0, 0);
205 dbenv.lsn_reset(strFile.c_str(), 0);
206 mapFileUseCount.erase(strFile);
208 bool fSuccess = true;
209 printf("Rewriting %s...\n", strFile.c_str());
210 string strFileRes = strFile + ".rewrite";
211 { // surround usage of db with extra {}
212 CDB db(strFile.c_str(), "r");
213 Db* pdbCopy = new Db(&dbenv, 0);
215 int ret = pdbCopy->open(NULL, // Txn pointer
216 strFileRes.c_str(), // Filename
217 "main", // Logical db name
218 DB_BTREE, // Database type
223 printf("Cannot create database file %s\n", strFileRes.c_str());
227 Dbc* pcursor = db.GetCursor();
231 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
232 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
233 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
234 if (ret == DB_NOTFOUND)
246 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
248 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
252 ssValue << CLIENT_VERSION;
254 Dbt datKey(&ssKey[0], ssKey.size());
255 Dbt datValue(&ssValue[0], ssValue.size());
256 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
264 if (pdbCopy->close(0))
272 if (dbA.remove(strFile.c_str(), NULL, 0))
275 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
279 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
289 void DBFlush(bool fShutdown)
291 // Flush log data to the actual data file
292 // on all files that are not in use
293 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
298 map<string, int>::iterator mi = mapFileUseCount.begin();
299 while (mi != mapFileUseCount.end())
301 string strFile = (*mi).first;
302 int nRefCount = (*mi).second;
303 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
306 // Move log data to the dat file
308 dbenv.txn_checkpoint(0, 0, 0);
309 printf("%s flush\n", strFile.c_str());
310 dbenv.lsn_reset(strFile.c_str(), 0);
311 mapFileUseCount.erase(mi++);
319 if (mapFileUseCount.empty())
321 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
337 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
341 return Read(make_pair(string("tx"), hash), txindex);
344 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
347 return Write(make_pair(string("tx"), hash), txindex);
350 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
355 uint256 hash = tx.GetHash();
356 CTxIndex txindex(pos, tx.vout.size());
357 return Write(make_pair(string("tx"), hash), txindex);
360 bool CTxDB::EraseTxIndex(const CTransaction& tx)
363 uint256 hash = tx.GetHash();
365 return Erase(make_pair(string("tx"), hash));
368 bool CTxDB::ContainsTx(uint256 hash)
371 return Exists(make_pair(string("tx"), hash));
374 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
380 Dbc* pcursor = GetCursor();
384 unsigned int fFlags = DB_SET_RANGE;
388 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
389 if (fFlags == DB_SET_RANGE)
390 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
391 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
392 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
394 if (ret == DB_NOTFOUND)
406 ssKey >> strType >> hashItem >> pos;
408 ssValue >> nItemHeight;
411 if (strType != "owner" || hashItem != hash160)
413 if (nItemHeight >= nMinHeight)
415 vtx.resize(vtx.size()+1);
416 if (!vtx.back().ReadFromDisk(pos))
428 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
432 if (!ReadTxIndex(hash, txindex))
434 return (tx.ReadFromDisk(txindex.pos));
437 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
440 return ReadDiskTx(hash, tx, txindex);
443 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
445 return ReadDiskTx(outpoint.hash, tx, txindex);
448 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
451 return ReadDiskTx(outpoint.hash, tx, txindex);
454 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
456 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
459 bool CTxDB::EraseBlockIndex(uint256 hash)
461 return Erase(make_pair(string("blockindex"), hash));
464 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
466 return Read(string("hashBestChain"), hashBestChain);
469 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
471 return Write(string("hashBestChain"), hashBestChain);
474 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
476 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
479 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
481 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
484 CBlockIndex static * InsertBlockIndex(uint256 hash)
490 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
491 if (mi != mapBlockIndex.end())
495 CBlockIndex* pindexNew = new CBlockIndex();
497 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
498 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
499 pindexNew->phashBlock = &((*mi).first);
504 bool CTxDB::LoadBlockIndex()
506 // Get database cursor
507 Dbc* pcursor = GetCursor();
511 // Load mapBlockIndex
512 unsigned int fFlags = DB_SET_RANGE;
516 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
517 if (fFlags == DB_SET_RANGE)
518 ssKey << make_pair(string("blockindex"), uint256(0));
519 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
520 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
522 if (ret == DB_NOTFOUND)
530 if (strType == "blockindex")
532 CDiskBlockIndex diskindex;
533 ssValue >> diskindex;
535 // Construct block index object
536 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
537 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
538 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
539 pindexNew->nFile = diskindex.nFile;
540 pindexNew->nBlockPos = diskindex.nBlockPos;
541 pindexNew->nHeight = diskindex.nHeight;
542 pindexNew->nVersion = diskindex.nVersion;
543 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
544 pindexNew->nTime = diskindex.nTime;
545 pindexNew->nBits = diskindex.nBits;
546 pindexNew->nNonce = diskindex.nNonce;
548 // Watch for genesis block
549 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
550 pindexGenesisBlock = pindexNew;
552 if (!pindexNew->CheckIndex())
553 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
562 // Calculate bnChainWork
563 vector<pair<int, CBlockIndex*> > vSortedByHeight;
564 vSortedByHeight.reserve(mapBlockIndex.size());
565 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
567 CBlockIndex* pindex = item.second;
568 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
570 sort(vSortedByHeight.begin(), vSortedByHeight.end());
571 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
573 CBlockIndex* pindex = item.second;
574 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
577 // Load hashBestChain pointer to end of best chain
578 if (!ReadHashBestChain(hashBestChain))
580 if (pindexGenesisBlock == NULL)
582 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
584 if (!mapBlockIndex.count(hashBestChain))
585 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
586 pindexBest = mapBlockIndex[hashBestChain];
587 nBestHeight = pindexBest->nHeight;
588 bnBestChainWork = pindexBest->bnChainWork;
589 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
591 // Load bnBestInvalidWork, OK if it doesn't exist
592 ReadBestInvalidWork(bnBestInvalidWork);
594 // Verify blocks in the best chain
595 int nCheckLevel = GetArg("-checklevel", 1);
596 int nCheckDepth = GetArg( "-checkblocks", 2500);
597 if (nCheckDepth == 0)
598 nCheckDepth = 1000000000; // suffices until the year 19000
599 if (nCheckDepth > nBestHeight)
600 nCheckDepth = nBestHeight;
601 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
602 CBlockIndex* pindexFork = NULL;
603 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
604 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
606 if (pindex->nHeight < nBestHeight-nCheckDepth)
609 if (!block.ReadFromDisk(pindex))
610 return error("LoadBlockIndex() : block.ReadFromDisk failed");
611 // check level 1: verify block validity
612 if (nCheckLevel>0 && !block.CheckBlock())
614 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
615 pindexFork = pindex->pprev;
617 // check level 2: verify transaction index validity
620 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
621 mapBlockPos[pos] = pindex;
622 BOOST_FOREACH(const CTransaction &tx, block.vtx)
624 uint256 hashTx = tx.GetHash();
626 if (ReadTxIndex(hashTx, txindex))
628 // check level 3: checker transaction hashes
629 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
631 // either an error or a duplicate transaction
632 CTransaction txFound;
633 if (!txFound.ReadFromDisk(txindex.pos))
635 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
636 pindexFork = pindex->pprev;
639 if (txFound.GetHash() != hashTx) // not a duplicate tx
641 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
642 pindexFork = pindex->pprev;
645 // check level 4: check whether spent txouts were spent within the main chain
649 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
653 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
654 if (!mapBlockPos.count(posFind))
656 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
657 pindexFork = pindex->pprev;
659 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
662 CTransaction txSpend;
663 if (!txSpend.ReadFromDisk(txpos))
665 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
666 pindexFork = pindex->pprev;
668 else if (!txSpend.CheckTransaction())
670 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
671 pindexFork = pindex->pprev;
676 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
677 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
681 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
682 pindexFork = pindex->pprev;
691 // check level 5: check whether all prevouts are marked spent
694 BOOST_FOREACH(const CTxIn &txin, tx.vin)
697 if (ReadTxIndex(txin.prevout.hash, txindex))
698 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
700 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
701 pindexFork = pindex->pprev;
710 // Reorg back to the fork
711 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
713 if (!block.ReadFromDisk(pindexFork))
714 return error("LoadBlockIndex() : block.ReadFromDisk failed");
716 block.SetBestChain(txdb, pindexFork);
730 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
732 return Write(string("addrman"), addrman);
735 bool CAddrDB::LoadAddresses()
737 if (Read(string("addrman"), addrman))
739 printf("Loaded %i addresses\n", addrman.size());
743 // Read pre-0.6 addr records
745 vector<CAddress> vAddr;
746 vector<vector<unsigned char> > vDelete;
749 Dbc* pcursor = GetCursor();
756 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
757 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
758 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
759 if (ret == DB_NOTFOUND)
767 if (strType == "addr")
771 vAddr.push_back(addr);
776 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
777 printf("Loaded %i addresses\n", addrman.size());
779 // Note: old records left; we ran into hangs-on-startup
780 // bugs for some users who (we think) were running after
781 // an unclean shutdown.
788 return CAddrDB("cr+").LoadAddresses();