Merge pull request #1114 from sipa/lesssync
[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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "db.h"
7 #include "util.h"
8 #include "main.h"
9 #include <boost/version.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12
13 #ifndef WIN32
14 #include "sys/stat.h"
15 #endif
16
17 using namespace std;
18 using namespace boost;
19
20
21 unsigned int nWalletDBUpdated;
22
23
24
25 //
26 // CDB
27 //
28
29 CCriticalSection cs_db;
30 static bool fDbEnvInit = false;
31 DbEnv dbenv(0);
32 map<string, int> mapFileUseCount;
33 static map<string, Db*> mapDb;
34
35 static void EnvShutdown()
36 {
37     if (!fDbEnvInit)
38         return;
39
40     fDbEnvInit = false;
41     try
42     {
43         dbenv.close(0);
44     }
45     catch (const DbException& e)
46     {
47         printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
48     }
49     DbEnv(0).remove(GetDataDir().string().c_str(), 0);
50 }
51
52 class CDBInit
53 {
54 public:
55     CDBInit()
56     {
57     }
58     ~CDBInit()
59     {
60         EnvShutdown();
61     }
62 }
63 instance_of_cdbinit;
64
65
66 CDB::CDB(const char *pszFile, const char* pszMode) : pdb(NULL)
67 {
68     int ret;
69     if (pszFile == NULL)
70         return;
71
72     fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
73     bool fCreate = strchr(pszMode, 'c');
74     unsigned int nFlags = DB_THREAD;
75     if (fCreate)
76         nFlags |= DB_CREATE;
77
78     {
79         LOCK(cs_db);
80         if (!fDbEnvInit)
81         {
82             if (fShutdown)
83                 return;
84             filesystem::path pathDataDir = GetDataDir();
85             filesystem::path pathLogDir = pathDataDir / "database";
86             filesystem::create_directory(pathLogDir);
87             filesystem::path pathErrorFile = pathDataDir / "db.log";
88             printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
89
90             int nDbCache = GetArg("-dbcache", 25);
91             dbenv.set_lg_dir(pathLogDir.string().c_str());
92             dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
93             dbenv.set_lg_bsize(1048576);
94             dbenv.set_lg_max(10485760);
95             dbenv.set_lk_max_locks(10000);
96             dbenv.set_lk_max_objects(10000);
97             dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
98             dbenv.set_flags(DB_AUTO_COMMIT, 1);
99             dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
100             ret = dbenv.open(pathDataDir.string().c_str(),
101                              DB_CREATE     |
102                              DB_INIT_LOCK  |
103                              DB_INIT_LOG   |
104                              DB_INIT_MPOOL |
105                              DB_INIT_TXN   |
106                              DB_THREAD     |
107                              DB_RECOVER,
108                              S_IRUSR | S_IWUSR);
109             if (ret > 0)
110                 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
111             fDbEnvInit = true;
112         }
113
114         strFile = pszFile;
115         ++mapFileUseCount[strFile];
116         pdb = mapDb[strFile];
117         if (pdb == NULL)
118         {
119             pdb = new Db(&dbenv, 0);
120
121             ret = pdb->open(NULL,      // Txn pointer
122                             pszFile,   // Filename
123                             "main",    // Logical db name
124                             DB_BTREE,  // Database type
125                             nFlags,    // Flags
126                             0);
127
128             if (ret > 0)
129             {
130                 delete pdb;
131                 pdb = NULL;
132                 {
133                      LOCK(cs_db);
134                     --mapFileUseCount[strFile];
135                 }
136                 strFile = "";
137                 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
138             }
139
140             if (fCreate && !Exists(string("version")))
141             {
142                 bool fTmp = fReadOnly;
143                 fReadOnly = false;
144                 WriteVersion(CLIENT_VERSION);
145                 fReadOnly = fTmp;
146             }
147
148             mapDb[strFile] = pdb;
149         }
150     }
151 }
152
153 void CDB::Close()
154 {
155     if (!pdb)
156         return;
157     if (!vTxn.empty())
158         vTxn.front()->abort();
159     vTxn.clear();
160     pdb = NULL;
161
162     // Flush database activity from memory pool to disk log
163     unsigned int nMinutes = 0;
164     if (fReadOnly)
165         nMinutes = 1;
166     if (strFile == "addr.dat")
167         nMinutes = 2;
168     if (strFile == "blkindex.dat")
169         nMinutes = 2;
170     if (strFile == "blkindex.dat" && IsInitialBlockDownload())
171         nMinutes = 5;
172
173     dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
174
175     {
176         LOCK(cs_db);
177         --mapFileUseCount[strFile];
178     }
179 }
180
181 void CloseDb(const string& strFile)
182 {
183     {
184         LOCK(cs_db);
185         if (mapDb[strFile] != NULL)
186         {
187             // Close the database handle
188             Db* pdb = mapDb[strFile];
189             pdb->close(0);
190             delete pdb;
191             mapDb[strFile] = NULL;
192         }
193     }
194 }
195
196 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
197 {
198     while (!fShutdown)
199     {
200         {
201             LOCK(cs_db);
202             if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
203             {
204                 // Flush log data to the dat file
205                 CloseDb(strFile);
206                 dbenv.txn_checkpoint(0, 0, 0);
207                 dbenv.lsn_reset(strFile.c_str(), 0);
208                 mapFileUseCount.erase(strFile);
209
210                 bool fSuccess = true;
211                 printf("Rewriting %s...\n", strFile.c_str());
212                 string strFileRes = strFile + ".rewrite";
213                 { // surround usage of db with extra {}
214                     CDB db(strFile.c_str(), "r");
215                     Db* pdbCopy = new Db(&dbenv, 0);
216     
217                     int ret = pdbCopy->open(NULL,                 // Txn pointer
218                                             strFileRes.c_str(),   // Filename
219                                             "main",    // Logical db name
220                                             DB_BTREE,  // Database type
221                                             DB_CREATE,    // Flags
222                                             0);
223                     if (ret > 0)
224                     {
225                         printf("Cannot create database file %s\n", strFileRes.c_str());
226                         fSuccess = false;
227                     }
228     
229                     Dbc* pcursor = db.GetCursor();
230                     if (pcursor)
231                         while (fSuccess)
232                         {
233                             CDataStream ssKey(SER_DISK, CLIENT_VERSION);
234                             CDataStream ssValue(SER_DISK, CLIENT_VERSION);
235                             int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
236                             if (ret == DB_NOTFOUND)
237                             {
238                                 pcursor->close();
239                                 break;
240                             }
241                             else if (ret != 0)
242                             {
243                                 pcursor->close();
244                                 fSuccess = false;
245                                 break;
246                             }
247                             if (pszSkip &&
248                                 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
249                                 continue;
250                             if (strncmp(&ssKey[0], "\x07version", 8) == 0)
251                             {
252                                 // Update version:
253                                 ssValue.clear();
254                                 ssValue << CLIENT_VERSION;
255                             }
256                             Dbt datKey(&ssKey[0], ssKey.size());
257                             Dbt datValue(&ssValue[0], ssValue.size());
258                             int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
259                             if (ret2 > 0)
260                                 fSuccess = false;
261                         }
262                     if (fSuccess)
263                     {
264                         db.Close();
265                         CloseDb(strFile);
266                         if (pdbCopy->close(0))
267                             fSuccess = false;
268                         delete pdbCopy;
269                     }
270                 }
271                 if (fSuccess)
272                 {
273                     Db dbA(&dbenv, 0);
274                     if (dbA.remove(strFile.c_str(), NULL, 0))
275                         fSuccess = false;
276                     Db dbB(&dbenv, 0);
277                     if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
278                         fSuccess = false;
279                 }
280                 if (!fSuccess)
281                     printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
282                 return fSuccess;
283             }
284         }
285         Sleep(100);
286     }
287     return false;
288 }
289
290
291 void DBFlush(bool fShutdown)
292 {
293     // Flush log data to the actual data file
294     //  on all files that are not in use
295     printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
296     if (!fDbEnvInit)
297         return;
298     {
299         LOCK(cs_db);
300         map<string, int>::iterator mi = mapFileUseCount.begin();
301         while (mi != mapFileUseCount.end())
302         {
303             string strFile = (*mi).first;
304             int nRefCount = (*mi).second;
305             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
306             if (nRefCount == 0)
307             {
308                 // Move log data to the dat file
309                 CloseDb(strFile);
310                 dbenv.txn_checkpoint(0, 0, 0);
311                 printf("%s flush\n", strFile.c_str());
312                 dbenv.lsn_reset(strFile.c_str(), 0);
313                 mapFileUseCount.erase(mi++);
314             }
315             else
316                 mi++;
317         }
318         if (fShutdown)
319         {
320             char** listp;
321             if (mapFileUseCount.empty())
322             {
323                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
324                 EnvShutdown();
325             }
326         }
327     }
328 }
329
330
331
332
333
334
335 //
336 // CTxDB
337 //
338
339 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
340 {
341     assert(!fClient);
342     txindex.SetNull();
343     return Read(make_pair(string("tx"), hash), txindex);
344 }
345
346 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
347 {
348     assert(!fClient);
349     return Write(make_pair(string("tx"), hash), txindex);
350 }
351
352 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
353 {
354     assert(!fClient);
355
356     // Add to tx index
357     uint256 hash = tx.GetHash();
358     CTxIndex txindex(pos, tx.vout.size());
359     return Write(make_pair(string("tx"), hash), txindex);
360 }
361
362 bool CTxDB::EraseTxIndex(const CTransaction& tx)
363 {
364     assert(!fClient);
365     uint256 hash = tx.GetHash();
366
367     return Erase(make_pair(string("tx"), hash));
368 }
369
370 bool CTxDB::ContainsTx(uint256 hash)
371 {
372     assert(!fClient);
373     return Exists(make_pair(string("tx"), hash));
374 }
375
376 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
377 {
378     assert(!fClient);
379     vtx.clear();
380
381     // Get cursor
382     Dbc* pcursor = GetCursor();
383     if (!pcursor)
384         return false;
385
386     unsigned int fFlags = DB_SET_RANGE;
387     loop
388     {
389         // Read next record
390         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
391         if (fFlags == DB_SET_RANGE)
392             ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
393         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
394         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
395         fFlags = DB_NEXT;
396         if (ret == DB_NOTFOUND)
397             break;
398         else if (ret != 0)
399         {
400             pcursor->close();
401             return false;
402         }
403
404         // Unserialize
405         string strType;
406         uint160 hashItem;
407         CDiskTxPos pos;
408         ssKey >> strType >> hashItem >> pos;
409         int nItemHeight;
410         ssValue >> nItemHeight;
411
412         // Read transaction
413         if (strType != "owner" || hashItem != hash160)
414             break;
415         if (nItemHeight >= nMinHeight)
416         {
417             vtx.resize(vtx.size()+1);
418             if (!vtx.back().ReadFromDisk(pos))
419             {
420                 pcursor->close();
421                 return false;
422             }
423         }
424     }
425
426     pcursor->close();
427     return true;
428 }
429
430 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
431 {
432     assert(!fClient);
433     tx.SetNull();
434     if (!ReadTxIndex(hash, txindex))
435         return false;
436     return (tx.ReadFromDisk(txindex.pos));
437 }
438
439 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
440 {
441     CTxIndex txindex;
442     return ReadDiskTx(hash, tx, txindex);
443 }
444
445 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
446 {
447     return ReadDiskTx(outpoint.hash, tx, txindex);
448 }
449
450 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
451 {
452     CTxIndex txindex;
453     return ReadDiskTx(outpoint.hash, tx, txindex);
454 }
455
456 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
457 {
458     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
459 }
460
461 bool CTxDB::EraseBlockIndex(uint256 hash)
462 {
463     return Erase(make_pair(string("blockindex"), hash));
464 }
465
466 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
467 {
468     return Read(string("hashBestChain"), hashBestChain);
469 }
470
471 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
472 {
473     return Write(string("hashBestChain"), hashBestChain);
474 }
475
476 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
477 {
478     return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
479 }
480
481 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
482 {
483     return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
484 }
485
486 CBlockIndex static * InsertBlockIndex(uint256 hash)
487 {
488     if (hash == 0)
489         return NULL;
490
491     // Return existing
492     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
493     if (mi != mapBlockIndex.end())
494         return (*mi).second;
495
496     // Create new
497     CBlockIndex* pindexNew = new CBlockIndex();
498     if (!pindexNew)
499         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
500     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
501     pindexNew->phashBlock = &((*mi).first);
502
503     return pindexNew;
504 }
505
506 bool CTxDB::LoadBlockIndex()
507 {
508     // Get database cursor
509     Dbc* pcursor = GetCursor();
510     if (!pcursor)
511         return false;
512
513     // Load mapBlockIndex
514     unsigned int fFlags = DB_SET_RANGE;
515     loop
516     {
517         // Read next record
518         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
519         if (fFlags == DB_SET_RANGE)
520             ssKey << make_pair(string("blockindex"), uint256(0));
521         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
522         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
523         fFlags = DB_NEXT;
524         if (ret == DB_NOTFOUND)
525             break;
526         else if (ret != 0)
527             return false;
528
529         // Unserialize
530         string strType;
531         ssKey >> strType;
532         if (strType == "blockindex")
533         {
534             CDiskBlockIndex diskindex;
535             ssValue >> diskindex;
536
537             // Construct block index object
538             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
539             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
540             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
541             pindexNew->nFile          = diskindex.nFile;
542             pindexNew->nBlockPos      = diskindex.nBlockPos;
543             pindexNew->nHeight        = diskindex.nHeight;
544             pindexNew->nVersion       = diskindex.nVersion;
545             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
546             pindexNew->nTime          = diskindex.nTime;
547             pindexNew->nBits          = diskindex.nBits;
548             pindexNew->nNonce         = diskindex.nNonce;
549
550             // Watch for genesis block
551             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
552                 pindexGenesisBlock = pindexNew;
553
554             if (!pindexNew->CheckIndex())
555                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
556         }
557         else
558         {
559             break;
560         }
561     }
562     pcursor->close();
563
564     // Calculate bnChainWork
565     vector<pair<int, CBlockIndex*> > vSortedByHeight;
566     vSortedByHeight.reserve(mapBlockIndex.size());
567     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
568     {
569         CBlockIndex* pindex = item.second;
570         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
571     }
572     sort(vSortedByHeight.begin(), vSortedByHeight.end());
573     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
574     {
575         CBlockIndex* pindex = item.second;
576         pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
577     }
578
579     // Load hashBestChain pointer to end of best chain
580     if (!ReadHashBestChain(hashBestChain))
581     {
582         if (pindexGenesisBlock == NULL)
583             return true;
584         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
585     }
586     if (!mapBlockIndex.count(hashBestChain))
587         return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
588     pindexBest = mapBlockIndex[hashBestChain];
589     nBestHeight = pindexBest->nHeight;
590     bnBestChainWork = pindexBest->bnChainWork;
591     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
592
593     // Load bnBestInvalidWork, OK if it doesn't exist
594     ReadBestInvalidWork(bnBestInvalidWork);
595
596     // Verify blocks in the best chain
597     int nCheckLevel = GetArg("-checklevel", 1);
598     int nCheckDepth = GetArg( "-checkblocks", 2500);
599     if (nCheckDepth == 0)
600         nCheckDepth = 1000000000; // suffices until the year 19000
601     if (nCheckDepth > nBestHeight)
602         nCheckDepth = nBestHeight;
603     printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
604     CBlockIndex* pindexFork = NULL;
605     map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
606     for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
607     {
608         if (pindex->nHeight < nBestHeight-nCheckDepth)
609             break;
610         CBlock block;
611         if (!block.ReadFromDisk(pindex))
612             return error("LoadBlockIndex() : block.ReadFromDisk failed");
613         // check level 1: verify block validity
614         if (nCheckLevel>0 && !block.CheckBlock())
615         {
616             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
617             pindexFork = pindex->pprev;
618         }
619         // check level 2: verify transaction index validity
620         if (nCheckLevel>1)
621         {
622             pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
623             mapBlockPos[pos] = pindex;
624             BOOST_FOREACH(const CTransaction &tx, block.vtx)
625             {
626                 uint256 hashTx = tx.GetHash();
627                 CTxIndex txindex;
628                 if (ReadTxIndex(hashTx, txindex))
629                 {
630                     // check level 3: checker transaction hashes
631                     if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
632                     {
633                         // either an error or a duplicate transaction
634                         CTransaction txFound;
635                         if (!txFound.ReadFromDisk(txindex.pos))
636                         {
637                             printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
638                             pindexFork = pindex->pprev;
639                         }
640                         else
641                             if (txFound.GetHash() != hashTx) // not a duplicate tx
642                             {
643                                 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
644                                 pindexFork = pindex->pprev;
645                             }
646                     }
647                     // check level 4: check whether spent txouts were spent within the main chain
648                     int nOutput = 0;
649                     if (nCheckLevel>3)
650                     {
651                         BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
652                         {
653                             if (!txpos.IsNull())
654                             {
655                                 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
656                                 if (!mapBlockPos.count(posFind))
657                                 {
658                                     printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
659                                     pindexFork = pindex->pprev;
660                                 }
661                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
662                                 if (nCheckLevel>5)
663                                 {
664                                     CTransaction txSpend;
665                                     if (!txSpend.ReadFromDisk(txpos))
666                                     {
667                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
668                                         pindexFork = pindex->pprev;
669                                     }
670                                     else if (!txSpend.CheckTransaction())
671                                     {
672                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
673                                         pindexFork = pindex->pprev;
674                                     }
675                                     else
676                                     {
677                                         bool fFound = false;
678                                         BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
679                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
680                                                 fFound = true;
681                                         if (!fFound)
682                                         {
683                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
684                                             pindexFork = pindex->pprev;
685                                         }
686                                     }
687                                 }
688                             }
689                             nOutput++;
690                         }
691                     }
692                 }
693                 // check level 5: check whether all prevouts are marked spent
694                 if (nCheckLevel>4)
695                 {
696                      BOOST_FOREACH(const CTxIn &txin, tx.vin)
697                      {
698                           CTxIndex txindex;
699                           if (ReadTxIndex(txin.prevout.hash, txindex))
700                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
701                               {
702                                   printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
703                                   pindexFork = pindex->pprev;
704                               }
705                      }
706                 }
707             }
708         }
709     }
710     if (pindexFork)
711     {
712         // Reorg back to the fork
713         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
714         CBlock block;
715         if (!block.ReadFromDisk(pindexFork))
716             return error("LoadBlockIndex() : block.ReadFromDisk failed");
717         CTxDB txdb;
718         block.SetBestChain(txdb, pindexFork);
719     }
720
721     return true;
722 }
723
724
725
726
727
728 //
729 // CAddrDB
730 //
731
732 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
733 {
734     return Write(string("addrman"), addrman);
735 }
736
737 bool CAddrDB::LoadAddresses()
738 {
739     if (Read(string("addrman"), addrman))
740     {
741         printf("Loaded %i addresses\n", addrman.size());
742         return true;
743     }
744     
745     // Read pre-0.6 addr records
746
747     vector<CAddress> vAddr;
748     vector<vector<unsigned char> > vDelete;
749
750     // Get cursor
751     Dbc* pcursor = GetCursor();
752     if (!pcursor)
753         return false;
754
755     loop
756     {
757         // Read next record
758         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
759         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
760         int ret = ReadAtCursor(pcursor, ssKey, ssValue);
761         if (ret == DB_NOTFOUND)
762             break;
763         else if (ret != 0)
764             return false;
765
766         // Unserialize
767         string strType;
768         ssKey >> strType;
769         if (strType == "addr")
770         {
771             CAddress addr;
772             ssValue >> addr;
773             vAddr.push_back(addr);
774         }
775     }
776     pcursor->close();
777
778     addrman.Add(vAddr, CNetAddr("0.0.0.0"));
779     printf("Loaded %i addresses\n", addrman.size());
780
781     // Note: old records left; we ran into hangs-on-startup
782     // bugs for some users who (we think) were running after
783     // an unclean shutdown.
784
785     return true;
786 }
787
788 bool LoadAddresses()
789 {
790     return CAddrDB("cr+").LoadAddresses();
791 }
792
793