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 <boost/version.hpp>
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);
88 dbenv.set_lk_max_locks(10000);
89 dbenv.set_lk_max_objects(10000);
90 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
91 dbenv.set_flags(DB_AUTO_COMMIT, 1);
92 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
93 // dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
94 int ret = dbenv.open(strPath.c_str(),
105 return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
112 void CDBEnv::MakeMock()
115 throw runtime_error("CDBEnv::MakeMock(): already initialized");
118 throw runtime_error("CDBEnv::MakeMock(): during shutdown");
120 printf("CDBEnv::MakeMock()\n");
122 dbenv.set_cachesize(1, 0, 1);
123 dbenv.set_lg_bsize(10485760*4);
124 dbenv.set_lg_max(10485760);
125 dbenv.set_lk_max_locks(10000);
126 dbenv.set_lk_max_objects(10000);
127 dbenv.set_flags(DB_AUTO_COMMIT, 1);
128 // dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
129 int ret = dbenv.open(NULL,
139 throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
145 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
148 assert(mapFileUseCount.count(strFile) == 0);
151 int result = db.verify(strFile.c_str(), NULL, NULL, 0);
154 else if (recoverFunc == NULL)
158 bool fRecovered = (*recoverFunc)(*this, strFile);
159 return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
162 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
163 std::vector<CDBEnv::KeyValPair >& vResult)
166 assert(mapFileUseCount.count(strFile) == 0);
168 u_int32_t flags = DB_SALVAGE;
169 if (fAggressive) flags |= DB_AGGRESSIVE;
171 stringstream strDump;
174 int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
177 printf("ERROR: db salvage failed\n");
181 // Format of bdb dump is ascii lines:
190 while (!strDump.eof() && strLine != "HEADER=END")
191 getline(strDump, strLine); // Skip past header
193 std::string keyHex, valueHex;
194 while (!strDump.eof() && keyHex != "DATA=END")
196 getline(strDump, keyHex);
197 if (keyHex != "DATA_END")
199 getline(strDump, valueHex);
200 vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
204 return (result == 0);
208 void CDBEnv::CheckpointLSN(std::string strFile)
210 dbenv.txn_checkpoint(0, 0, 0);
213 dbenv.lsn_reset(strFile.c_str(), 0);
217 CDB::CDB(const char *pszFile, const char* pszMode) :
218 pdb(NULL), activeTxn(NULL)
224 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
225 bool fCreate = strchr(pszMode, 'c');
226 unsigned int nFlags = DB_THREAD;
232 if (!bitdb.Open(GetDataDir()))
233 throw runtime_error("env open failed");
236 ++bitdb.mapFileUseCount[strFile];
237 pdb = bitdb.mapDb[strFile];
240 pdb = new Db(&bitdb.dbenv, 0);
242 bool fMockDb = bitdb.IsMock();
245 DbMpoolFile*mpf = pdb->get_mpf();
246 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
248 throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
251 ret = pdb->open(NULL, // Txn pointer
252 fMockDb ? NULL : pszFile, // Filename
253 "main", // Logical db name
254 DB_BTREE, // Database type
262 --bitdb.mapFileUseCount[strFile];
264 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
267 if (fCreate && !Exists(string("version")))
269 bool fTmp = fReadOnly;
271 WriteVersion(CLIENT_VERSION);
275 bitdb.mapDb[strFile] = pdb;
280 static bool IsChainFile(std::string strFile)
282 if (strFile == "blkindex.dat")
297 // Flush database activity from memory pool to disk log
298 unsigned int nMinutes = 0;
301 if (IsChainFile(strFile))
303 if (IsChainFile(strFile) && IsInitialBlockDownload())
306 bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
310 --bitdb.mapFileUseCount[strFile];
314 void CDBEnv::CloseDb(const string& strFile)
318 if (mapDb[strFile] != NULL)
320 // Close the database handle
321 Db* pdb = mapDb[strFile];
324 mapDb[strFile] = NULL;
329 bool CDBEnv::RemoveDb(const string& strFile)
331 this->CloseDb(strFile);
334 int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
338 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
344 if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
346 // Flush log data to the dat file
347 bitdb.CloseDb(strFile);
348 bitdb.CheckpointLSN(strFile);
349 bitdb.mapFileUseCount.erase(strFile);
351 bool fSuccess = true;
352 printf("Rewriting %s...\n", strFile.c_str());
353 string strFileRes = strFile + ".rewrite";
354 { // surround usage of db with extra {}
355 CDB db(strFile.c_str(), "r");
356 Db* pdbCopy = new Db(&bitdb.dbenv, 0);
358 int ret = pdbCopy->open(NULL, // Txn pointer
359 strFileRes.c_str(), // Filename
360 "main", // Logical db name
361 DB_BTREE, // Database type
366 printf("Cannot create database file %s\n", strFileRes.c_str());
370 Dbc* pcursor = db.GetCursor();
374 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
375 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
376 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
377 if (ret == DB_NOTFOUND)
389 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
391 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
395 ssValue << CLIENT_VERSION;
397 Dbt datKey(&ssKey[0], ssKey.size());
398 Dbt datValue(&ssValue[0], ssValue.size());
399 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
406 bitdb.CloseDb(strFile);
407 if (pdbCopy->close(0))
414 Db dbA(&bitdb.dbenv, 0);
415 if (dbA.remove(strFile.c_str(), NULL, 0))
417 Db dbB(&bitdb.dbenv, 0);
418 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
422 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
432 void CDBEnv::Flush(bool fShutdown)
434 int64 nStart = GetTimeMillis();
435 // Flush log data to the actual data file
436 // on all files that are not in use
437 printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
442 map<string, int>::iterator mi = mapFileUseCount.begin();
443 while (mi != mapFileUseCount.end())
445 string strFile = (*mi).first;
446 int nRefCount = (*mi).second;
447 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
450 // Move log data to the dat file
452 printf("%s checkpoint\n", strFile.c_str());
453 dbenv.txn_checkpoint(0, 0, 0);
454 if (!IsChainFile(strFile) || fDetachDB) {
455 printf("%s detach\n", strFile.c_str());
457 dbenv.lsn_reset(strFile.c_str(), 0);
459 printf("%s closed\n", strFile.c_str());
460 mapFileUseCount.erase(mi++);
465 printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
469 if (mapFileUseCount.empty())
471 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
487 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
491 return Read(make_pair(string("tx"), hash), txindex);
494 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
497 return Write(make_pair(string("tx"), hash), txindex);
500 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
505 uint256 hash = tx.GetHash();
506 CTxIndex txindex(pos, tx.vout.size());
507 return Write(make_pair(string("tx"), hash), txindex);
510 bool CTxDB::EraseTxIndex(const CTransaction& tx)
513 uint256 hash = tx.GetHash();
515 return Erase(make_pair(string("tx"), hash));
518 bool CTxDB::ContainsTx(uint256 hash)
521 return Exists(make_pair(string("tx"), hash));
524 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
528 if (!ReadTxIndex(hash, txindex))
530 return (tx.ReadFromDisk(txindex.pos));
533 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
536 return ReadDiskTx(hash, tx, txindex);
539 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
541 return ReadDiskTx(outpoint.hash, tx, txindex);
544 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
547 return ReadDiskTx(outpoint.hash, tx, txindex);
550 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
552 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
555 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
557 return Read(string("hashBestChain"), hashBestChain);
560 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
562 return Write(string("hashBestChain"), hashBestChain);
565 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
567 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
570 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
572 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
575 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
577 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
580 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
582 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
585 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
587 return Read(string("strCheckpointPubKey"), strPubKey);
590 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
592 return Write(string("strCheckpointPubKey"), strPubKey);
595 CBlockIndex static * InsertBlockIndex(uint256 hash)
601 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
602 if (mi != mapBlockIndex.end())
606 CBlockIndex* pindexNew = new CBlockIndex();
608 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
609 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
610 pindexNew->phashBlock = &((*mi).first);
615 bool CTxDB::LoadBlockIndex()
617 if (!LoadBlockIndexGuts())
620 if (fRequestShutdown)
623 // Calculate bnChainTrust
624 vector<pair<int, CBlockIndex*> > vSortedByHeight;
625 vSortedByHeight.reserve(mapBlockIndex.size());
626 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
628 CBlockIndex* pindex = item.second;
629 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
631 sort(vSortedByHeight.begin(), vSortedByHeight.end());
632 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
634 CBlockIndex* pindex = item.second;
635 pindex->bnChainTrust = (pindex->pprev ? pindex->pprev->bnChainTrust : 0) + pindex->GetBlockTrust();
636 // ppcoin: calculate stake modifier checksum
637 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
638 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
639 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
642 // Load hashBestChain pointer to end of best chain
643 if (!ReadHashBestChain(hashBestChain))
645 if (pindexGenesisBlock == NULL)
647 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
649 if (!mapBlockIndex.count(hashBestChain))
650 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
651 pindexBest = mapBlockIndex[hashBestChain];
652 nBestHeight = pindexBest->nHeight;
653 bnBestChainTrust = pindexBest->bnChainTrust;
654 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
655 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
656 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
658 // ppcoin: load hashSyncCheckpoint
659 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
660 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
661 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
663 // Load bnBestInvalidTrust, OK if it doesn't exist
664 ReadBestInvalidTrust(bnBestInvalidTrust);
666 // Verify blocks in the best chain
667 int nCheckLevel = GetArg("-checklevel", 1);
668 int nCheckDepth = GetArg( "-checkblocks", 2500);
669 if (nCheckDepth == 0)
670 nCheckDepth = 1000000000; // suffices until the year 19000
671 if (nCheckDepth > nBestHeight)
672 nCheckDepth = nBestHeight;
673 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
674 CBlockIndex* pindexFork = NULL;
675 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
676 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
678 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
681 if (!block.ReadFromDisk(pindex))
682 return error("LoadBlockIndex() : block.ReadFromDisk failed");
683 // check level 1: verify block validity
684 if (nCheckLevel>0 && !block.CheckBlock())
686 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
687 pindexFork = pindex->pprev;
689 // check level 2: verify transaction index validity
692 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
693 mapBlockPos[pos] = pindex;
694 BOOST_FOREACH(const CTransaction &tx, block.vtx)
696 uint256 hashTx = tx.GetHash();
698 if (ReadTxIndex(hashTx, txindex))
700 // check level 3: checker transaction hashes
701 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
703 // either an error or a duplicate transaction
704 CTransaction txFound;
705 if (!txFound.ReadFromDisk(txindex.pos))
707 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
708 pindexFork = pindex->pprev;
711 if (txFound.GetHash() != hashTx) // not a duplicate tx
713 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
714 pindexFork = pindex->pprev;
717 // check level 4: check whether spent txouts were spent within the main chain
718 unsigned int nOutput = 0;
721 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
725 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
726 if (!mapBlockPos.count(posFind))
728 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
729 pindexFork = pindex->pprev;
731 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
734 CTransaction txSpend;
735 if (!txSpend.ReadFromDisk(txpos))
737 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
738 pindexFork = pindex->pprev;
740 else if (!txSpend.CheckTransaction())
742 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
743 pindexFork = pindex->pprev;
748 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
749 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
753 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
754 pindexFork = pindex->pprev;
763 // check level 5: check whether all prevouts are marked spent
766 BOOST_FOREACH(const CTxIn &txin, tx.vin)
769 if (ReadTxIndex(txin.prevout.hash, txindex))
770 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
772 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
773 pindexFork = pindex->pprev;
780 if (pindexFork && !fRequestShutdown)
782 // Reorg back to the fork
783 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
785 if (!block.ReadFromDisk(pindexFork))
786 return error("LoadBlockIndex() : block.ReadFromDisk failed");
788 block.SetBestChain(txdb, pindexFork);
796 bool CTxDB::LoadBlockIndexGuts()
798 // Get database cursor
799 Dbc* pcursor = GetCursor();
803 // Load mapBlockIndex
804 unsigned int fFlags = DB_SET_RANGE;
808 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
809 if (fFlags == DB_SET_RANGE)
810 ssKey << make_pair(string("blockindex"), uint256(0));
811 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
812 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
814 if (ret == DB_NOTFOUND)
824 if (strType == "blockindex" && !fRequestShutdown)
826 CDiskBlockIndex diskindex;
827 ssValue >> diskindex;
829 // Construct block index object
830 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
831 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
832 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
833 pindexNew->nFile = diskindex.nFile;
834 pindexNew->nBlockPos = diskindex.nBlockPos;
835 pindexNew->nHeight = diskindex.nHeight;
836 pindexNew->nMint = diskindex.nMint;
837 pindexNew->nMoneySupply = diskindex.nMoneySupply;
838 pindexNew->nFlags = diskindex.nFlags;
839 pindexNew->nStakeModifier = diskindex.nStakeModifier;
840 pindexNew->prevoutStake = diskindex.prevoutStake;
841 pindexNew->nStakeTime = diskindex.nStakeTime;
842 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
843 pindexNew->nVersion = diskindex.nVersion;
844 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
845 pindexNew->nTime = diskindex.nTime;
846 pindexNew->nBits = diskindex.nBits;
847 pindexNew->nNonce = diskindex.nNonce;
849 // Watch for genesis block
850 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
851 pindexGenesisBlock = pindexNew;
853 if (!pindexNew->CheckIndex())
854 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
856 // ppcoin: build setStakeSeen
857 if (pindexNew->IsProofOfStake())
858 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
862 break; // if shutdown requested or finished loading block index
865 catch (std::exception &e) {
866 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
885 pathAddr = GetDataDir() / "peers.dat";
888 bool CAddrDB::Write(const CAddrMan& addr)
890 // Generate random temporary filename
891 unsigned short randv = 0;
892 RAND_bytes((unsigned char *)&randv, sizeof(randv));
893 std::string tmpfn = strprintf("peers.dat.%04x", randv);
895 // serialize addresses, checksum data up to that point, then append csum
896 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
897 ssPeers << FLATDATA(pchMessageStart);
899 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
902 // open temp output file, and associate with CAutoFile
903 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
904 FILE *file = fopen(pathTmp.string().c_str(), "wb");
905 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
907 return error("CAddrman::Write() : open failed");
909 // Write and commit header, data
913 catch (std::exception &e) {
914 return error("CAddrman::Write() : I/O error");
919 // replace existing peers.dat, if any, with new peers.dat.XXXX
920 if (!RenameOver(pathTmp, pathAddr))
921 return error("CAddrman::Write() : Rename-into-place failed");
926 bool CAddrDB::Read(CAddrMan& addr)
928 // open input file, and associate with CAutoFile
929 FILE *file = fopen(pathAddr.string().c_str(), "rb");
930 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
932 return error("CAddrman::Read() : open failed");
934 // use file size to size memory buffer
935 int fileSize = GetFilesize(filein);
936 int dataSize = fileSize - sizeof(uint256);
937 vector<unsigned char> vchData;
938 vchData.resize(dataSize);
941 // read data and checksum from file
943 filein.read((char *)&vchData[0], dataSize);
946 catch (std::exception &e) {
947 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
951 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
953 // verify stored checksum matches input data
954 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
955 if (hashIn != hashTmp)
956 return error("CAddrman::Read() : checksum mismatch; data corrupted");
958 unsigned char pchMsgTmp[4];
960 // de-serialize file header (pchMessageStart magic number) and
961 ssPeers >> FLATDATA(pchMsgTmp);
963 // verify the network matches ours
964 if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
965 return error("CAddrman::Read() : invalid network magic number");
967 // de-serialize address data into one CAddrMan object
970 catch (std::exception &e) {
971 return error("CAddrman::Read() : I/O error or stream data corrupted");