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.
10 #include <boost/version.hpp>
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
22 unsigned int nWalletDBUpdated;
30 CCriticalSection cs_db;
31 static bool fDbEnvInit = 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" && IsInitialBlockDownload())
172 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
176 --mapFileUseCount[strFile];
180 void CloseDb(const string& strFile)
184 if (mapDb[strFile] != NULL)
186 // Close the database handle
187 Db* pdb = mapDb[strFile];
190 mapDb[strFile] = NULL;
195 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
201 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
203 // Flush log data to the dat file
205 dbenv.txn_checkpoint(0, 0, 0);
206 dbenv.lsn_reset(strFile.c_str(), 0);
207 mapFileUseCount.erase(strFile);
209 bool fSuccess = true;
210 printf("Rewriting %s...\n", strFile.c_str());
211 string strFileRes = strFile + ".rewrite";
212 { // surround usage of db with extra {}
213 CDB db(strFile.c_str(), "r");
214 Db* pdbCopy = new Db(&dbenv, 0);
216 int ret = pdbCopy->open(NULL, // Txn pointer
217 strFileRes.c_str(), // Filename
218 "main", // Logical db name
219 DB_BTREE, // Database type
224 printf("Cannot create database file %s\n", strFileRes.c_str());
228 Dbc* pcursor = db.GetCursor();
234 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
235 if (ret == DB_NOTFOUND)
247 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
249 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
253 ssValue << CLIENT_VERSION;
255 Dbt datKey(&ssKey[0], ssKey.size());
256 Dbt datValue(&ssValue[0], ssValue.size());
257 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
265 if (pdbCopy->close(0))
273 if (dbA.remove(strFile.c_str(), NULL, 0))
276 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
280 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
290 void DBFlush(bool fShutdown)
292 // Flush log data to the actual data file
293 // on all files that are not in use
294 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
299 map<string, int>::iterator mi = mapFileUseCount.begin();
300 while (mi != mapFileUseCount.end())
302 string strFile = (*mi).first;
303 int nRefCount = (*mi).second;
304 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
307 // Move log data to the dat file
309 dbenv.txn_checkpoint(0, 0, 0);
310 printf("%s flush\n", strFile.c_str());
311 dbenv.lsn_reset(strFile.c_str(), 0);
312 mapFileUseCount.erase(mi++);
320 if (mapFileUseCount.empty())
322 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
338 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
342 return Read(make_pair(string("tx"), hash), txindex);
345 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
348 return Write(make_pair(string("tx"), hash), txindex);
351 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
356 uint256 hash = tx.GetHash();
357 CTxIndex txindex(pos, tx.vout.size());
358 return Write(make_pair(string("tx"), hash), txindex);
361 bool CTxDB::EraseTxIndex(const CTransaction& tx)
364 uint256 hash = tx.GetHash();
366 return Erase(make_pair(string("tx"), hash));
369 bool CTxDB::ContainsTx(uint256 hash)
372 return Exists(make_pair(string("tx"), hash));
375 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
381 Dbc* pcursor = GetCursor();
385 unsigned int fFlags = DB_SET_RANGE;
390 if (fFlags == DB_SET_RANGE)
391 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
393 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
395 if (ret == DB_NOTFOUND)
407 ssKey >> strType >> hashItem >> pos;
409 ssValue >> nItemHeight;
412 if (strType != "owner" || hashItem != hash160)
414 if (nItemHeight >= nMinHeight)
416 vtx.resize(vtx.size()+1);
417 if (!vtx.back().ReadFromDisk(pos))
429 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
433 if (!ReadTxIndex(hash, txindex))
435 return (tx.ReadFromDisk(txindex.pos));
438 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
441 return ReadDiskTx(hash, tx, txindex);
444 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
446 return ReadDiskTx(outpoint.hash, tx, txindex);
449 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
452 return ReadDiskTx(outpoint.hash, tx, txindex);
455 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
457 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
460 bool CTxDB::EraseBlockIndex(uint256 hash)
462 return Erase(make_pair(string("blockindex"), hash));
465 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
467 return Read(string("hashBestChain"), hashBestChain);
470 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
472 return Write(string("hashBestChain"), hashBestChain);
475 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
477 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
480 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
482 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
485 CBlockIndex static * InsertBlockIndex(uint256 hash)
491 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
492 if (mi != mapBlockIndex.end())
496 CBlockIndex* pindexNew = new CBlockIndex();
498 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
499 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
500 pindexNew->phashBlock = &((*mi).first);
505 bool CTxDB::LoadBlockIndex()
507 // Get database cursor
508 Dbc* pcursor = GetCursor();
512 // Load mapBlockIndex
513 unsigned int fFlags = DB_SET_RANGE;
518 if (fFlags == DB_SET_RANGE)
519 ssKey << make_pair(string("blockindex"), uint256(0));
521 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
523 if (ret == DB_NOTFOUND)
531 if (strType == "blockindex")
533 CDiskBlockIndex diskindex;
534 ssValue >> diskindex;
536 // Construct block index object
537 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
538 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
539 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
540 pindexNew->nFile = diskindex.nFile;
541 pindexNew->nBlockPos = diskindex.nBlockPos;
542 pindexNew->nHeight = diskindex.nHeight;
543 pindexNew->nVersion = diskindex.nVersion;
544 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
545 pindexNew->nTime = diskindex.nTime;
546 pindexNew->nBits = diskindex.nBits;
547 pindexNew->nNonce = diskindex.nNonce;
549 // Watch for genesis block
550 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
551 pindexGenesisBlock = pindexNew;
553 if (!pindexNew->CheckIndex())
554 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
563 // Calculate bnChainWork
564 vector<pair<int, CBlockIndex*> > vSortedByHeight;
565 vSortedByHeight.reserve(mapBlockIndex.size());
566 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
568 CBlockIndex* pindex = item.second;
569 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
571 sort(vSortedByHeight.begin(), vSortedByHeight.end());
572 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
574 CBlockIndex* pindex = item.second;
575 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
578 // Load hashBestChain pointer to end of best chain
579 if (!ReadHashBestChain(hashBestChain))
581 if (pindexGenesisBlock == NULL)
583 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
585 if (!mapBlockIndex.count(hashBestChain))
586 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
587 pindexBest = mapBlockIndex[hashBestChain];
588 nBestHeight = pindexBest->nHeight;
589 bnBestChainWork = pindexBest->bnChainWork;
590 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
592 // Load bnBestInvalidWork, OK if it doesn't exist
593 ReadBestInvalidWork(bnBestInvalidWork);
595 // Verify blocks in the best chain
596 int nCheckLevel = GetArg("-checklevel", 1);
597 int nCheckDepth = GetArg( "-checkblocks", 2500);
598 if (nCheckDepth == 0)
599 nCheckDepth = 1000000000; // suffices until the year 19000
600 if (nCheckDepth > nBestHeight)
601 nCheckDepth = nBestHeight;
602 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
603 CBlockIndex* pindexFork = NULL;
604 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
605 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
607 if (pindex->nHeight < nBestHeight-nCheckDepth)
610 if (!block.ReadFromDisk(pindex))
611 return error("LoadBlockIndex() : block.ReadFromDisk failed");
612 // check level 1: verify block validity
613 if (nCheckLevel>0 && !block.CheckBlock())
615 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
616 pindexFork = pindex->pprev;
618 // check level 2: verify transaction index validity
621 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
622 mapBlockPos[pos] = pindex;
623 BOOST_FOREACH(const CTransaction &tx, block.vtx)
625 uint256 hashTx = tx.GetHash();
627 if (ReadTxIndex(hashTx, txindex))
629 // check level 3: checker transaction hashes
630 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
632 // either an error or a duplicate transaction
633 CTransaction txFound;
634 if (!txFound.ReadFromDisk(txindex.pos))
636 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
637 pindexFork = pindex->pprev;
640 if (txFound.GetHash() != hashTx) // not a duplicate tx
642 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
643 pindexFork = pindex->pprev;
646 // check level 4: check whether spent txouts were spent within the main chain
650 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
654 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
655 if (!mapBlockPos.count(posFind))
657 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
658 pindexFork = pindex->pprev;
660 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
663 CTransaction txSpend;
664 if (!txSpend.ReadFromDisk(txpos))
666 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
667 pindexFork = pindex->pprev;
669 else if (!txSpend.CheckTransaction())
671 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
672 pindexFork = pindex->pprev;
677 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
678 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
682 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
683 pindexFork = pindex->pprev;
692 // check level 5: check whether all prevouts are marked spent
695 BOOST_FOREACH(const CTxIn &txin, tx.vin)
698 if (ReadTxIndex(txin.prevout.hash, txindex))
699 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
701 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
702 pindexFork = pindex->pprev;
711 // Reorg back to the fork
712 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
714 if (!block.ReadFromDisk(pindexFork))
715 return error("LoadBlockIndex() : block.ReadFromDisk failed");
717 block.SetBestChain(txdb, pindexFork);
731 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
733 return Write(string("addrman"), addrman);
736 bool CAddrDB::LoadAddresses()
738 if (Read(string("addrman"), addrman))
740 printf("Loaded %i addresses\n", addrman.size());
744 // Read pre-0.6 addr records
746 vector<CAddress> vAddr;
747 vector<vector<unsigned char> > vDelete;
750 Dbc* pcursor = GetCursor();
759 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
760 if (ret == DB_NOTFOUND)
768 if (strType == "addr")
772 vAddr.push_back(addr);
777 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
778 printf("Loaded %i addresses\n", addrman.size());
780 // Note: old records left; we ran into hangs-on-startup
781 // bugs for some users who (we think) were running after
782 // an unclean shutdown.
789 return CAddrDB("cr+").LoadAddresses();