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(uint64& nBestInvalidTrust)
493 return Read(string("nBestInvalidTrust"), nBestInvalidTrust);
496 bool CTxDB::WriteBestInvalidTrust(uint64 nBestInvalidTrust)
498 return Write(string("nBestInvalidTrust"), nBestInvalidTrust);
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->nChainTrust = diskindex.nChainTrust;
581 pindexNew->nHeight = diskindex.nHeight;
582 pindexNew->fProofOfStake = diskindex.fProofOfStake;
583 pindexNew->prevoutStake = diskindex.prevoutStake;
584 pindexNew->nVersion = diskindex.nVersion;
585 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
586 pindexNew->nTime = diskindex.nTime;
587 pindexNew->nBits = diskindex.nBits;
588 pindexNew->nNonce = diskindex.nNonce;
590 // Watch for genesis block
591 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
592 pindexGenesisBlock = pindexNew;
594 if (!pindexNew->CheckIndex())
595 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
597 // ppcoin: build setStakeSeen
598 if (pindexNew->fProofOfStake)
599 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
603 break; // if shutdown requested or finished loading block index
606 catch (std::exception &e) {
607 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
612 if (fRequestShutdown)
615 // Load hashBestChain pointer to end of best chain
616 if (!ReadHashBestChain(hashBestChain))
618 if (pindexGenesisBlock == NULL)
620 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
622 if (!mapBlockIndex.count(hashBestChain))
623 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
624 pindexBest = mapBlockIndex[hashBestChain];
625 nBestHeight = pindexBest->nHeight;
626 nBestChainTrust = pindexBest->nChainTrust;
627 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, nBestChainTrust);
629 // ppcoin: load hashSyncCheckpoint
630 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
631 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
632 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
634 // Load nBestInvalidTrust, OK if it doesn't exist
635 ReadBestInvalidTrust(nBestInvalidTrust);
637 // Verify blocks in the best chain
638 int nCheckLevel = GetArg("-checklevel", 1);
639 int nCheckDepth = GetArg( "-checkblocks", 2500);
640 if (nCheckDepth == 0)
641 nCheckDepth = 1000000000; // suffices until the year 19000
642 if (nCheckDepth > nBestHeight)
643 nCheckDepth = nBestHeight;
644 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
645 CBlockIndex* pindexFork = NULL;
646 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
647 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
649 if (pindex->nHeight < nBestHeight-nCheckDepth)
652 if (!block.ReadFromDisk(pindex))
653 return error("LoadBlockIndex() : block.ReadFromDisk failed");
654 // check level 1: verify block validity
655 if (nCheckLevel>0 && !block.CheckBlock())
657 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
658 pindexFork = pindex->pprev;
660 // check level 2: verify transaction index validity
663 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
664 mapBlockPos[pos] = pindex;
665 BOOST_FOREACH(const CTransaction &tx, block.vtx)
667 uint256 hashTx = tx.GetHash();
669 if (ReadTxIndex(hashTx, txindex))
671 // check level 3: checker transaction hashes
672 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
674 // either an error or a duplicate transaction
675 CTransaction txFound;
676 if (!txFound.ReadFromDisk(txindex.pos))
678 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
679 pindexFork = pindex->pprev;
682 if (txFound.GetHash() != hashTx) // not a duplicate tx
684 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
685 pindexFork = pindex->pprev;
688 // check level 4: check whether spent txouts were spent within the main chain
689 unsigned int nOutput = 0;
692 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
696 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
697 if (!mapBlockPos.count(posFind))
699 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
700 pindexFork = pindex->pprev;
702 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
705 CTransaction txSpend;
706 if (!txSpend.ReadFromDisk(txpos))
708 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
709 pindexFork = pindex->pprev;
711 else if (!txSpend.CheckTransaction())
713 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
714 pindexFork = pindex->pprev;
719 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
720 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
724 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
725 pindexFork = pindex->pprev;
734 // check level 5: check whether all prevouts are marked spent
737 BOOST_FOREACH(const CTxIn &txin, tx.vin)
740 if (ReadTxIndex(txin.prevout.hash, txindex))
741 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
743 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
744 pindexFork = pindex->pprev;
753 // Reorg back to the fork
754 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
756 if (!block.ReadFromDisk(pindexFork))
757 return error("LoadBlockIndex() : block.ReadFromDisk failed");
759 block.SetBestChain(txdb, pindexFork);
773 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
775 return Write(string("addrman"), addrman);
778 bool CAddrDB::LoadAddresses()
780 if (Read(string("addrman"), addrman))
782 printf("Loaded %i addresses\n", addrman.size());
786 // Read pre-0.6 addr records
788 vector<CAddress> vAddr;
789 vector<vector<unsigned char> > vDelete;
792 Dbc* pcursor = GetCursor();
799 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
800 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
801 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
802 if (ret == DB_NOTFOUND)
810 if (strType == "addr")
814 vAddr.push_back(addr);
819 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
820 printf("Loaded %i addresses\n", addrman.size());
822 // Note: old records left; we ran into hangs-on-startup
823 // bugs for some users who (we think) were running after
824 // an unclean shutdown.
831 return CAddrDB("cr+").LoadAddresses();