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 COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "checkpoints.h"
12 #include "ui_interface.h"
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
24 unsigned int nWalletDBUpdated;
34 void CDBEnv::EnvShutdown()
40 int ret = dbenv.close(0);
42 printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
44 DbEnv(0).remove(strPath.c_str(), 0);
47 CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
63 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
72 filesystem::path pathDataDir = pathEnv;
73 strPath = pathDataDir.string();
74 filesystem::path pathLogDir = pathDataDir / "database";
75 filesystem::create_directory(pathLogDir);
76 filesystem::path pathErrorFile = pathDataDir / "db.log";
77 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
79 unsigned int nEnvFlags = 0;
80 if (GetBoolArg("-privdb", true))
81 nEnvFlags |= DB_PRIVATE;
83 int nDbCache = GetArg("-dbcache", 25);
84 dbenv.set_lg_dir(pathLogDir.string().c_str());
85 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
86 dbenv.set_lg_bsize(1048576);
87 dbenv.set_lg_max(10485760);
89 // Bugfix: Bump lk_max_locks default to 537000, to safely handle reorgs with up to 5 blocks reversed
90 // dbenv.set_lk_max_locks(10000);
91 dbenv.set_lk_max_locks(537000);
93 dbenv.set_lk_max_objects(10000);
94 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
95 dbenv.set_flags(DB_AUTO_COMMIT, 1);
96 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
97 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
98 int ret = dbenv.open(strPath.c_str(),
109 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
114 // Check that the number of locks is sufficient (to prevent chain fork possibility, read http://bitcoin.org/may15 for more info)
116 if (!dbenv.get_lk_max_locks(&nMaxLocks))
118 int nBlocks, nDeepReorg;
119 std::string strMessage;
121 nBlocks = nMaxLocks / 48768;
122 nDeepReorg = (nBlocks - 1) / 2;
124 printf("Final lk_max_locks is %lu, sufficient for (worst case) %d block%s in a single transaction (up to a %d-deep reorganization)\n", (unsigned long)nMaxLocks, nBlocks, (nBlocks == 1) ? "" : "s", nDeepReorg);
128 strMessage = strprintf(_("Warning: DB_CONFIG has set_lk_max_locks %lu, which may be too low for a single block. If this limit is reached, NovaCoin may stop working."), (unsigned long)nMaxLocks);
130 strMessage = strprintf(_("Warning: DB_CONFIG has set_lk_max_locks %lu, which may be too low for a common blockchain reorganization. If this limit is reached, NovaCoin may stop working."), (unsigned long)nMaxLocks);
132 strMiscWarning = strMessage;
133 printf("*** %s\n", strMessage.c_str());
140 void CDBEnv::MakeMock()
143 throw runtime_error("CDBEnv::MakeMock(): already initialized");
146 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
148 printf("CDBEnv::MakeMock()\n");
150 dbenv.set_cachesize(1, 0, 1);
151 dbenv.set_lg_bsize(10485760*4);
152 dbenv.set_lg_max(10485760);
153 dbenv.set_lk_max_locks(10000);
154 dbenv.set_lk_max_objects(10000);
155 dbenv.set_flags(DB_AUTO_COMMIT, 1);
156 dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
157 int ret = dbenv.open(NULL,
167 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
173 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
176 assert(mapFileUseCount.count(strFile) == 0);
179 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
182 else if (recoverFunc == NULL)
186 bool fRecovered = (*recoverFunc)(*this, strFile);
187 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
190 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
191 std::vector<CDBEnv::KeyValPair >& vResult)
194 assert(mapFileUseCount.count(strFile) == 0);
196 u_int32_t flags = DB_SALVAGE;
197 if (fAggressive) flags |= DB_AGGRESSIVE;
199 stringstream strDump;
202 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
205 printf("ERROR: db salvage failed\n");
209 // Format of bdb dump is ascii lines:
218 while (!strDump.eof() && strLine != "HEADER=END")
219 getline(strDump, strLine); // Skip past header
221 std::string keyHex, valueHex;
222 while (!strDump.eof() && keyHex != "DATA=END")
224 getline(strDump, keyHex);
225 if (keyHex != "DATA_END")
227 getline(strDump, valueHex);
228 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
232 return (result == 0);
236 void CDBEnv::CheckpointLSN(std::string strFile)
238 dbenv.txn_checkpoint(0, 0, 0);
241 dbenv.lsn_reset(strFile.c_str(), 0);
245 CDB::CDB(const char *pszFile, const char* pszMode) :
246 pdb(NULL), activeTxn(NULL)
252 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
253 bool fCreate = strchr(pszMode, 'c');
254 unsigned int nFlags = DB_THREAD;
260 if (!bitdb.Open(GetDataDir()))
261 throw runtime_error("env open failed");
264 ++bitdb.mapFileUseCount[strFile];
265 pdb = bitdb.mapDb[strFile];
268 pdb = new Db(&bitdb.dbenv, 0);
270 bool fMockDb = bitdb.IsMock();
273 DbMpoolFile*mpf = pdb->get_mpf();
274 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
276 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
279 ret = pdb->open(NULL, // Txn pointer
280 fMockDb ? NULL : pszFile, // Filename
281 "main", // Logical db name
282 DB_BTREE, // Database type
290 --bitdb.mapFileUseCount[strFile];
292 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
295 if (fCreate && !Exists(string("version")))
297 bool fTmp = fReadOnly;
299 WriteVersion(CLIENT_VERSION);
303 bitdb.mapDb[strFile] = pdb;
308 static bool IsChainFile(std::string strFile)
310 if (strFile == "blkindex.dat")
325 // Flush database activity from memory pool to disk log
326 unsigned int nMinutes = 0;
329 if (IsChainFile(strFile))
331 if (IsChainFile(strFile) && IsInitialBlockDownload())
334 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
338 --bitdb.mapFileUseCount[strFile];
342 void CDBEnv::CloseDb(const string& strFile)
346 if (mapDb[strFile] != NULL)
348 // Close the database handle
349 Db* pdb = mapDb[strFile];
352 mapDb[strFile] = NULL;
357 bool CDBEnv::RemoveDb(const string& strFile)
359 this->CloseDb(strFile);
362 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
366 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
372 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
374 // Flush log data to the dat file
375 bitdb.CloseDb(strFile);
376 bitdb.CheckpointLSN(strFile);
377 bitdb.mapFileUseCount.erase(strFile);
379 bool fSuccess = true;
380 printf("Rewriting %s...\n", strFile.c_str());
381 string strFileRes = strFile + ".rewrite";
382 { // surround usage of db with extra {}
383 CDB db(strFile.c_str(), "r");
384 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
386 int ret = pdbCopy->open(NULL, // Txn pointer
387 strFileRes.c_str(), // Filename
388 "main", // Logical db name
389 DB_BTREE, // Database type
394 printf("Cannot create database file %s\n", strFileRes.c_str());
398 Dbc* pcursor = db.GetCursor();
402 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
403 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
404 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
405 if (ret == DB_NOTFOUND)
417 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
419 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
423 ssValue << CLIENT_VERSION;
425 Dbt datKey(&ssKey[0], ssKey.size());
426 Dbt datValue(&ssValue[0], ssValue.size());
427 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
434 bitdb.CloseDb(strFile);
435 if (pdbCopy->close(0))
442 Db dbA(&bitdb.dbenv, 0);
443 if (dbA.remove(strFile.c_str(), NULL, 0))
445 Db dbB(&bitdb.dbenv, 0);
446 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
450 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
460 void CDBEnv::Flush(bool fShutdown)
462 int64 nStart = GetTimeMillis();
463 // Flush log data to the actual data file
464 // on all files that are not in use
465 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
470 map<string, int>::iterator mi = mapFileUseCount.begin();
471 while (mi != mapFileUseCount.end())
473 string strFile = (*mi).first;
474 int nRefCount = (*mi).second;
475 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
478 // Move log data to the dat file
480 printf("%s checkpoint\n", strFile.c_str());
481 dbenv.txn_checkpoint(0, 0, 0);
482 if (!IsChainFile(strFile) || fDetachDB) {
483 printf("%s detach\n", strFile.c_str());
485 dbenv.lsn_reset(strFile.c_str(), 0);
487 printf("%s closed\n", strFile.c_str());
488 mapFileUseCount.erase(mi++);
493 printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
497 if (mapFileUseCount.empty())
499 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
515 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
519 return Read(make_pair(string("tx"), hash), txindex);
522 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
525 return Write(make_pair(string("tx"), hash), txindex);
528 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
533 uint256 hash = tx.GetHash();
534 CTxIndex txindex(pos, tx.vout.size());
535 return Write(make_pair(string("tx"), hash), txindex);
538 bool CTxDB::EraseTxIndex(const CTransaction& tx)
541 uint256 hash = tx.GetHash();
543 return Erase(make_pair(string("tx"), hash));
546 bool CTxDB::ContainsTx(uint256 hash)
549 return Exists(make_pair(string("tx"), hash));
552 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
556 if (!ReadTxIndex(hash, txindex))
558 return (tx.ReadFromDisk(txindex.pos));
561 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
564 return ReadDiskTx(hash, tx, txindex);
567 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
569 return ReadDiskTx(outpoint.hash, tx, txindex);
572 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
575 return ReadDiskTx(outpoint.hash, tx, txindex);
578 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
580 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
583 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
585 return Read(string("hashBestChain"), hashBestChain);
588 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
590 return Write(string("hashBestChain"), hashBestChain);
593 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
595 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
598 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
600 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
603 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
605 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
608 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
610 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
613 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
615 return Read(string("strCheckpointPubKey"), strPubKey);
618 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
620 return Write(string("strCheckpointPubKey"), strPubKey);
623 CBlockIndex static * InsertBlockIndex(uint256 hash)
629 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
630 if (mi != mapBlockIndex.end())
634 CBlockIndex* pindexNew = new CBlockIndex();
636 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
637 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
638 pindexNew->phashBlock = &((*mi).first);
643 bool CTxDB::LoadBlockIndex()
645 if (!LoadBlockIndexGuts())
648 if (fRequestShutdown)
651 // Calculate nChainTrust
652 vector<pair<int, CBlockIndex*> > vSortedByHeight;
653 vSortedByHeight.reserve(mapBlockIndex.size());
654 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
656 CBlockIndex* pindex = item.second;
657 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
659 sort(vSortedByHeight.begin(), vSortedByHeight.end());
660 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
662 CBlockIndex* pindex = item.second;
663 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
664 // ppcoin: calculate stake modifier checksum
665 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
666 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
667 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
670 // Load hashBestChain pointer to end of best chain
671 if (!ReadHashBestChain(hashBestChain))
673 if (pindexGenesisBlock == NULL)
675 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
677 if (!mapBlockIndex.count(hashBestChain))
678 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
679 pindexBest = mapBlockIndex[hashBestChain];
680 nBestHeight = pindexBest->nHeight;
681 nBestChainTrust = pindexBest->nChainTrust;
682 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
683 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
684 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
686 // ppcoin: load hashSyncCheckpoint
687 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
688 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
689 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
691 // Load bnBestInvalidTrust, OK if it doesn't exist
692 CBigNum bnBestInvalidTrust;
693 ReadBestInvalidTrust(bnBestInvalidTrust);
694 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
696 // Verify blocks in the best chain
697 int nCheckLevel = GetArg("-checklevel", 1);
698 int nCheckDepth = GetArg( "-checkblocks", 2500);
699 if (nCheckDepth == 0)
700 nCheckDepth = 1000000000; // suffices until the year 19000
701 if (nCheckDepth > nBestHeight)
702 nCheckDepth = nBestHeight;
703 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
704 CBlockIndex* pindexFork = NULL;
705 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
706 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
708 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
711 if (!block.ReadFromDisk(pindex))
712 return error("LoadBlockIndex() : block.ReadFromDisk failed");
713 // check level 1: verify block validity
714 // check level 7: verify block signature too
715 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
717 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
718 pindexFork = pindex->pprev;
720 // check level 2: verify transaction index validity
723 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
724 mapBlockPos[pos] = pindex;
725 BOOST_FOREACH(const CTransaction &tx, block.vtx)
727 uint256 hashTx = tx.GetHash();
729 if (ReadTxIndex(hashTx, txindex))
731 // check level 3: checker transaction hashes
732 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
734 // either an error or a duplicate transaction
735 CTransaction txFound;
736 if (!txFound.ReadFromDisk(txindex.pos))
738 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
739 pindexFork = pindex->pprev;
742 if (txFound.GetHash() != hashTx) // not a duplicate tx
744 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
745 pindexFork = pindex->pprev;
748 // check level 4: check whether spent txouts were spent within the main chain
749 unsigned int nOutput = 0;
752 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
756 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
757 if (!mapBlockPos.count(posFind))
759 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
760 pindexFork = pindex->pprev;
762 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
765 CTransaction txSpend;
766 if (!txSpend.ReadFromDisk(txpos))
768 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
769 pindexFork = pindex->pprev;
771 else if (!txSpend.CheckTransaction())
773 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
774 pindexFork = pindex->pprev;
779 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
780 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
784 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
785 pindexFork = pindex->pprev;
794 // check level 5: check whether all prevouts are marked spent
797 BOOST_FOREACH(const CTxIn &txin, tx.vin)
800 if (ReadTxIndex(txin.prevout.hash, txindex))
801 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
803 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
804 pindexFork = pindex->pprev;
811 if (pindexFork && !fRequestShutdown)
813 // Reorg back to the fork
814 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
816 if (!block.ReadFromDisk(pindexFork))
817 return error("LoadBlockIndex() : block.ReadFromDisk failed");
819 block.SetBestChain(txdb, pindexFork);
827 bool CTxDB::LoadBlockIndexGuts()
829 // Get database cursor
830 Dbc* pcursor = GetCursor();
834 // Load mapBlockIndex
835 unsigned int fFlags = DB_SET_RANGE;
839 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
840 if (fFlags == DB_SET_RANGE)
841 ssKey << make_pair(string("blockindex"), uint256(0));
842 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
843 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
845 if (ret == DB_NOTFOUND)
855 if (strType == "blockindex" && !fRequestShutdown)
857 CDiskBlockIndex diskindex;
858 ssValue >> diskindex;
860 // Construct block index object
861 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
862 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
863 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
864 pindexNew->nFile = diskindex.nFile;
865 pindexNew->nBlockPos = diskindex.nBlockPos;
866 pindexNew->nHeight = diskindex.nHeight;
867 pindexNew->nMint = diskindex.nMint;
868 pindexNew->nMoneySupply = diskindex.nMoneySupply;
869 pindexNew->nFlags = diskindex.nFlags;
870 pindexNew->nStakeModifier = diskindex.nStakeModifier;
871 pindexNew->prevoutStake = diskindex.prevoutStake;
872 pindexNew->nStakeTime = diskindex.nStakeTime;
873 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
874 pindexNew->nVersion = diskindex.nVersion;
875 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
876 pindexNew->nTime = diskindex.nTime;
877 pindexNew->nBits = diskindex.nBits;
878 pindexNew->nNonce = diskindex.nNonce;
880 // Watch for genesis block
881 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
882 pindexGenesisBlock = pindexNew;
884 if (!pindexNew->CheckIndex())
885 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
887 // ppcoin: build setStakeSeen
888 if (pindexNew->IsProofOfStake())
889 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
893 break; // if shutdown requested or finished loading block index
896 catch (std::exception &e) {
897 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
916 pathAddr = GetDataDir() / "peers.dat";
919 bool CAddrDB::Write(const CAddrMan& addr)
921 // Generate random temporary filename
922 unsigned short randv = 0;
923 RAND_bytes((unsigned char *)&randv, sizeof(randv));
924 std::string tmpfn = strprintf("peers.dat.%04x", randv);
926 // serialize addresses, checksum data up to that point, then append csum
927 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
928 ssPeers << FLATDATA(pchMessageStart);
930 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
933 // open temp output file, and associate with CAutoFile
934 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
935 FILE *file = fopen(pathTmp.string().c_str(), "wb");
936 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
938 return error("CAddrman::Write() : open failed");
940 // Write and commit header, data
944 catch (std::exception &e) {
945 return error("CAddrman::Write() : I/O error");
950 // replace existing peers.dat, if any, with new peers.dat.XXXX
951 if (!RenameOver(pathTmp, pathAddr))
952 return error("CAddrman::Write() : Rename-into-place failed");
957 bool CAddrDB::Read(CAddrMan& addr)
959 // open input file, and associate with CAutoFile
960 FILE *file = fopen(pathAddr.string().c_str(), "rb");
961 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
963 return error("CAddrman::Read() : open failed");
965 // use file size to size memory buffer
966 int fileSize = GetFilesize(filein);
967 int dataSize = fileSize - sizeof(uint256);
968 //Don't try to resize to a negative number if file is small
969 if ( dataSize < 0 ) dataSize = 0;
970 vector<unsigned char> vchData;
971 vchData.resize(dataSize);
974 // read data and checksum from file
976 filein.read((char *)&vchData[0], dataSize);
979 catch (std::exception &e) {
980 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
984 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
986 // verify stored checksum matches input data
987 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
988 if (hashIn != hashTmp)
989 return error("CAddrman::Read() : checksum mismatch; data corrupted");
991 unsigned char pchMsgTmp[4];
993 // de-serialize file header (pchMessageStart magic number) and
994 ssPeers >> FLATDATA(pchMsgTmp);
996 // verify the network matches ours
997 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
998 return error("CAddrman::Read() : invalid network magic number");
1000 // de-serialize address data into one CAddrMan object
1003 catch (std::exception &e) {
1004 return error("CAddrman::Read() : I/O error or stream data corrupted");