Further reduce header dependencies
[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" && IsInitialBlockDownload())
169         nMinutes = 5;
170
171     dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
172
173     {
174         LOCK(cs_db);
175         --mapFileUseCount[strFile];
176     }
177 }
178
179 void CloseDb(const string& strFile)
180 {
181     {
182         LOCK(cs_db);
183         if (mapDb[strFile] != NULL)
184         {
185             // Close the database handle
186             Db* pdb = mapDb[strFile];
187             pdb->close(0);
188             delete pdb;
189             mapDb[strFile] = NULL;
190         }
191     }
192 }
193
194 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
195 {
196     while (!fShutdown)
197     {
198         {
199             LOCK(cs_db);
200             if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
201             {
202                 // Flush log data to the dat file
203                 CloseDb(strFile);
204                 dbenv.txn_checkpoint(0, 0, 0);
205                 dbenv.lsn_reset(strFile.c_str(), 0);
206                 mapFileUseCount.erase(strFile);
207
208                 bool fSuccess = true;
209                 printf("Rewriting %s...\n", strFile.c_str());
210                 string strFileRes = strFile + ".rewrite";
211                 { // surround usage of db with extra {}
212                     CDB db(strFile.c_str(), "r");
213                     Db* pdbCopy = new Db(&dbenv, 0);
214     
215                     int ret = pdbCopy->open(NULL,                 // Txn pointer
216                                             strFileRes.c_str(),   // Filename
217                                             "main",    // Logical db name
218                                             DB_BTREE,  // Database type
219                                             DB_CREATE,    // Flags
220                                             0);
221                     if (ret > 0)
222                     {
223                         printf("Cannot create database file %s\n", strFileRes.c_str());
224                         fSuccess = false;
225                     }
226     
227                     Dbc* pcursor = db.GetCursor();
228                     if (pcursor)
229                         while (fSuccess)
230                         {
231                             CDataStream ssKey(SER_DISK, CLIENT_VERSION);
232                             CDataStream ssValue(SER_DISK, CLIENT_VERSION);
233                             int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
234                             if (ret == DB_NOTFOUND)
235                             {
236                                 pcursor->close();
237                                 break;
238                             }
239                             else if (ret != 0)
240                             {
241                                 pcursor->close();
242                                 fSuccess = false;
243                                 break;
244                             }
245                             if (pszSkip &&
246                                 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
247                                 continue;
248                             if (strncmp(&ssKey[0], "\x07version", 8) == 0)
249                             {
250                                 // Update version:
251                                 ssValue.clear();
252                                 ssValue << CLIENT_VERSION;
253                             }
254                             Dbt datKey(&ssKey[0], ssKey.size());
255                             Dbt datValue(&ssValue[0], ssValue.size());
256                             int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
257                             if (ret2 > 0)
258                                 fSuccess = false;
259                         }
260                     if (fSuccess)
261                     {
262                         db.Close();
263                         CloseDb(strFile);
264                         if (pdbCopy->close(0))
265                             fSuccess = false;
266                         delete pdbCopy;
267                     }
268                 }
269                 if (fSuccess)
270                 {
271                     Db dbA(&dbenv, 0);
272                     if (dbA.remove(strFile.c_str(), NULL, 0))
273                         fSuccess = false;
274                     Db dbB(&dbenv, 0);
275                     if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
276                         fSuccess = false;
277                 }
278                 if (!fSuccess)
279                     printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
280                 return fSuccess;
281             }
282         }
283         Sleep(100);
284     }
285     return false;
286 }
287
288
289 void DBFlush(bool fShutdown)
290 {
291     // Flush log data to the actual data file
292     //  on all files that are not in use
293     printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
294     if (!fDbEnvInit)
295         return;
296     {
297         LOCK(cs_db);
298         map<string, int>::iterator mi = mapFileUseCount.begin();
299         while (mi != mapFileUseCount.end())
300         {
301             string strFile = (*mi).first;
302             int nRefCount = (*mi).second;
303             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
304             if (nRefCount == 0)
305             {
306                 // Move log data to the dat file
307                 CloseDb(strFile);
308                 dbenv.txn_checkpoint(0, 0, 0);
309                 printf("%s flush\n", strFile.c_str());
310                 dbenv.lsn_reset(strFile.c_str(), 0);
311                 mapFileUseCount.erase(mi++);
312             }
313             else
314                 mi++;
315         }
316         if (fShutdown)
317         {
318             char** listp;
319             if (mapFileUseCount.empty())
320             {
321                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
322                 EnvShutdown();
323             }
324         }
325     }
326 }
327
328
329
330
331
332
333 //
334 // CTxDB
335 //
336
337 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
338 {
339     assert(!fClient);
340     txindex.SetNull();
341     return Read(make_pair(string("tx"), hash), txindex);
342 }
343
344 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
345 {
346     assert(!fClient);
347     return Write(make_pair(string("tx"), hash), txindex);
348 }
349
350 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
351 {
352     assert(!fClient);
353
354     // Add to tx index
355     uint256 hash = tx.GetHash();
356     CTxIndex txindex(pos, tx.vout.size());
357     return Write(make_pair(string("tx"), hash), txindex);
358 }
359
360 bool CTxDB::EraseTxIndex(const CTransaction& tx)
361 {
362     assert(!fClient);
363     uint256 hash = tx.GetHash();
364
365     return Erase(make_pair(string("tx"), hash));
366 }
367
368 bool CTxDB::ContainsTx(uint256 hash)
369 {
370     assert(!fClient);
371     return Exists(make_pair(string("tx"), hash));
372 }
373
374 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
375 {
376     assert(!fClient);
377     vtx.clear();
378
379     // Get cursor
380     Dbc* pcursor = GetCursor();
381     if (!pcursor)
382         return false;
383
384     unsigned int fFlags = DB_SET_RANGE;
385     loop
386     {
387         // Read next record
388         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
389         if (fFlags == DB_SET_RANGE)
390             ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
391         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
392         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
393         fFlags = DB_NEXT;
394         if (ret == DB_NOTFOUND)
395             break;
396         else if (ret != 0)
397         {
398             pcursor->close();
399             return false;
400         }
401
402         // Unserialize
403         string strType;
404         uint160 hashItem;
405         CDiskTxPos pos;
406         ssKey >> strType >> hashItem >> pos;
407         int nItemHeight;
408         ssValue >> nItemHeight;
409
410         // Read transaction
411         if (strType != "owner" || hashItem != hash160)
412             break;
413         if (nItemHeight >= nMinHeight)
414         {
415             vtx.resize(vtx.size()+1);
416             if (!vtx.back().ReadFromDisk(pos))
417             {
418                 pcursor->close();
419                 return false;
420             }
421         }
422     }
423
424     pcursor->close();
425     return true;
426 }
427
428 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
429 {
430     assert(!fClient);
431     tx.SetNull();
432     if (!ReadTxIndex(hash, txindex))
433         return false;
434     return (tx.ReadFromDisk(txindex.pos));
435 }
436
437 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
438 {
439     CTxIndex txindex;
440     return ReadDiskTx(hash, tx, txindex);
441 }
442
443 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
444 {
445     return ReadDiskTx(outpoint.hash, tx, txindex);
446 }
447
448 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
449 {
450     CTxIndex txindex;
451     return ReadDiskTx(outpoint.hash, tx, txindex);
452 }
453
454 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
455 {
456     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
457 }
458
459 bool CTxDB::EraseBlockIndex(uint256 hash)
460 {
461     return Erase(make_pair(string("blockindex"), hash));
462 }
463
464 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
465 {
466     return Read(string("hashBestChain"), hashBestChain);
467 }
468
469 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
470 {
471     return Write(string("hashBestChain"), hashBestChain);
472 }
473
474 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
475 {
476     return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
477 }
478
479 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
480 {
481     return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
482 }
483
484 CBlockIndex static * InsertBlockIndex(uint256 hash)
485 {
486     if (hash == 0)
487         return NULL;
488
489     // Return existing
490     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
491     if (mi != mapBlockIndex.end())
492         return (*mi).second;
493
494     // Create new
495     CBlockIndex* pindexNew = new CBlockIndex();
496     if (!pindexNew)
497         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
498     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
499     pindexNew->phashBlock = &((*mi).first);
500
501     return pindexNew;
502 }
503
504 bool CTxDB::LoadBlockIndex()
505 {
506     // Get database cursor
507     Dbc* pcursor = GetCursor();
508     if (!pcursor)
509         return false;
510
511     // Load mapBlockIndex
512     unsigned int fFlags = DB_SET_RANGE;
513     loop
514     {
515         // Read next record
516         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
517         if (fFlags == DB_SET_RANGE)
518             ssKey << make_pair(string("blockindex"), uint256(0));
519         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
520         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
521         fFlags = DB_NEXT;
522         if (ret == DB_NOTFOUND)
523             break;
524         else if (ret != 0)
525             return false;
526
527         // Unserialize
528         string strType;
529         ssKey >> strType;
530         if (strType == "blockindex")
531         {
532             CDiskBlockIndex diskindex;
533             ssValue >> diskindex;
534
535             // Construct block index object
536             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
537             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
538             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
539             pindexNew->nFile          = diskindex.nFile;
540             pindexNew->nBlockPos      = diskindex.nBlockPos;
541             pindexNew->nHeight        = diskindex.nHeight;
542             pindexNew->nVersion       = diskindex.nVersion;
543             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
544             pindexNew->nTime          = diskindex.nTime;
545             pindexNew->nBits          = diskindex.nBits;
546             pindexNew->nNonce         = diskindex.nNonce;
547
548             // Watch for genesis block
549             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
550                 pindexGenesisBlock = pindexNew;
551
552             if (!pindexNew->CheckIndex())
553                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
554         }
555         else
556         {
557             break;
558         }
559     }
560     pcursor->close();
561
562     // Calculate bnChainWork
563     vector<pair<int, CBlockIndex*> > vSortedByHeight;
564     vSortedByHeight.reserve(mapBlockIndex.size());
565     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
566     {
567         CBlockIndex* pindex = item.second;
568         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
569     }
570     sort(vSortedByHeight.begin(), vSortedByHeight.end());
571     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
572     {
573         CBlockIndex* pindex = item.second;
574         pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
575     }
576
577     // Load hashBestChain pointer to end of best chain
578     if (!ReadHashBestChain(hashBestChain))
579     {
580         if (pindexGenesisBlock == NULL)
581             return true;
582         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
583     }
584     if (!mapBlockIndex.count(hashBestChain))
585         return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
586     pindexBest = mapBlockIndex[hashBestChain];
587     nBestHeight = pindexBest->nHeight;
588     bnBestChainWork = pindexBest->bnChainWork;
589     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
590
591     // Load bnBestInvalidWork, OK if it doesn't exist
592     ReadBestInvalidWork(bnBestInvalidWork);
593
594     // Verify blocks in the best chain
595     int nCheckLevel = GetArg("-checklevel", 1);
596     int nCheckDepth = GetArg( "-checkblocks", 2500);
597     if (nCheckDepth == 0)
598         nCheckDepth = 1000000000; // suffices until the year 19000
599     if (nCheckDepth > nBestHeight)
600         nCheckDepth = nBestHeight;
601     printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
602     CBlockIndex* pindexFork = NULL;
603     map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
604     for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
605     {
606         if (pindex->nHeight < nBestHeight-nCheckDepth)
607             break;
608         CBlock block;
609         if (!block.ReadFromDisk(pindex))
610             return error("LoadBlockIndex() : block.ReadFromDisk failed");
611         // check level 1: verify block validity
612         if (nCheckLevel>0 && !block.CheckBlock())
613         {
614             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
615             pindexFork = pindex->pprev;
616         }
617         // check level 2: verify transaction index validity
618         if (nCheckLevel>1)
619         {
620             pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
621             mapBlockPos[pos] = pindex;
622             BOOST_FOREACH(const CTransaction &tx, block.vtx)
623             {
624                 uint256 hashTx = tx.GetHash();
625                 CTxIndex txindex;
626                 if (ReadTxIndex(hashTx, txindex))
627                 {
628                     // check level 3: checker transaction hashes
629                     if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
630                     {
631                         // either an error or a duplicate transaction
632                         CTransaction txFound;
633                         if (!txFound.ReadFromDisk(txindex.pos))
634                         {
635                             printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
636                             pindexFork = pindex->pprev;
637                         }
638                         else
639                             if (txFound.GetHash() != hashTx) // not a duplicate tx
640                             {
641                                 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
642                                 pindexFork = pindex->pprev;
643                             }
644                     }
645                     // check level 4: check whether spent txouts were spent within the main chain
646                     int nOutput = 0;
647                     if (nCheckLevel>3)
648                     {
649                         BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
650                         {
651                             if (!txpos.IsNull())
652                             {
653                                 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
654                                 if (!mapBlockPos.count(posFind))
655                                 {
656                                     printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
657                                     pindexFork = pindex->pprev;
658                                 }
659                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
660                                 if (nCheckLevel>5)
661                                 {
662                                     CTransaction txSpend;
663                                     if (!txSpend.ReadFromDisk(txpos))
664                                     {
665                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
666                                         pindexFork = pindex->pprev;
667                                     }
668                                     else if (!txSpend.CheckTransaction())
669                                     {
670                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
671                                         pindexFork = pindex->pprev;
672                                     }
673                                     else
674                                     {
675                                         bool fFound = false;
676                                         BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
677                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
678                                                 fFound = true;
679                                         if (!fFound)
680                                         {
681                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
682                                             pindexFork = pindex->pprev;
683                                         }
684                                     }
685                                 }
686                             }
687                             nOutput++;
688                         }
689                     }
690                 }
691                 // check level 5: check whether all prevouts are marked spent
692                 if (nCheckLevel>4)
693                 {
694                      BOOST_FOREACH(const CTxIn &txin, tx.vin)
695                      {
696                           CTxIndex txindex;
697                           if (ReadTxIndex(txin.prevout.hash, txindex))
698                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
699                               {
700                                   printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
701                                   pindexFork = pindex->pprev;
702                               }
703                      }
704                 }
705             }
706         }
707     }
708     if (pindexFork)
709     {
710         // Reorg back to the fork
711         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
712         CBlock block;
713         if (!block.ReadFromDisk(pindexFork))
714             return error("LoadBlockIndex() : block.ReadFromDisk failed");
715         CTxDB txdb;
716         block.SetBestChain(txdb, pindexFork);
717     }
718
719     return true;
720 }
721
722
723
724
725
726 //
727 // CAddrDB
728 //
729
730 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
731 {
732     return Write(string("addrman"), addrman);
733 }
734
735 bool CAddrDB::LoadAddresses()
736 {
737     if (Read(string("addrman"), addrman))
738     {
739         printf("Loaded %i addresses\n", addrman.size());
740         return true;
741     }
742     
743     // Read pre-0.6 addr records
744
745     vector<CAddress> vAddr;
746     vector<vector<unsigned char> > vDelete;
747
748     // Get cursor
749     Dbc* pcursor = GetCursor();
750     if (!pcursor)
751         return false;
752
753     loop
754     {
755         // Read next record
756         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
757         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
758         int ret = ReadAtCursor(pcursor, ssKey, ssValue);
759         if (ret == DB_NOTFOUND)
760             break;
761         else if (ret != 0)
762             return false;
763
764         // Unserialize
765         string strType;
766         ssKey >> strType;
767         if (strType == "addr")
768         {
769             CAddress addr;
770             ssValue >> addr;
771             vAddr.push_back(addr);
772         }
773     }
774     pcursor->close();
775
776     addrman.Add(vAddr, CNetAddr("0.0.0.0"));
777     printf("Loaded %i addresses\n", addrman.size());
778
779     // Note: old records left; we ran into hangs-on-startup
780     // bugs for some users who (we think) were running after
781     // an unclean shutdown.
782
783     return true;
784 }
785
786 bool LoadAddresses()
787 {
788     return CAddrDB("cr+").LoadAddresses();
789 }
790
791