1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 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"
13 #include <boost/version.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
25 unsigned int nWalletDBUpdated;
33 CCriticalSection cs_db;
34 static bool fDbEnvInit = false;
35 bool fDetachDB = false;
37 map<string, int> mapFileUseCount;
38 static map<string, Db*> mapDb;
40 static void EnvShutdown()
50 catch (const DbException& e)
52 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
54 DbEnv(0).remove(GetDataDir().string().c_str(), 0);
71 CDB::CDB(const char *pszFile, const char* pszMode) : pdb(NULL)
77 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
78 bool fCreate = strchr(pszMode, 'c');
79 unsigned int nFlags = DB_THREAD;
89 filesystem::path pathDataDir = GetDataDir();
90 filesystem::path pathLogDir = pathDataDir / "database";
91 filesystem::create_directory(pathLogDir);
92 filesystem::path pathErrorFile = pathDataDir / "db.log";
93 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
95 int nDbCache = GetArg("-dbcache", 25);
96 dbenv.set_lg_dir(pathLogDir.string().c_str());
97 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
98 dbenv.set_lg_bsize(1048576);
99 dbenv.set_lg_max(10485760);
100 dbenv.set_lk_max_locks(10000);
101 dbenv.set_lk_max_objects(10000);
102 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
103 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
104 dbenv.set_flags(DB_AUTO_COMMIT, 1);
105 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
106 ret = dbenv.open(pathDataDir.string().c_str(),
116 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
121 ++mapFileUseCount[strFile];
122 pdb = mapDb[strFile];
125 pdb = new Db(&dbenv, 0);
127 ret = pdb->open(NULL, // Txn pointer
129 "main", // Logical db name
130 DB_BTREE, // Database type
140 --mapFileUseCount[strFile];
143 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
146 if (fCreate && !Exists(string("version")))
148 bool fTmp = fReadOnly;
150 WriteVersion(CLIENT_VERSION);
154 mapDb[strFile] = pdb;
164 vTxn.front()->abort();
168 // Flush database activity from memory pool to disk log
169 unsigned int nMinutes = 0;
172 if (strFile == "addr.dat")
174 if (strFile == "blkindex.dat")
176 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
179 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
183 --mapFileUseCount[strFile];
187 void CloseDb(const string& strFile)
191 if (mapDb[strFile] != NULL)
193 // Close the database handle
194 Db* pdb = mapDb[strFile];
197 mapDb[strFile] = NULL;
202 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
208 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
210 // Flush log data to the dat file
212 dbenv.txn_checkpoint(0, 0, 0);
213 dbenv.lsn_reset(strFile.c_str(), 0);
214 mapFileUseCount.erase(strFile);
216 bool fSuccess = true;
217 printf("Rewriting %s...\n", strFile.c_str());
218 string strFileRes = strFile + ".rewrite";
219 { // surround usage of db with extra {}
220 CDB db(strFile.c_str(), "r");
221 Db* pdbCopy = new Db(&dbenv, 0);
223 int ret = pdbCopy->open(NULL, // Txn pointer
224 strFileRes.c_str(), // Filename
225 "main", // Logical db name
226 DB_BTREE, // Database type
231 printf("Cannot create database file %s\n", strFileRes.c_str());
235 Dbc* pcursor = db.GetCursor();
239 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
240 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
241 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
242 if (ret == DB_NOTFOUND)
254 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
256 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
260 ssValue << CLIENT_VERSION;
262 Dbt datKey(&ssKey[0], ssKey.size());
263 Dbt datValue(&ssValue[0], ssValue.size());
264 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
272 if (pdbCopy->close(0))
280 if (dbA.remove(strFile.c_str(), NULL, 0))
283 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
287 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
297 void DBFlush(bool fShutdown)
299 // Flush log data to the actual data file
300 // on all files that are not in use
301 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
306 map<string, int>::iterator mi = mapFileUseCount.begin();
307 while (mi != mapFileUseCount.end())
309 string strFile = (*mi).first;
310 int nRefCount = (*mi).second;
311 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
314 // Move log data to the dat file
316 printf("%s checkpoint\n", strFile.c_str());
317 dbenv.txn_checkpoint(0, 0, 0);
318 if ((strFile != "blkindex.dat" && strFile != "addr.dat") || fDetachDB) {
319 printf("%s detach\n", strFile.c_str());
320 dbenv.lsn_reset(strFile.c_str(), 0);
322 printf("%s closed\n", strFile.c_str());
323 mapFileUseCount.erase(mi++);
331 if (mapFileUseCount.empty())
333 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
349 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
353 return Read(make_pair(string("tx"), hash), txindex);
356 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
359 return Write(make_pair(string("tx"), hash), txindex);
362 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
367 uint256 hash = tx.GetHash();
368 CTxIndex txindex(pos, tx.vout.size());
369 return Write(make_pair(string("tx"), hash), txindex);
372 bool CTxDB::EraseTxIndex(const CTransaction& tx)
375 uint256 hash = tx.GetHash();
377 return Erase(make_pair(string("tx"), hash));
380 bool CTxDB::ContainsTx(uint256 hash)
383 return Exists(make_pair(string("tx"), hash));
386 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
392 Dbc* pcursor = GetCursor();
396 unsigned int fFlags = DB_SET_RANGE;
400 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
401 if (fFlags == DB_SET_RANGE)
402 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
403 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
404 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
406 if (ret == DB_NOTFOUND)
421 ssKey >> strType >> hashItem >> pos;
422 ssValue >> nItemHeight;
424 catch (std::exception &e) {
425 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
429 if (strType != "owner" || hashItem != hash160)
431 if (nItemHeight >= nMinHeight)
433 vtx.resize(vtx.size()+1);
434 if (!vtx.back().ReadFromDisk(pos))
446 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
450 if (!ReadTxIndex(hash, txindex))
452 return (tx.ReadFromDisk(txindex.pos));
455 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
458 return ReadDiskTx(hash, tx, txindex);
461 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
463 return ReadDiskTx(outpoint.hash, tx, txindex);
466 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
469 return ReadDiskTx(outpoint.hash, tx, txindex);
472 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
474 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
477 bool CTxDB::EraseBlockIndex(uint256 hash)
479 return Erase(make_pair(string("blockindex"), hash));
482 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
484 return Read(string("hashBestChain"), hashBestChain);
487 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
489 return Write(string("hashBestChain"), hashBestChain);
492 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
494 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
497 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
499 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
502 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
504 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
507 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
509 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
512 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
514 return Read(string("strCheckpointPubKey"), strPubKey);
517 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
519 return Write(string("strCheckpointPubKey"), strPubKey);
522 CBlockIndex static * InsertBlockIndex(uint256 hash)
528 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
529 if (mi != mapBlockIndex.end())
533 CBlockIndex* pindexNew = new CBlockIndex();
535 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
536 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
537 pindexNew->phashBlock = &((*mi).first);
542 bool CTxDB::LoadBlockIndex()
544 // Get database cursor
545 Dbc* pcursor = GetCursor();
549 // Load mapBlockIndex
550 unsigned int fFlags = DB_SET_RANGE;
554 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
555 if (fFlags == DB_SET_RANGE)
556 ssKey << make_pair(string("blockindex"), uint256(0));
557 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
558 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
560 if (ret == DB_NOTFOUND)
570 if (strType == "blockindex" && !fRequestShutdown)
572 CDiskBlockIndex diskindex;
573 ssValue >> diskindex;
575 // Construct block index object
576 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
577 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
578 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
579 pindexNew->nFile = diskindex.nFile;
580 pindexNew->nBlockPos = diskindex.nBlockPos;
581 pindexNew->nHeight = diskindex.nHeight;
582 pindexNew->nMint = diskindex.nMint;
583 pindexNew->nMoneySupply = diskindex.nMoneySupply;
584 pindexNew->nFlags = diskindex.nFlags;
585 pindexNew->nStakeModifier = diskindex.nStakeModifier;
586 pindexNew->prevoutStake = diskindex.prevoutStake;
587 pindexNew->nStakeTime = diskindex.nStakeTime;
588 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
589 pindexNew->nVersion = diskindex.nVersion;
590 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
591 pindexNew->nTime = diskindex.nTime;
592 pindexNew->nBits = diskindex.nBits;
593 pindexNew->nNonce = diskindex.nNonce;
595 // Watch for genesis block
596 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
597 pindexGenesisBlock = pindexNew;
599 if (!pindexNew->CheckIndex())
600 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
602 // ppcoin: build setStakeSeen
603 if (pindexNew->IsProofOfStake())
604 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
608 break; // if shutdown requested or finished loading block index
611 catch (std::exception &e) {
612 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
617 if (fRequestShutdown)
620 // Calculate bnChainTrust
621 vector<pair<int, CBlockIndex*> > vSortedByHeight;
622 vSortedByHeight.reserve(mapBlockIndex.size());
623 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
625 CBlockIndex* pindex = item.second;
626 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
628 sort(vSortedByHeight.begin(), vSortedByHeight.end());
629 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
631 CBlockIndex* pindex = item.second;
632 pindex->bnChainTrust = (pindex->pprev ? pindex->pprev->bnChainTrust : 0) + pindex->GetBlockTrust();
633 // ppcoin: calculate stake modifier checksum
634 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
635 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
636 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
639 // Load hashBestChain pointer to end of best chain
640 if (!ReadHashBestChain(hashBestChain))
642 if (pindexGenesisBlock == NULL)
644 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
646 if (!mapBlockIndex.count(hashBestChain))
647 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
648 pindexBest = mapBlockIndex[hashBestChain];
649 nBestHeight = pindexBest->nHeight;
650 bnBestChainTrust = pindexBest->bnChainTrust;
651 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str());
653 // ppcoin: load hashSyncCheckpoint
654 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
655 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
656 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
658 // Load bnBestInvalidTrust, OK if it doesn't exist
659 ReadBestInvalidTrust(bnBestInvalidTrust);
661 // Verify blocks in the best chain
662 int nCheckLevel = GetArg("-checklevel", 1);
663 int nCheckDepth = GetArg( "-checkblocks", 2500);
664 if (nCheckDepth == 0)
665 nCheckDepth = 1000000000; // suffices until the year 19000
666 if (nCheckDepth > nBestHeight)
667 nCheckDepth = nBestHeight;
668 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
669 CBlockIndex* pindexFork = NULL;
670 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
671 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
673 if (pindex->nHeight < nBestHeight-nCheckDepth)
676 if (!block.ReadFromDisk(pindex))
677 return error("LoadBlockIndex() : block.ReadFromDisk failed");
678 // check level 1: verify block validity
679 if (nCheckLevel>0 && !block.CheckBlock())
681 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
682 pindexFork = pindex->pprev;
684 // check level 2: verify transaction index validity
687 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
688 mapBlockPos[pos] = pindex;
689 BOOST_FOREACH(const CTransaction &tx, block.vtx)
691 uint256 hashTx = tx.GetHash();
693 if (ReadTxIndex(hashTx, txindex))
695 // check level 3: checker transaction hashes
696 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
698 // either an error or a duplicate transaction
699 CTransaction txFound;
700 if (!txFound.ReadFromDisk(txindex.pos))
702 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
703 pindexFork = pindex->pprev;
706 if (txFound.GetHash() != hashTx) // not a duplicate tx
708 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
709 pindexFork = pindex->pprev;
712 // check level 4: check whether spent txouts were spent within the main chain
713 unsigned int nOutput = 0;
716 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
720 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
721 if (!mapBlockPos.count(posFind))
723 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
724 pindexFork = pindex->pprev;
726 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
729 CTransaction txSpend;
730 if (!txSpend.ReadFromDisk(txpos))
732 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
733 pindexFork = pindex->pprev;
735 else if (!txSpend.CheckTransaction())
737 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
738 pindexFork = pindex->pprev;
743 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
744 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
748 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
749 pindexFork = pindex->pprev;
758 // check level 5: check whether all prevouts are marked spent
761 BOOST_FOREACH(const CTxIn &txin, tx.vin)
764 if (ReadTxIndex(txin.prevout.hash, txindex))
765 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
767 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
768 pindexFork = pindex->pprev;
777 // Reorg back to the fork
778 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
780 if (!block.ReadFromDisk(pindexFork))
781 return error("LoadBlockIndex() : block.ReadFromDisk failed");
783 block.SetBestChain(txdb, pindexFork);
797 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
799 return Write(string("addrman"), addrman);
802 bool CAddrDB::LoadAddresses()
804 if (Read(string("addrman"), addrman))
806 printf("Loaded %i addresses\n", addrman.size());
810 // Read pre-0.6 addr records
812 vector<CAddress> vAddr;
813 vector<vector<unsigned char> > vDelete;
816 Dbc* pcursor = GetCursor();
823 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
824 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
825 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
826 if (ret == DB_NOTFOUND)
834 if (strType == "addr")
838 vAddr.push_back(addr);
843 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
844 printf("Loaded %i addresses\n", addrman.size());
846 // Note: old records left; we ran into hangs-on-startup
847 // bugs for some users who (we think) were running after
848 // an unclean shutdown.
855 return CAddrDB("cr+").LoadAddresses();