update to 0.4.1
[novacoin.git] / src / db.cpp
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.
5
6 #include "db.h"
7 #include "net.h"
8 #include "checkpoints.h"
9 #include "util.h"
10 #include "main.h"
11 #include "kernel.h"
12 #include <boost/version.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15
16 #ifndef WIN32
17 #include "sys/stat.h"
18 #endif
19
20 using namespace std;
21 using namespace boost;
22
23
24 unsigned int nWalletDBUpdated;
25
26
27
28 //
29 // CDB
30 //
31
32 CDBEnv bitdb;
33
34 void CDBEnv::EnvShutdown()
35 {
36     if (!fDbEnvInit)
37         return;
38
39     fDbEnvInit = false;
40     int ret = dbenv.close(0);
41     if (ret != 0)
42         printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
43     if (!fMockDb)
44         DbEnv(0).remove(strPath.c_str(), 0);
45 }
46
47 CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
48 {
49     fDbEnvInit = false;
50     fMockDb = false;
51 }
52
53 CDBEnv::~CDBEnv()
54 {
55     EnvShutdown();
56 }
57
58 void CDBEnv::Close()
59 {
60     EnvShutdown();
61 }
62
63 bool CDBEnv::Open(boost::filesystem::path pathEnv_)
64 {
65     if (fDbEnvInit)
66         return true;
67
68     if (fShutdown)
69         return false;
70
71     pathEnv = 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());
78
79     unsigned int nEnvFlags = 0;
80     if (GetBoolArg("-privdb", true))
81         nEnvFlags |= DB_PRIVATE;
82
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(),
95                      DB_CREATE     |
96                      DB_INIT_LOCK  |
97                      DB_INIT_LOG   |
98                      DB_INIT_MPOOL |
99                      DB_INIT_TXN   |
100                      DB_THREAD     |
101                      DB_RECOVER    |
102                      nEnvFlags,
103                      S_IRUSR | S_IWUSR);
104     if (ret != 0)
105         return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
106
107     fDbEnvInit = true;
108     fMockDb = false;
109     return true;
110 }
111
112 void CDBEnv::MakeMock()
113 {
114     if (fDbEnvInit)
115         throw runtime_error("CDBEnv::MakeMock(): already initialized");
116
117     if (fShutdown)
118         throw runtime_error("CDBEnv::MakeMock(): during shutdown");
119
120     printf("CDBEnv::MakeMock()\n");
121
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,
130                      DB_CREATE     |
131                      DB_INIT_LOCK  |
132                      DB_INIT_LOG   |
133                      DB_INIT_MPOOL |
134                      DB_INIT_TXN   |
135                      DB_THREAD     |
136                      DB_PRIVATE,
137                      S_IRUSR | S_IWUSR);
138     if (ret > 0)
139         throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
140
141     fDbEnvInit = true;
142     fMockDb = true;
143 }
144
145 CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
146 {
147     LOCK(cs_db);
148     assert(mapFileUseCount.count(strFile) == 0);
149
150     Db db(&dbenv, 0);
151     int result = db.verify(strFile.c_str(), NULL, NULL, 0);
152     if (result == 0)
153         return VERIFY_OK;
154     else if (recoverFunc == NULL)
155         return RECOVER_FAIL;
156
157     // Try to recover:
158     bool fRecovered = (*recoverFunc)(*this, strFile);
159     return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
160 }
161
162 bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
163                      std::vector<CDBEnv::KeyValPair >& vResult)
164 {
165     LOCK(cs_db);
166     assert(mapFileUseCount.count(strFile) == 0);
167
168     u_int32_t flags = DB_SALVAGE;
169     if (fAggressive) flags |= DB_AGGRESSIVE;
170
171     stringstream strDump;
172
173     Db db(&dbenv, 0);
174     int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
175     if (result != 0)
176     {
177         printf("ERROR: db salvage failed\n");
178         return false;
179     }
180
181     // Format of bdb dump is ascii lines:
182     // header lines...
183     // HEADER=END
184     // hexadecimal key
185     // hexadecimal value
186     // ... repeated
187     // DATA=END
188
189     string strLine;
190     while (!strDump.eof() && strLine != "HEADER=END")
191         getline(strDump, strLine); // Skip past header
192
193     std::string keyHex, valueHex;
194     while (!strDump.eof() && keyHex != "DATA=END")
195     {
196         getline(strDump, keyHex);
197         if (keyHex != "DATA_END")
198         {
199             getline(strDump, valueHex);
200             vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
201         }
202     }
203
204     return (result == 0);
205 }
206
207
208 void CDBEnv::CheckpointLSN(std::string strFile)
209 {
210     dbenv.txn_checkpoint(0, 0, 0);
211     if (fMockDb)
212         return;
213     dbenv.lsn_reset(strFile.c_str(), 0);
214 }
215
216
217 CDB::CDB(const char *pszFile, const char* pszMode) :
218     pdb(NULL), activeTxn(NULL)
219 {
220     int ret;
221     if (pszFile == NULL)
222         return;
223
224     fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
225     bool fCreate = strchr(pszMode, 'c');
226     unsigned int nFlags = DB_THREAD;
227     if (fCreate)
228         nFlags |= DB_CREATE;
229
230     {
231         LOCK(bitdb.cs_db);
232         if (!bitdb.Open(GetDataDir()))
233             throw runtime_error("env open failed");
234
235         strFile = pszFile;
236         ++bitdb.mapFileUseCount[strFile];
237         pdb = bitdb.mapDb[strFile];
238         if (pdb == NULL)
239         {
240             pdb = new Db(&bitdb.dbenv, 0);
241
242             bool fMockDb = bitdb.IsMock();
243             if (fMockDb)
244             {
245                 DbMpoolFile*mpf = pdb->get_mpf();
246                 ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
247                 if (ret != 0)
248                     throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
249             }
250
251             ret = pdb->open(NULL,      // Txn pointer
252                             fMockDb ? NULL : pszFile,   // Filename
253                             "main",    // Logical db name
254                             DB_BTREE,  // Database type
255                             nFlags,    // Flags
256                             0);
257
258             if (ret != 0)
259             {
260                 delete pdb;
261                 pdb = NULL;
262                 --bitdb.mapFileUseCount[strFile];
263                 strFile = "";
264                 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
265             }
266
267             if (fCreate && !Exists(string("version")))
268             {
269                 bool fTmp = fReadOnly;
270                 fReadOnly = false;
271                 WriteVersion(CLIENT_VERSION);
272                 fReadOnly = fTmp;
273             }
274
275             bitdb.mapDb[strFile] = pdb;
276         }
277     }
278 }
279
280 static bool IsChainFile(std::string strFile)
281 {
282     if (strFile == "blkindex.dat")
283         return true;
284
285     return false;
286 }
287
288 void CDB::Close()
289 {
290     if (!pdb)
291         return;
292     if (activeTxn)
293         activeTxn->abort();
294     activeTxn = NULL;
295     pdb = NULL;
296
297     // Flush database activity from memory pool to disk log
298     unsigned int nMinutes = 0;
299     if (fReadOnly)
300         nMinutes = 1;
301     if (IsChainFile(strFile))
302         nMinutes = 2;
303     if (IsChainFile(strFile) && IsInitialBlockDownload())
304         nMinutes = 5;
305
306     bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
307
308     {
309         LOCK(bitdb.cs_db);
310         --bitdb.mapFileUseCount[strFile];
311     }
312 }
313
314 void CDBEnv::CloseDb(const string& strFile)
315 {
316     {
317         LOCK(cs_db);
318         if (mapDb[strFile] != NULL)
319         {
320             // Close the database handle
321             Db* pdb = mapDb[strFile];
322             pdb->close(0);
323             delete pdb;
324             mapDb[strFile] = NULL;
325         }
326     }
327 }
328
329 bool CDBEnv::RemoveDb(const string& strFile)
330 {
331     this->CloseDb(strFile);
332
333     LOCK(cs_db);
334     int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
335     return (rc == 0);
336 }
337
338 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
339 {
340     while (!fShutdown)
341     {
342         {
343             LOCK(bitdb.cs_db);
344             if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
345             {
346                 // Flush log data to the dat file
347                 bitdb.CloseDb(strFile);
348                 bitdb.CheckpointLSN(strFile);
349                 bitdb.mapFileUseCount.erase(strFile);
350
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);
357
358                     int ret = pdbCopy->open(NULL,                 // Txn pointer
359                                             strFileRes.c_str(),   // Filename
360                                             "main",    // Logical db name
361                                             DB_BTREE,  // Database type
362                                             DB_CREATE,    // Flags
363                                             0);
364                     if (ret > 0)
365                     {
366                         printf("Cannot create database file %s\n", strFileRes.c_str());
367                         fSuccess = false;
368                     }
369
370                     Dbc* pcursor = db.GetCursor();
371                     if (pcursor)
372                         while (fSuccess)
373                         {
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)
378                             {
379                                 pcursor->close();
380                                 break;
381                             }
382                             else if (ret != 0)
383                             {
384                                 pcursor->close();
385                                 fSuccess = false;
386                                 break;
387                             }
388                             if (pszSkip &&
389                                 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
390                                 continue;
391                             if (strncmp(&ssKey[0], "\x07version", 8) == 0)
392                             {
393                                 // Update version:
394                                 ssValue.clear();
395                                 ssValue << CLIENT_VERSION;
396                             }
397                             Dbt datKey(&ssKey[0], ssKey.size());
398                             Dbt datValue(&ssValue[0], ssValue.size());
399                             int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
400                             if (ret2 > 0)
401                                 fSuccess = false;
402                         }
403                     if (fSuccess)
404                     {
405                         db.Close();
406                         bitdb.CloseDb(strFile);
407                         if (pdbCopy->close(0))
408                             fSuccess = false;
409                         delete pdbCopy;
410                     }
411                 }
412                 if (fSuccess)
413                 {
414                     Db dbA(&bitdb.dbenv, 0);
415                     if (dbA.remove(strFile.c_str(), NULL, 0))
416                         fSuccess = false;
417                     Db dbB(&bitdb.dbenv, 0);
418                     if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
419                         fSuccess = false;
420                 }
421                 if (!fSuccess)
422                     printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
423                 return fSuccess;
424             }
425         }
426         Sleep(100);
427     }
428     return false;
429 }
430
431
432 void CDBEnv::Flush(bool fShutdown)
433 {
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");
438     if (!fDbEnvInit)
439         return;
440     {
441         LOCK(cs_db);
442         map<string, int>::iterator mi = mapFileUseCount.begin();
443         while (mi != mapFileUseCount.end())
444         {
445             string strFile = (*mi).first;
446             int nRefCount = (*mi).second;
447             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
448             if (nRefCount == 0)
449             {
450                 // Move log data to the dat file
451                 CloseDb(strFile);
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());
456                     if (!fMockDb)
457                         dbenv.lsn_reset(strFile.c_str(), 0);
458                 }
459                 printf("%s closed\n", strFile.c_str());
460                 mapFileUseCount.erase(mi++);
461             }
462             else
463                 mi++;
464         }
465         printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
466         if (fShutdown)
467         {
468             char** listp;
469             if (mapFileUseCount.empty())
470             {
471                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
472                 Close();
473             }
474         }
475     }
476 }
477
478
479
480
481
482
483 //
484 // CTxDB
485 //
486
487 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
488 {
489     assert(!fClient);
490     txindex.SetNull();
491     return Read(make_pair(string("tx"), hash), txindex);
492 }
493
494 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
495 {
496     assert(!fClient);
497     return Write(make_pair(string("tx"), hash), txindex);
498 }
499
500 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
501 {
502     assert(!fClient);
503
504     // Add to tx index
505     uint256 hash = tx.GetHash();
506     CTxIndex txindex(pos, tx.vout.size());
507     return Write(make_pair(string("tx"), hash), txindex);
508 }
509
510 bool CTxDB::EraseTxIndex(const CTransaction& tx)
511 {
512     assert(!fClient);
513     uint256 hash = tx.GetHash();
514
515     return Erase(make_pair(string("tx"), hash));
516 }
517
518 bool CTxDB::ContainsTx(uint256 hash)
519 {
520     assert(!fClient);
521     return Exists(make_pair(string("tx"), hash));
522 }
523
524 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
525 {
526     assert(!fClient);
527     tx.SetNull();
528     if (!ReadTxIndex(hash, txindex))
529         return false;
530     return (tx.ReadFromDisk(txindex.pos));
531 }
532
533 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
534 {
535     CTxIndex txindex;
536     return ReadDiskTx(hash, tx, txindex);
537 }
538
539 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
540 {
541     return ReadDiskTx(outpoint.hash, tx, txindex);
542 }
543
544 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
545 {
546     CTxIndex txindex;
547     return ReadDiskTx(outpoint.hash, tx, txindex);
548 }
549
550 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
551 {
552     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
553 }
554
555 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
556 {
557     return Read(string("hashBestChain"), hashBestChain);
558 }
559
560 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
561 {
562     return Write(string("hashBestChain"), hashBestChain);
563 }
564
565 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
566 {
567     return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
568 }
569
570 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
571 {
572     return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
573 }
574
575 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
576 {
577     return Read(string("hashSyncCheckpoint"), hashCheckpoint);
578 }
579
580 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
581 {
582     return Write(string("hashSyncCheckpoint"), hashCheckpoint);
583 }
584
585 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
586 {
587     return Read(string("strCheckpointPubKey"), strPubKey);
588 }
589
590 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
591 {
592     return Write(string("strCheckpointPubKey"), strPubKey);
593 }
594
595 CBlockIndex static * InsertBlockIndex(uint256 hash)
596 {
597     if (hash == 0)
598         return NULL;
599
600     // Return existing
601     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
602     if (mi != mapBlockIndex.end())
603         return (*mi).second;
604
605     // Create new
606     CBlockIndex* pindexNew = new CBlockIndex();
607     if (!pindexNew)
608         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
609     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
610     pindexNew->phashBlock = &((*mi).first);
611
612     return pindexNew;
613 }
614
615 bool CTxDB::LoadBlockIndex()
616 {
617     if (!LoadBlockIndexGuts())
618         return false;
619
620     if (fRequestShutdown)
621         return true;
622
623     // Calculate bnChainTrust
624     vector<pair<int, CBlockIndex*> > vSortedByHeight;
625     vSortedByHeight.reserve(mapBlockIndex.size());
626     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
627     {
628         CBlockIndex* pindex = item.second;
629         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
630     }
631     sort(vSortedByHeight.begin(), vSortedByHeight.end());
632     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
633     {
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);
640     }
641
642     // Load hashBestChain pointer to end of best chain
643     if (!ReadHashBestChain(hashBestChain))
644     {
645         if (pindexGenesisBlock == NULL)
646             return true;
647         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
648     }
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());
657
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());
662
663     // Load bnBestInvalidTrust, OK if it doesn't exist
664     ReadBestInvalidTrust(bnBestInvalidTrust);
665
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)
677     {
678         if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
679             break;
680         CBlock block;
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())
685         {
686             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
687             pindexFork = pindex->pprev;
688         }
689         // check level 2: verify transaction index validity
690         if (nCheckLevel>1)
691         {
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)
695             {
696                 uint256 hashTx = tx.GetHash();
697                 CTxIndex txindex;
698                 if (ReadTxIndex(hashTx, txindex))
699                 {
700                     // check level 3: checker transaction hashes
701                     if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
702                     {
703                         // either an error or a duplicate transaction
704                         CTransaction txFound;
705                         if (!txFound.ReadFromDisk(txindex.pos))
706                         {
707                             printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
708                             pindexFork = pindex->pprev;
709                         }
710                         else
711                             if (txFound.GetHash() != hashTx) // not a duplicate tx
712                             {
713                                 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
714                                 pindexFork = pindex->pprev;
715                             }
716                     }
717                     // check level 4: check whether spent txouts were spent within the main chain
718                     unsigned int nOutput = 0;
719                     if (nCheckLevel>3)
720                     {
721                         BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
722                         {
723                             if (!txpos.IsNull())
724                             {
725                                 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
726                                 if (!mapBlockPos.count(posFind))
727                                 {
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;
730                                 }
731                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
732                                 if (nCheckLevel>5)
733                                 {
734                                     CTransaction txSpend;
735                                     if (!txSpend.ReadFromDisk(txpos))
736                                     {
737                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
738                                         pindexFork = pindex->pprev;
739                                     }
740                                     else if (!txSpend.CheckTransaction())
741                                     {
742                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
743                                         pindexFork = pindex->pprev;
744                                     }
745                                     else
746                                     {
747                                         bool fFound = false;
748                                         BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
749                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
750                                                 fFound = true;
751                                         if (!fFound)
752                                         {
753                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
754                                             pindexFork = pindex->pprev;
755                                         }
756                                     }
757                                 }
758                             }
759                             nOutput++;
760                         }
761                     }
762                 }
763                 // check level 5: check whether all prevouts are marked spent
764                 if (nCheckLevel>4)
765                 {
766                      BOOST_FOREACH(const CTxIn &txin, tx.vin)
767                      {
768                           CTxIndex txindex;
769                           if (ReadTxIndex(txin.prevout.hash, txindex))
770                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
771                               {
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;
774                               }
775                      }
776                 }
777             }
778         }
779     }
780     if (pindexFork && !fRequestShutdown)
781     {
782         // Reorg back to the fork
783         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
784         CBlock block;
785         if (!block.ReadFromDisk(pindexFork))
786             return error("LoadBlockIndex() : block.ReadFromDisk failed");
787         CTxDB txdb;
788         block.SetBestChain(txdb, pindexFork);
789     }
790
791     return true;
792 }
793
794
795
796 bool CTxDB::LoadBlockIndexGuts()
797 {
798     // Get database cursor
799     Dbc* pcursor = GetCursor();
800     if (!pcursor)
801         return false;
802
803     // Load mapBlockIndex
804     unsigned int fFlags = DB_SET_RANGE;
805     loop
806     {
807         // Read next record
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);
813         fFlags = DB_NEXT;
814         if (ret == DB_NOTFOUND)
815             break;
816         else if (ret != 0)
817             return false;
818
819         // Unserialize
820
821         try {
822         string strType;
823         ssKey >> strType;
824         if (strType == "blockindex" && !fRequestShutdown)
825         {
826             CDiskBlockIndex diskindex;
827             ssValue >> diskindex;
828
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;
848
849             // Watch for genesis block
850             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
851                 pindexGenesisBlock = pindexNew;
852
853             if (!pindexNew->CheckIndex())
854                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
855
856             // ppcoin: build setStakeSeen
857             if (pindexNew->IsProofOfStake())
858                 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
859         }
860         else
861         {
862             break; // if shutdown requested or finished loading block index
863         }
864         }    // try
865         catch (std::exception &e) {
866             return error("%s() : deserialize error", __PRETTY_FUNCTION__);
867         }
868     }
869     pcursor->close();
870
871     return true;
872 }
873
874
875
876
877
878 //
879 // CAddrDB
880 //
881
882
883 CAddrDB::CAddrDB()
884 {
885     pathAddr = GetDataDir() / "peers.dat";
886 }
887
888 bool CAddrDB::Write(const CAddrMan& addr)
889 {
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);
894
895     // serialize addresses, checksum data up to that point, then append csum
896     CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
897     ssPeers << FLATDATA(pchMessageStart);
898     ssPeers << addr;
899     uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
900     ssPeers << hash;
901
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);
906     if (!fileout)
907         return error("CAddrman::Write() : open failed");
908
909     // Write and commit header, data
910     try {
911         fileout << ssPeers;
912     }
913     catch (std::exception &e) {
914         return error("CAddrman::Write() : I/O error");
915     }
916     FileCommit(fileout);
917     fileout.fclose();
918
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");
922
923     return true;
924 }
925
926 bool CAddrDB::Read(CAddrMan& addr)
927 {
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);
931     if (!filein)
932         return error("CAddrman::Read() : open failed");
933
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);
939     uint256 hashIn;
940
941     // read data and checksum from file
942     try {
943         filein.read((char *)&vchData[0], dataSize);
944         filein >> hashIn;
945     }
946     catch (std::exception &e) {
947         return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
948     }
949     filein.fclose();
950
951     CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
952
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");
957
958     unsigned char pchMsgTmp[4];
959     try {
960         // de-serialize file header (pchMessageStart magic number) and
961         ssPeers >> FLATDATA(pchMsgTmp);
962
963         // verify the network matches ours
964         if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
965             return error("CAddrman::Read() : invalid network magic number");
966
967         // de-serialize address data into one CAddrMan object
968         ssPeers >> addr;
969     }
970     catch (std::exception &e) {
971         return error("CAddrman::Read() : I/O error or stream data corrupted");
972     }
973
974     return true;
975 }
976