1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "checkpoints.h"
12 #include <boost/version.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
24 unsigned int nWalletDBUpdated;
32 CCriticalSection cs_db;
33 static bool fDbEnvInit = false;
34 bool fDetachDB = false;
36 map<string, int> mapFileUseCount;
37 static map<string, Db*> mapDb;
39 static void EnvShutdown()
49 catch (const DbException& e)
51 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
53 DbEnv(0).remove(GetDataDir().string().c_str(), 0);
70 CDB::CDB(const char *pszFile, const char* pszMode) : pdb(NULL)
76 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
77 bool fCreate = strchr(pszMode, 'c');
78 unsigned int nFlags = DB_THREAD;
88 filesystem::path pathDataDir = GetDataDir();
89 filesystem::path pathLogDir = pathDataDir / "database";
90 filesystem::create_directory(pathLogDir);
91 filesystem::path pathErrorFile = pathDataDir / "db.log";
92 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
94 int nDbCache = GetArg("-dbcache", 25);
95 dbenv.set_lg_dir(pathLogDir.string().c_str());
96 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
97 dbenv.set_lg_bsize(1048576);
98 dbenv.set_lg_max(10485760);
99 dbenv.set_lk_max_locks(10000);
100 dbenv.set_lk_max_objects(10000);
101 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
102 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
103 dbenv.set_flags(DB_AUTO_COMMIT, 1);
104 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
105 ret = dbenv.open(pathDataDir.string().c_str(),
115 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
120 ++mapFileUseCount[strFile];
121 pdb = mapDb[strFile];
124 pdb = new Db(&dbenv, 0);
126 ret = pdb->open(NULL, // Txn pointer
128 "main", // Logical db name
129 DB_BTREE, // Database type
139 --mapFileUseCount[strFile];
142 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
145 if (fCreate && !Exists(string("version")))
147 bool fTmp = fReadOnly;
149 WriteVersion(CLIENT_VERSION);
153 mapDb[strFile] = pdb;
163 vTxn.front()->abort();
167 // Flush database activity from memory pool to disk log
168 unsigned int nMinutes = 0;
171 if (strFile == "addr.dat")
173 if (strFile == "blkindex.dat")
175 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
178 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
182 --mapFileUseCount[strFile];
186 void CloseDb(const string& strFile)
190 if (mapDb[strFile] != NULL)
192 // Close the database handle
193 Db* pdb = mapDb[strFile];
196 mapDb[strFile] = NULL;
201 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
207 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
209 // Flush log data to the dat file
211 dbenv.txn_checkpoint(0, 0, 0);
212 dbenv.lsn_reset(strFile.c_str(), 0);
213 mapFileUseCount.erase(strFile);
215 bool fSuccess = true;
216 printf("Rewriting %s...\n", strFile.c_str());
217 string strFileRes = strFile + ".rewrite";
218 { // surround usage of db with extra {}
219 CDB db(strFile.c_str(), "r");
220 Db* pdbCopy = new Db(&dbenv, 0);
222 int ret = pdbCopy->open(NULL, // Txn pointer
223 strFileRes.c_str(), // Filename
224 "main", // Logical db name
225 DB_BTREE, // Database type
230 printf("Cannot create database file %s\n", strFileRes.c_str());
234 Dbc* pcursor = db.GetCursor();
238 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
239 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
240 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
241 if (ret == DB_NOTFOUND)
253 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
255 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
259 ssValue << CLIENT_VERSION;
261 Dbt datKey(&ssKey[0], ssKey.size());
262 Dbt datValue(&ssValue[0], ssValue.size());
263 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
271 if (pdbCopy->close(0))
279 if (dbA.remove(strFile.c_str(), NULL, 0))
282 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
286 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
296 void DBFlush(bool fShutdown)
298 // Flush log data to the actual data file
299 // on all files that are not in use
300 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
305 map<string, int>::iterator mi = mapFileUseCount.begin();
306 while (mi != mapFileUseCount.end())
308 string strFile = (*mi).first;
309 int nRefCount = (*mi).second;
310 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
313 // Move log data to the dat file
315 printf("%s checkpoint\n", strFile.c_str());
316 dbenv.txn_checkpoint(0, 0, 0);
317 if ((strFile != "blkindex.dat" && strFile != "addr.dat") || fDetachDB) {
318 printf("%s detach\n", strFile.c_str());
319 dbenv.lsn_reset(strFile.c_str(), 0);
321 printf("%s closed\n", strFile.c_str());
322 mapFileUseCount.erase(mi++);
330 if (mapFileUseCount.empty())
332 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
348 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
352 return Read(make_pair(string("tx"), hash), txindex);
355 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
358 return Write(make_pair(string("tx"), hash), txindex);
361 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
366 uint256 hash = tx.GetHash();
367 CTxIndex txindex(pos, tx.vout.size());
368 return Write(make_pair(string("tx"), hash), txindex);
371 bool CTxDB::EraseTxIndex(const CTransaction& tx)
374 uint256 hash = tx.GetHash();
376 return Erase(make_pair(string("tx"), hash));
379 bool CTxDB::ContainsTx(uint256 hash)
382 return Exists(make_pair(string("tx"), hash));
385 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
391 Dbc* pcursor = GetCursor();
395 unsigned int fFlags = DB_SET_RANGE;
399 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
400 if (fFlags == DB_SET_RANGE)
401 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
402 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
403 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
405 if (ret == DB_NOTFOUND)
420 ssKey >> strType >> hashItem >> pos;
421 ssValue >> nItemHeight;
423 catch (std::exception &e) {
424 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
428 if (strType != "owner" || hashItem != hash160)
430 if (nItemHeight >= nMinHeight)
432 vtx.resize(vtx.size()+1);
433 if (!vtx.back().ReadFromDisk(pos))
445 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
449 if (!ReadTxIndex(hash, txindex))
451 return (tx.ReadFromDisk(txindex.pos));
454 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
457 return ReadDiskTx(hash, tx, txindex);
460 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
462 return ReadDiskTx(outpoint.hash, tx, txindex);
465 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
468 return ReadDiskTx(outpoint.hash, tx, txindex);
471 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
473 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
476 bool CTxDB::EraseBlockIndex(uint256 hash)
478 return Erase(make_pair(string("blockindex"), hash));
481 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
483 return Read(string("hashBestChain"), hashBestChain);
486 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
488 return Write(string("hashBestChain"), hashBestChain);
491 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
493 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
496 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
498 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
501 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
503 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
506 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
508 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
511 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
513 return Read(string("strCheckpointPubKey"), strPubKey);
516 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
518 return Write(string("strCheckpointPubKey"), strPubKey);
521 CBlockIndex static * InsertBlockIndex(uint256 hash)
527 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
528 if (mi != mapBlockIndex.end())
532 CBlockIndex* pindexNew = new CBlockIndex();
534 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
535 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
536 pindexNew->phashBlock = &((*mi).first);
541 bool CTxDB::LoadBlockIndex()
543 // Get database cursor
544 Dbc* pcursor = GetCursor();
548 // Load mapBlockIndex
549 unsigned int fFlags = DB_SET_RANGE;
553 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
554 if (fFlags == DB_SET_RANGE)
555 ssKey << make_pair(string("blockindex"), uint256(0));
556 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
557 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
559 if (ret == DB_NOTFOUND)
569 if (strType == "blockindex" && !fRequestShutdown)
571 CDiskBlockIndex diskindex;
572 ssValue >> diskindex;
574 // Construct block index object
575 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
576 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
577 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
578 pindexNew->nFile = diskindex.nFile;
579 pindexNew->nBlockPos = diskindex.nBlockPos;
580 pindexNew->nHeight = diskindex.nHeight;
581 pindexNew->nMint = diskindex.nMint;
582 pindexNew->nMoneySupply = diskindex.nMoneySupply;
583 pindexNew->fProofOfStake = diskindex.fProofOfStake;
584 pindexNew->prevoutStake = diskindex.prevoutStake;
585 pindexNew->nVersion = diskindex.nVersion;
586 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
587 pindexNew->nTime = diskindex.nTime;
588 pindexNew->nBits = diskindex.nBits;
589 pindexNew->nNonce = diskindex.nNonce;
591 // Watch for genesis block
592 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
593 pindexGenesisBlock = pindexNew;
595 if (!pindexNew->CheckIndex())
596 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
598 // ppcoin: build setStakeSeen
599 if (pindexNew->fProofOfStake)
600 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
604 break; // if shutdown requested or finished loading block index
607 catch (std::exception &e) {
608 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
613 if (fRequestShutdown)
616 // Calculate bnChainTrust
617 vector<pair<int, CBlockIndex*> > vSortedByHeight;
618 vSortedByHeight.reserve(mapBlockIndex.size());
619 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
621 CBlockIndex* pindex = item.second;
622 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
624 sort(vSortedByHeight.begin(), vSortedByHeight.end());
625 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
627 CBlockIndex* pindex = item.second;
628 pindex->bnChainTrust = (pindex->pprev ? pindex->pprev->bnChainTrust : 0) + pindex->GetBlockTrust();
631 // Load hashBestChain pointer to end of best chain
632 if (!ReadHashBestChain(hashBestChain))
634 if (pindexGenesisBlock == NULL)
636 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
638 if (!mapBlockIndex.count(hashBestChain))
639 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
640 pindexBest = mapBlockIndex[hashBestChain];
641 nBestHeight = pindexBest->nHeight;
642 bnBestChainTrust = pindexBest->bnChainTrust;
643 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str());
645 // ppcoin: load hashSyncCheckpoint
646 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
647 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
648 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
650 // Load bnBestInvalidTrust, OK if it doesn't exist
651 ReadBestInvalidTrust(bnBestInvalidTrust);
653 // Verify blocks in the best chain
654 int nCheckLevel = GetArg("-checklevel", 1);
655 int nCheckDepth = GetArg( "-checkblocks", 2500);
656 if (nCheckDepth == 0)
657 nCheckDepth = 1000000000; // suffices until the year 19000
658 if (nCheckDepth > nBestHeight)
659 nCheckDepth = nBestHeight;
660 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
661 CBlockIndex* pindexFork = NULL;
662 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
663 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
665 if (pindex->nHeight < nBestHeight-nCheckDepth)
668 if (!block.ReadFromDisk(pindex))
669 return error("LoadBlockIndex() : block.ReadFromDisk failed");
670 // check level 1: verify block validity
671 if (nCheckLevel>0 && !block.CheckBlock())
673 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
674 pindexFork = pindex->pprev;
676 // check level 2: verify transaction index validity
679 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
680 mapBlockPos[pos] = pindex;
681 BOOST_FOREACH(const CTransaction &tx, block.vtx)
683 uint256 hashTx = tx.GetHash();
685 if (ReadTxIndex(hashTx, txindex))
687 // check level 3: checker transaction hashes
688 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
690 // either an error or a duplicate transaction
691 CTransaction txFound;
692 if (!txFound.ReadFromDisk(txindex.pos))
694 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
695 pindexFork = pindex->pprev;
698 if (txFound.GetHash() != hashTx) // not a duplicate tx
700 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
701 pindexFork = pindex->pprev;
704 // check level 4: check whether spent txouts were spent within the main chain
705 unsigned int nOutput = 0;
708 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
712 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
713 if (!mapBlockPos.count(posFind))
715 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
716 pindexFork = pindex->pprev;
718 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
721 CTransaction txSpend;
722 if (!txSpend.ReadFromDisk(txpos))
724 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
725 pindexFork = pindex->pprev;
727 else if (!txSpend.CheckTransaction())
729 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
730 pindexFork = pindex->pprev;
735 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
736 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
740 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
741 pindexFork = pindex->pprev;
750 // check level 5: check whether all prevouts are marked spent
753 BOOST_FOREACH(const CTxIn &txin, tx.vin)
756 if (ReadTxIndex(txin.prevout.hash, txindex))
757 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
759 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
760 pindexFork = pindex->pprev;
769 // Reorg back to the fork
770 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
772 if (!block.ReadFromDisk(pindexFork))
773 return error("LoadBlockIndex() : block.ReadFromDisk failed");
775 block.SetBestChain(txdb, pindexFork);
789 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
791 return Write(string("addrman"), addrman);
794 bool CAddrDB::LoadAddresses()
796 if (Read(string("addrman"), addrman))
798 printf("Loaded %i addresses\n", addrman.size());
802 // Read pre-0.6 addr records
804 vector<CAddress> vAddr;
805 vector<vector<unsigned char> > vDelete;
808 Dbc* pcursor = GetCursor();
815 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
816 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
817 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
818 if (ret == DB_NOTFOUND)
826 if (strType == "addr")
830 vAddr.push_back(addr);
835 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
836 printf("Loaded %i addresses\n", addrman.size());
838 // Note: old records left; we ran into hangs-on-startup
839 // bugs for some users who (we think) were running after
840 // an unclean shutdown.
847 return CAddrDB("cr+").LoadAddresses();