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 #ifdef DB_LOG_AUTO_REMOVE
98 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
100 int ret = dbenv.open(strPath.c_str(),
111 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
116 // Check that the number of locks is sufficient (to prevent chain fork possibility, read http://bitcoin.org/may15 for more info)
118 if (!dbenv.get_lk_max_locks(&nMaxLocks))
120 int nBlocks, nDeepReorg;
121 std::string strMessage;
123 nBlocks = nMaxLocks / 48768;
124 nDeepReorg = (nBlocks - 1) / 2;
126 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);
130 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);
132 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);
134 strMiscWarning = strMessage;
135 printf("*** %s\n", strMessage.c_str());
142 void CDBEnv::MakeMock()
145 throw runtime_error("CDBEnv::MakeMock(): already initialized");
148 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
150 printf("CDBEnv::MakeMock()\n");
152 dbenv.set_cachesize(1, 0, 1);
153 dbenv.set_lg_bsize(10485760*4);
154 dbenv.set_lg_max(10485760);
155 dbenv.set_lk_max_locks(10000);
156 dbenv.set_lk_max_objects(10000);
157 dbenv.set_flags(DB_AUTO_COMMIT, 1);
158 #ifdef DB_LOG_IN_MEMORY
159 dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
161 int ret = dbenv.open(NULL,
171 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
177 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
180 assert(mapFileUseCount.count(strFile) == 0);
183 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
186 else if (recoverFunc == NULL)
190 bool fRecovered = (*recoverFunc)(*this, strFile);
191 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
194 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
195 std::vector<CDBEnv::KeyValPair >& vResult)
198 assert(mapFileUseCount.count(strFile) == 0);
200 u_int32_t flags = DB_SALVAGE;
201 if (fAggressive) flags |= DB_AGGRESSIVE;
203 stringstream strDump;
206 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
209 printf("ERROR: db salvage failed\n");
213 // Format of bdb dump is ascii lines:
222 while (!strDump.eof() && strLine != "HEADER=END")
223 getline(strDump, strLine); // Skip past header
225 std::string keyHex, valueHex;
226 while (!strDump.eof() && keyHex != "DATA=END")
228 getline(strDump, keyHex);
229 if (keyHex != "DATA_END")
231 getline(strDump, valueHex);
232 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
236 return (result == 0);
240 void CDBEnv::CheckpointLSN(std::string strFile)
242 dbenv.txn_checkpoint(0, 0, 0);
245 dbenv.lsn_reset(strFile.c_str(), 0);
249 CDB::CDB(const char *pszFile, const char* pszMode) :
250 pdb(NULL), activeTxn(NULL)
256 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
257 bool fCreate = strchr(pszMode, 'c');
258 unsigned int nFlags = DB_THREAD;
264 if (!bitdb.Open(GetDataDir()))
265 throw runtime_error("env open failed");
268 ++bitdb.mapFileUseCount[strFile];
269 pdb = bitdb.mapDb[strFile];
272 pdb = new Db(&bitdb.dbenv, 0);
274 bool fMockDb = bitdb.IsMock();
277 DbMpoolFile*mpf = pdb->get_mpf();
278 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
280 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
283 ret = pdb->open(NULL, // Txn pointer
284 fMockDb ? NULL : pszFile, // Filename
285 "main", // Logical db name
286 DB_BTREE, // Database type
294 --bitdb.mapFileUseCount[strFile];
296 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
299 if (fCreate && !Exists(string("version")))
301 bool fTmp = fReadOnly;
303 WriteVersion(CLIENT_VERSION);
307 bitdb.mapDb[strFile] = pdb;
312 static bool IsChainFile(std::string strFile)
314 if (strFile == "blkindex.dat")
329 // Flush database activity from memory pool to disk log
330 unsigned int nMinutes = 0;
333 if (IsChainFile(strFile))
335 if (IsChainFile(strFile) && IsInitialBlockDownload())
338 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
342 --bitdb.mapFileUseCount[strFile];
346 void CDBEnv::CloseDb(const string& strFile)
350 if (mapDb[strFile] != NULL)
352 // Close the database handle
353 Db* pdb = mapDb[strFile];
356 mapDb[strFile] = NULL;
361 bool CDBEnv::RemoveDb(const string& strFile)
363 this->CloseDb(strFile);
366 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
370 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
376 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
378 // Flush log data to the dat file
379 bitdb.CloseDb(strFile);
380 bitdb.CheckpointLSN(strFile);
381 bitdb.mapFileUseCount.erase(strFile);
383 bool fSuccess = true;
384 printf("Rewriting %s...\n", strFile.c_str());
385 string strFileRes = strFile + ".rewrite";
386 { // surround usage of db with extra {}
387 CDB db(strFile.c_str(), "r");
388 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
390 int ret = pdbCopy->open(NULL, // Txn pointer
391 strFileRes.c_str(), // Filename
392 "main", // Logical db name
393 DB_BTREE, // Database type
398 printf("Cannot create database file %s\n", strFileRes.c_str());
402 Dbc* pcursor = db.GetCursor();
406 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
407 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
408 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
409 if (ret == DB_NOTFOUND)
421 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
423 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
427 ssValue << CLIENT_VERSION;
429 Dbt datKey(&ssKey[0], ssKey.size());
430 Dbt datValue(&ssValue[0], ssValue.size());
431 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
438 bitdb.CloseDb(strFile);
439 if (pdbCopy->close(0))
446 Db dbA(&bitdb.dbenv, 0);
447 if (dbA.remove(strFile.c_str(), NULL, 0))
449 Db dbB(&bitdb.dbenv, 0);
450 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
454 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
464 void CDBEnv::Flush(bool fShutdown)
466 int64 nStart = GetTimeMillis();
467 // Flush log data to the actual data file
468 // on all files that are not in use
469 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
474 map<string, int>::iterator mi = mapFileUseCount.begin();
475 while (mi != mapFileUseCount.end())
477 string strFile = (*mi).first;
478 int nRefCount = (*mi).second;
479 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
482 // Move log data to the dat file
484 printf("%s checkpoint\n", strFile.c_str());
485 dbenv.txn_checkpoint(0, 0, 0);
486 if (!IsChainFile(strFile) || fDetachDB) {
487 printf("%s detach\n", strFile.c_str());
489 dbenv.lsn_reset(strFile.c_str(), 0);
491 printf("%s closed\n", strFile.c_str());
492 mapFileUseCount.erase(mi++);
497 printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
501 if (mapFileUseCount.empty())
503 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
519 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
523 return Read(make_pair(string("tx"), hash), txindex);
526 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
529 return Write(make_pair(string("tx"), hash), txindex);
532 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
537 uint256 hash = tx.GetHash();
538 CTxIndex txindex(pos, tx.vout.size());
539 return Write(make_pair(string("tx"), hash), txindex);
542 bool CTxDB::EraseTxIndex(const CTransaction& tx)
545 uint256 hash = tx.GetHash();
547 return Erase(make_pair(string("tx"), hash));
550 bool CTxDB::ContainsTx(uint256 hash)
553 return Exists(make_pair(string("tx"), hash));
556 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
560 if (!ReadTxIndex(hash, txindex))
562 return (tx.ReadFromDisk(txindex.pos));
565 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
568 return ReadDiskTx(hash, tx, txindex);
571 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
573 return ReadDiskTx(outpoint.hash, tx, txindex);
576 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
579 return ReadDiskTx(outpoint.hash, tx, txindex);
582 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
584 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
587 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
589 return Read(string("hashBestChain"), hashBestChain);
592 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
594 return Write(string("hashBestChain"), hashBestChain);
597 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
599 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
602 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
604 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
607 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
609 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
612 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
614 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
617 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
619 return Read(string("strCheckpointPubKey"), strPubKey);
622 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
624 return Write(string("strCheckpointPubKey"), strPubKey);
627 CBlockIndex static * InsertBlockIndex(uint256 hash)
633 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
634 if (mi != mapBlockIndex.end())
638 CBlockIndex* pindexNew = new CBlockIndex();
640 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
641 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
642 pindexNew->phashBlock = &((*mi).first);
647 bool CTxDB::LoadBlockIndex()
649 if (!LoadBlockIndexGuts())
652 if (fRequestShutdown)
655 // Calculate nChainTrust
656 vector<pair<int, CBlockIndex*> > vSortedByHeight;
657 vSortedByHeight.reserve(mapBlockIndex.size());
658 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
660 CBlockIndex* pindex = item.second;
661 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
663 sort(vSortedByHeight.begin(), vSortedByHeight.end());
664 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
666 CBlockIndex* pindex = item.second;
667 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
668 // ppcoin: calculate stake modifier checksum
669 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
670 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
671 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
674 // Load hashBestChain pointer to end of best chain
675 if (!ReadHashBestChain(hashBestChain))
677 if (pindexGenesisBlock == NULL)
679 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
681 if (!mapBlockIndex.count(hashBestChain))
682 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
683 pindexBest = mapBlockIndex[hashBestChain];
684 nBestHeight = pindexBest->nHeight;
685 nBestChainTrust = pindexBest->nChainTrust;
686 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
687 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
688 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
690 // ppcoin: load hashSyncCheckpoint
691 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
692 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
693 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
695 // Load bnBestInvalidTrust, OK if it doesn't exist
696 CBigNum bnBestInvalidTrust;
697 ReadBestInvalidTrust(bnBestInvalidTrust);
698 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
700 // Verify blocks in the best chain
701 int nCheckLevel = GetArg("-checklevel", 1);
702 int nCheckDepth = GetArg( "-checkblocks", 2500);
703 if (nCheckDepth == 0)
704 nCheckDepth = 1000000000; // suffices until the year 19000
705 if (nCheckDepth > nBestHeight)
706 nCheckDepth = nBestHeight;
707 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
708 CBlockIndex* pindexFork = NULL;
709 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
710 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
712 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
715 if (!block.ReadFromDisk(pindex))
716 return error("LoadBlockIndex() : block.ReadFromDisk failed");
717 // check level 1: verify block validity
718 // check level 7: verify block signature too
719 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
721 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
722 pindexFork = pindex->pprev;
724 // check level 2: verify transaction index validity
727 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
728 mapBlockPos[pos] = pindex;
729 BOOST_FOREACH(const CTransaction &tx, block.vtx)
731 uint256 hashTx = tx.GetHash();
733 if (ReadTxIndex(hashTx, txindex))
735 // check level 3: checker transaction hashes
736 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
738 // either an error or a duplicate transaction
739 CTransaction txFound;
740 if (!txFound.ReadFromDisk(txindex.pos))
742 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
743 pindexFork = pindex->pprev;
746 if (txFound.GetHash() != hashTx) // not a duplicate tx
748 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
749 pindexFork = pindex->pprev;
752 // check level 4: check whether spent txouts were spent within the main chain
753 unsigned int nOutput = 0;
756 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
760 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
761 if (!mapBlockPos.count(posFind))
763 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
764 pindexFork = pindex->pprev;
766 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
769 CTransaction txSpend;
770 if (!txSpend.ReadFromDisk(txpos))
772 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
773 pindexFork = pindex->pprev;
775 else if (!txSpend.CheckTransaction())
777 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
778 pindexFork = pindex->pprev;
783 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
784 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
788 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
789 pindexFork = pindex->pprev;
798 // check level 5: check whether all prevouts are marked spent
801 BOOST_FOREACH(const CTxIn &txin, tx.vin)
804 if (ReadTxIndex(txin.prevout.hash, txindex))
805 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
807 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
808 pindexFork = pindex->pprev;
815 if (pindexFork && !fRequestShutdown)
817 // Reorg back to the fork
818 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
820 if (!block.ReadFromDisk(pindexFork))
821 return error("LoadBlockIndex() : block.ReadFromDisk failed");
823 block.SetBestChain(txdb, pindexFork);
831 bool CTxDB::LoadBlockIndexGuts()
833 // Get database cursor
834 Dbc* pcursor = GetCursor();
838 // Load mapBlockIndex
839 unsigned int fFlags = DB_SET_RANGE;
843 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
844 if (fFlags == DB_SET_RANGE)
845 ssKey << make_pair(string("blockindex"), uint256(0));
846 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
847 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
849 if (ret == DB_NOTFOUND)
859 if (strType == "blockindex" && !fRequestShutdown)
861 CDiskBlockIndex diskindex;
862 ssValue >> diskindex;
864 // Construct block index object
865 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
866 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
867 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
868 pindexNew->nFile = diskindex.nFile;
869 pindexNew->nBlockPos = diskindex.nBlockPos;
870 pindexNew->nHeight = diskindex.nHeight;
871 pindexNew->nMint = diskindex.nMint;
872 pindexNew->nMoneySupply = diskindex.nMoneySupply;
873 pindexNew->nFlags = diskindex.nFlags;
874 pindexNew->nStakeModifier = diskindex.nStakeModifier;
875 pindexNew->prevoutStake = diskindex.prevoutStake;
876 pindexNew->nStakeTime = diskindex.nStakeTime;
877 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
878 pindexNew->nVersion = diskindex.nVersion;
879 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
880 pindexNew->nTime = diskindex.nTime;
881 pindexNew->nBits = diskindex.nBits;
882 pindexNew->nNonce = diskindex.nNonce;
884 // Watch for genesis block
885 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
886 pindexGenesisBlock = pindexNew;
888 if (!pindexNew->CheckIndex())
889 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
891 // ppcoin: build setStakeSeen
892 if (pindexNew->IsProofOfStake())
893 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
897 break; // if shutdown requested or finished loading block index
900 catch (std::exception &e) {
901 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
920 pathAddr = GetDataDir() / "peers.dat";
923 bool CAddrDB::Write(const CAddrMan& addr)
925 // Generate random temporary filename
926 unsigned short randv = 0;
927 RAND_bytes((unsigned char *)&randv, sizeof(randv));
928 std::string tmpfn = strprintf("peers.dat.%04x", randv);
930 // serialize addresses, checksum data up to that point, then append csum
931 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
932 ssPeers << FLATDATA(pchMessageStart);
934 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
937 // open temp output file, and associate with CAutoFile
938 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
939 FILE *file = fopen(pathTmp.string().c_str(), "wb");
940 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
942 return error("CAddrman::Write() : open failed");
944 // Write and commit header, data
948 catch (std::exception &e) {
949 return error("CAddrman::Write() : I/O error");
954 // replace existing peers.dat, if any, with new peers.dat.XXXX
955 if (!RenameOver(pathTmp, pathAddr))
956 return error("CAddrman::Write() : Rename-into-place failed");
961 bool CAddrDB::Read(CAddrMan& addr)
963 // open input file, and associate with CAutoFile
964 FILE *file = fopen(pathAddr.string().c_str(), "rb");
965 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
967 return error("CAddrman::Read() : open failed");
969 // use file size to size memory buffer
970 int fileSize = GetFilesize(filein);
971 int dataSize = fileSize - sizeof(uint256);
972 //Don't try to resize to a negative number if file is small
973 if ( dataSize < 0 ) dataSize = 0;
974 vector<unsigned char> vchData;
975 vchData.resize(dataSize);
978 // read data and checksum from file
980 filein.read((char *)&vchData[0], dataSize);
983 catch (std::exception &e) {
984 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
988 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
990 // verify stored checksum matches input data
991 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
992 if (hashIn != hashTmp)
993 return error("CAddrman::Read() : checksum mismatch; data corrupted");
995 unsigned char pchMsgTmp[4];
997 // de-serialize file header (pchMessageStart magic number) and
998 ssPeers >> FLATDATA(pchMsgTmp);
1000 // verify the network matches ours
1001 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
1002 return error("CAddrman::Read() : invalid network magic number");
1004 // de-serialize address data into one CAddrMan object
1007 catch (std::exception &e) {
1008 return error("CAddrman::Read() : I/O error or stream data corrupted");