Workaround hangs when upgrading old addr.dat files
[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 "headers.h"
7 #include "db.h"
8 #include "net.h"
9 #include <boost/version.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12
13 using namespace std;
14 using namespace boost;
15
16
17 unsigned int nWalletDBUpdated;
18 uint64 nAccountingEntryNumber = 0;
19
20
21
22 //
23 // CDB
24 //
25
26 static CCriticalSection cs_db;
27 static bool fDbEnvInit = false;
28 DbEnv dbenv(0);
29 static map<string, int> mapFileUseCount;
30 static map<string, Db*> mapDb;
31
32 static void EnvShutdown()
33 {
34     if (!fDbEnvInit)
35         return;
36
37     fDbEnvInit = false;
38     try
39     {
40         dbenv.close(0);
41     }
42     catch (const DbException& e)
43     {
44         printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
45     }
46     DbEnv(0).remove(GetDataDir().c_str(), 0);
47 }
48
49 class CDBInit
50 {
51 public:
52     CDBInit()
53     {
54     }
55     ~CDBInit()
56     {
57         EnvShutdown();
58     }
59 }
60 instance_of_cdbinit;
61
62
63 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
64 {
65     int ret;
66     if (pszFile == NULL)
67         return;
68
69     fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
70     bool fCreate = strchr(pszMode, 'c');
71     unsigned int nFlags = DB_THREAD;
72     if (fCreate)
73         nFlags |= DB_CREATE;
74
75     CRITICAL_BLOCK(cs_db)
76     {
77         if (!fDbEnvInit)
78         {
79             if (fShutdown)
80                 return;
81             string strDataDir = GetDataDir();
82             string strLogDir = strDataDir + "/database";
83             filesystem::create_directory(strLogDir.c_str());
84             string strErrorFile = strDataDir + "/db.log";
85             printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
86
87             int nDbCache = GetArg("-dbcache", 25);
88             dbenv.set_lg_dir(strLogDir.c_str());
89             dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
90             dbenv.set_lg_bsize(1048576);
91             dbenv.set_lg_max(10485760);
92             dbenv.set_lk_max_locks(10000);
93             dbenv.set_lk_max_objects(10000);
94             dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
95             dbenv.set_flags(DB_AUTO_COMMIT, 1);
96             dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
97             ret = dbenv.open(strDataDir.c_str(),
98                              DB_CREATE     |
99                              DB_INIT_LOCK  |
100                              DB_INIT_LOG   |
101                              DB_INIT_MPOOL |
102                              DB_INIT_TXN   |
103                              DB_THREAD     |
104                              DB_RECOVER,
105                              S_IRUSR | S_IWUSR);
106             if (ret > 0)
107                 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
108             fDbEnvInit = true;
109         }
110
111         strFile = pszFile;
112         ++mapFileUseCount[strFile];
113         pdb = mapDb[strFile];
114         if (pdb == NULL)
115         {
116             pdb = new Db(&dbenv, 0);
117
118             ret = pdb->open(NULL,      // Txn pointer
119                             pszFile,   // Filename
120                             "main",    // Logical db name
121                             DB_BTREE,  // Database type
122                             nFlags,    // Flags
123                             0);
124
125             if (ret > 0)
126             {
127                 delete pdb;
128                 pdb = NULL;
129                 CRITICAL_BLOCK(cs_db)
130                     --mapFileUseCount[strFile];
131                 strFile = "";
132                 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
133             }
134
135             if (fCreate && !Exists(string("version")))
136             {
137                 bool fTmp = fReadOnly;
138                 fReadOnly = false;
139                 WriteVersion(CLIENT_VERSION);
140                 fReadOnly = fTmp;
141             }
142
143             mapDb[strFile] = pdb;
144         }
145     }
146 }
147
148 void CDB::Close()
149 {
150     if (!pdb)
151         return;
152     if (!vTxn.empty())
153         vTxn.front()->abort();
154     vTxn.clear();
155     pdb = NULL;
156
157     // Flush database activity from memory pool to disk log
158     unsigned int nMinutes = 0;
159     if (fReadOnly)
160         nMinutes = 1;
161     if (strFile == "addr.dat")
162         nMinutes = 2;
163     if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 5000 != 0)
164         nMinutes = 1;
165     dbenv.txn_checkpoint(0, nMinutes, 0);
166
167     CRITICAL_BLOCK(cs_db)
168         --mapFileUseCount[strFile];
169 }
170
171 void static CloseDb(const string& strFile)
172 {
173     CRITICAL_BLOCK(cs_db)
174     {
175         if (mapDb[strFile] != NULL)
176         {
177             // Close the database handle
178             Db* pdb = mapDb[strFile];
179             pdb->close(0);
180             delete pdb;
181             mapDb[strFile] = NULL;
182         }
183     }
184 }
185
186 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
187 {
188     while (!fShutdown)
189     {
190         CRITICAL_BLOCK(cs_db)
191         {
192             if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
193             {
194                 // Flush log data to the dat file
195                 CloseDb(strFile);
196                 dbenv.txn_checkpoint(0, 0, 0);
197                 dbenv.lsn_reset(strFile.c_str(), 0);
198                 mapFileUseCount.erase(strFile);
199
200                 bool fSuccess = true;
201                 printf("Rewriting %s...\n", strFile.c_str());
202                 string strFileRes = strFile + ".rewrite";
203                 { // surround usage of db with extra {}
204                     CDB db(strFile.c_str(), "r");
205                     Db* pdbCopy = new Db(&dbenv, 0);
206     
207                     int ret = pdbCopy->open(NULL,                 // Txn pointer
208                                             strFileRes.c_str(),   // Filename
209                                             "main",    // Logical db name
210                                             DB_BTREE,  // Database type
211                                             DB_CREATE,    // Flags
212                                             0);
213                     if (ret > 0)
214                     {
215                         printf("Cannot create database file %s\n", strFileRes.c_str());
216                         fSuccess = false;
217                     }
218     
219                     Dbc* pcursor = db.GetCursor();
220                     if (pcursor)
221                         while (fSuccess)
222                         {
223                             CDataStream ssKey;
224                             CDataStream ssValue;
225                             int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
226                             if (ret == DB_NOTFOUND)
227                             {
228                                 pcursor->close();
229                                 break;
230                             }
231                             else if (ret != 0)
232                             {
233                                 pcursor->close();
234                                 fSuccess = false;
235                                 break;
236                             }
237                             if (pszSkip &&
238                                 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
239                                 continue;
240                             if (strncmp(&ssKey[0], "\x07version", 8) == 0)
241                             {
242                                 // Update version:
243                                 ssValue.clear();
244                                 ssValue << CLIENT_VERSION;
245                             }
246                             Dbt datKey(&ssKey[0], ssKey.size());
247                             Dbt datValue(&ssValue[0], ssValue.size());
248                             int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
249                             if (ret2 > 0)
250                                 fSuccess = false;
251                         }
252                     if (fSuccess)
253                     {
254                         db.Close();
255                         CloseDb(strFile);
256                         if (pdbCopy->close(0))
257                             fSuccess = false;
258                         delete pdbCopy;
259                     }
260                 }
261                 if (fSuccess)
262                 {
263                     Db dbA(&dbenv, 0);
264                     if (dbA.remove(strFile.c_str(), NULL, 0))
265                         fSuccess = false;
266                     Db dbB(&dbenv, 0);
267                     if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
268                         fSuccess = false;
269                 }
270                 if (!fSuccess)
271                     printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
272                 return fSuccess;
273             }
274         }
275         Sleep(100);
276     }
277     return false;
278 }
279
280
281 void DBFlush(bool fShutdown)
282 {
283     // Flush log data to the actual data file
284     //  on all files that are not in use
285     printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
286     if (!fDbEnvInit)
287         return;
288     CRITICAL_BLOCK(cs_db)
289     {
290         map<string, int>::iterator mi = mapFileUseCount.begin();
291         while (mi != mapFileUseCount.end())
292         {
293             string strFile = (*mi).first;
294             int nRefCount = (*mi).second;
295             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
296             if (nRefCount == 0)
297             {
298                 // Move log data to the dat file
299                 CloseDb(strFile);
300                 dbenv.txn_checkpoint(0, 0, 0);
301                 printf("%s flush\n", strFile.c_str());
302                 dbenv.lsn_reset(strFile.c_str(), 0);
303                 mapFileUseCount.erase(mi++);
304             }
305             else
306                 mi++;
307         }
308         if (fShutdown)
309         {
310             char** listp;
311             if (mapFileUseCount.empty())
312             {
313                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
314                 EnvShutdown();
315             }
316         }
317     }
318 }
319
320
321
322
323
324
325 //
326 // CTxDB
327 //
328
329 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
330 {
331     assert(!fClient);
332     txindex.SetNull();
333     return Read(make_pair(string("tx"), hash), txindex);
334 }
335
336 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
337 {
338     assert(!fClient);
339     return Write(make_pair(string("tx"), hash), txindex);
340 }
341
342 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
343 {
344     assert(!fClient);
345
346     // Add to tx index
347     uint256 hash = tx.GetHash();
348     CTxIndex txindex(pos, tx.vout.size());
349     return Write(make_pair(string("tx"), hash), txindex);
350 }
351
352 bool CTxDB::EraseTxIndex(const CTransaction& tx)
353 {
354     assert(!fClient);
355     uint256 hash = tx.GetHash();
356
357     return Erase(make_pair(string("tx"), hash));
358 }
359
360 bool CTxDB::ContainsTx(uint256 hash)
361 {
362     assert(!fClient);
363     return Exists(make_pair(string("tx"), hash));
364 }
365
366 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
367 {
368     assert(!fClient);
369     vtx.clear();
370
371     // Get cursor
372     Dbc* pcursor = GetCursor();
373     if (!pcursor)
374         return false;
375
376     unsigned int fFlags = DB_SET_RANGE;
377     loop
378     {
379         // Read next record
380         CDataStream ssKey;
381         if (fFlags == DB_SET_RANGE)
382             ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
383         CDataStream ssValue;
384         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
385         fFlags = DB_NEXT;
386         if (ret == DB_NOTFOUND)
387             break;
388         else if (ret != 0)
389         {
390             pcursor->close();
391             return false;
392         }
393
394         // Unserialize
395         string strType;
396         uint160 hashItem;
397         CDiskTxPos pos;
398         ssKey >> strType >> hashItem >> pos;
399         int nItemHeight;
400         ssValue >> nItemHeight;
401
402         // Read transaction
403         if (strType != "owner" || hashItem != hash160)
404             break;
405         if (nItemHeight >= nMinHeight)
406         {
407             vtx.resize(vtx.size()+1);
408             if (!vtx.back().ReadFromDisk(pos))
409             {
410                 pcursor->close();
411                 return false;
412             }
413         }
414     }
415
416     pcursor->close();
417     return true;
418 }
419
420 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
421 {
422     assert(!fClient);
423     tx.SetNull();
424     if (!ReadTxIndex(hash, txindex))
425         return false;
426     return (tx.ReadFromDisk(txindex.pos));
427 }
428
429 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
430 {
431     CTxIndex txindex;
432     return ReadDiskTx(hash, tx, txindex);
433 }
434
435 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
436 {
437     return ReadDiskTx(outpoint.hash, tx, txindex);
438 }
439
440 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
441 {
442     CTxIndex txindex;
443     return ReadDiskTx(outpoint.hash, tx, txindex);
444 }
445
446 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
447 {
448     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
449 }
450
451 bool CTxDB::EraseBlockIndex(uint256 hash)
452 {
453     return Erase(make_pair(string("blockindex"), hash));
454 }
455
456 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
457 {
458     return Read(string("hashBestChain"), hashBestChain);
459 }
460
461 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
462 {
463     return Write(string("hashBestChain"), hashBestChain);
464 }
465
466 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
467 {
468     return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
469 }
470
471 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
472 {
473     return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
474 }
475
476 CBlockIndex static * InsertBlockIndex(uint256 hash)
477 {
478     if (hash == 0)
479         return NULL;
480
481     // Return existing
482     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
483     if (mi != mapBlockIndex.end())
484         return (*mi).second;
485
486     // Create new
487     CBlockIndex* pindexNew = new CBlockIndex();
488     if (!pindexNew)
489         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
490     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
491     pindexNew->phashBlock = &((*mi).first);
492
493     return pindexNew;
494 }
495
496 bool CTxDB::LoadBlockIndex()
497 {
498     // Get database cursor
499     Dbc* pcursor = GetCursor();
500     if (!pcursor)
501         return false;
502
503     // Load mapBlockIndex
504     unsigned int fFlags = DB_SET_RANGE;
505     loop
506     {
507         // Read next record
508         CDataStream ssKey;
509         if (fFlags == DB_SET_RANGE)
510             ssKey << make_pair(string("blockindex"), uint256(0));
511         CDataStream ssValue;
512         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
513         fFlags = DB_NEXT;
514         if (ret == DB_NOTFOUND)
515             break;
516         else if (ret != 0)
517             return false;
518
519         // Unserialize
520         string strType;
521         ssKey >> strType;
522         if (strType == "blockindex")
523         {
524             CDiskBlockIndex diskindex;
525             ssValue >> diskindex;
526
527             // Construct block index object
528             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
529             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
530             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
531             pindexNew->nFile          = diskindex.nFile;
532             pindexNew->nBlockPos      = diskindex.nBlockPos;
533             pindexNew->nHeight        = diskindex.nHeight;
534             pindexNew->nVersion       = diskindex.nVersion;
535             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
536             pindexNew->nTime          = diskindex.nTime;
537             pindexNew->nBits          = diskindex.nBits;
538             pindexNew->nNonce         = diskindex.nNonce;
539
540             // Watch for genesis block
541             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
542                 pindexGenesisBlock = pindexNew;
543
544             if (!pindexNew->CheckIndex())
545                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
546         }
547         else
548         {
549             break;
550         }
551     }
552     pcursor->close();
553
554     // Calculate bnChainWork
555     vector<pair<int, CBlockIndex*> > vSortedByHeight;
556     vSortedByHeight.reserve(mapBlockIndex.size());
557     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
558     {
559         CBlockIndex* pindex = item.second;
560         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
561     }
562     sort(vSortedByHeight.begin(), vSortedByHeight.end());
563     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
564     {
565         CBlockIndex* pindex = item.second;
566         pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
567     }
568
569     // Load hashBestChain pointer to end of best chain
570     if (!ReadHashBestChain(hashBestChain))
571     {
572         if (pindexGenesisBlock == NULL)
573             return true;
574         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
575     }
576     if (!mapBlockIndex.count(hashBestChain))
577         return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
578     pindexBest = mapBlockIndex[hashBestChain];
579     nBestHeight = pindexBest->nHeight;
580     bnBestChainWork = pindexBest->bnChainWork;
581     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
582
583     // Load bnBestInvalidWork, OK if it doesn't exist
584     ReadBestInvalidWork(bnBestInvalidWork);
585
586     // Verify blocks in the best chain
587     int nCheckLevel = GetArg("-checklevel", 1);
588     int nCheckDepth = GetArg( "-checkblocks", 2500);
589     if (nCheckDepth == 0)
590         nCheckDepth = 1000000000; // suffices until the year 19000
591     if (nCheckDepth > nBestHeight)
592         nCheckDepth = nBestHeight;
593     printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
594     CBlockIndex* pindexFork = NULL;
595     map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
596     for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
597     {
598         if (pindex->nHeight < nBestHeight-nCheckDepth)
599             break;
600         CBlock block;
601         if (!block.ReadFromDisk(pindex))
602             return error("LoadBlockIndex() : block.ReadFromDisk failed");
603         // check level 1: verify block validity
604         if (nCheckLevel>0 && !block.CheckBlock())
605         {
606             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
607             pindexFork = pindex->pprev;
608         }
609         // check level 2: verify transaction index validity
610         if (nCheckLevel>1)
611         {
612             pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
613             mapBlockPos[pos] = pindex;
614             BOOST_FOREACH(const CTransaction &tx, block.vtx)
615             {
616                 uint256 hashTx = tx.GetHash();
617                 CTxIndex txindex;
618                 if (ReadTxIndex(hashTx, txindex))
619                 {
620                     // check level 3: checker transaction hashes
621                     if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
622                     {
623                         // either an error or a duplicate transaction
624                         CTransaction txFound;
625                         if (!txFound.ReadFromDisk(txindex.pos))
626                         {
627                             printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
628                             pindexFork = pindex->pprev;
629                         }
630                         else
631                             if (txFound.GetHash() != hashTx) // not a duplicate tx
632                             {
633                                 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
634                                 pindexFork = pindex->pprev;
635                             }
636                     }
637                     // check level 4: check whether spent txouts were spent within the main chain
638                     int nOutput = 0;
639                     if (nCheckLevel>3)
640                         BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
641                         {
642                             if (!txpos.IsNull())
643                             {
644                                 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
645                                 if (!mapBlockPos.count(posFind))
646                                 {
647                                     printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
648                                     pindexFork = pindex->pprev;
649                                 }
650                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
651                                 if (nCheckLevel>5)
652                                 {
653                                     CTransaction txSpend;
654                                     if (!txSpend.ReadFromDisk(txpos))
655                                     {
656                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
657                                         pindexFork = pindex->pprev;
658                                     }
659                                     else if (!txSpend.CheckTransaction())
660                                     {
661                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
662                                         pindexFork = pindex->pprev;
663                                     }
664                                     else
665                                     {
666                                         bool fFound = false;
667                                         BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
668                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
669                                                 fFound = true;
670                                         if (!fFound)
671                                         {
672                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
673                                             pindexFork = pindex->pprev;
674                                         }
675                                     }
676                                 }
677                             }
678                             nOutput++;
679                         }
680                 }
681                 // check level 5: check whether all prevouts are marked spent
682                 if (nCheckLevel>4)
683                      BOOST_FOREACH(const CTxIn &txin, tx.vin)
684                      {
685                           CTxIndex txindex;
686                           if (ReadTxIndex(txin.prevout.hash, txindex))
687                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
688                               {
689                                   printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
690                                   pindexFork = pindex->pprev;
691                               }
692                      }
693             }
694         }
695     }
696     if (pindexFork)
697     {
698         // Reorg back to the fork
699         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
700         CBlock block;
701         if (!block.ReadFromDisk(pindexFork))
702             return error("LoadBlockIndex() : block.ReadFromDisk failed");
703         CTxDB txdb;
704         block.SetBestChain(txdb, pindexFork);
705     }
706
707     return true;
708 }
709
710
711
712
713
714 //
715 // CAddrDB
716 //
717
718 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
719 {
720     return Write(string("addrman"), addrman);
721 }
722
723 bool CAddrDB::LoadAddresses()
724 {
725     if (Read(string("addrman"), addrman))
726     {
727         printf("Loaded %i addresses\n", addrman.size());
728         return true;
729     }
730     
731     // Read pre-0.6 addr records
732
733     vector<CAddress> vAddr;
734     vector<vector<unsigned char> > vDelete;
735
736     // Get cursor
737     Dbc* pcursor = GetCursor();
738     if (!pcursor)
739         return false;
740
741     loop
742     {
743         // Read next record
744         CDataStream ssKey;
745         CDataStream ssValue;
746         int ret = ReadAtCursor(pcursor, ssKey, ssValue);
747         if (ret == DB_NOTFOUND)
748             break;
749         else if (ret != 0)
750             return false;
751
752         // Unserialize
753         string strType;
754         ssKey >> strType;
755         if (strType == "addr")
756         {
757             CAddress addr;
758             ssValue >> addr;
759             vAddr.push_back(addr);
760         }
761     }
762     pcursor->close();
763
764     addrman.Add(vAddr, CNetAddr("0.0.0.0"));
765     printf("Loaded %i addresses\n", addrman.size());
766
767     // Note: old records left; we ran into hangs-on-startup
768     // bugs for some users who (we think) were running after
769     // an unclean shutdown.
770
771     return true;
772 }
773
774 bool LoadAddresses()
775 {
776     return CAddrDB("cr+").LoadAddresses();
777 }
778
779
780
781
782 //
783 // CWalletDB
784 //
785
786 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
787 {
788     nWalletDBUpdated++;
789     return Write(make_pair(string("name"), strAddress), strName);
790 }
791
792 bool CWalletDB::EraseName(const string& strAddress)
793 {
794     // This should only be used for sending addresses, never for receiving addresses,
795     // receiving addresses must always have an address book entry if they're not change return.
796     nWalletDBUpdated++;
797     return Erase(make_pair(string("name"), strAddress));
798 }
799
800 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
801 {
802     account.SetNull();
803     return Read(make_pair(string("acc"), strAccount), account);
804 }
805
806 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
807 {
808     return Write(make_pair(string("acc"), strAccount), account);
809 }
810
811 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
812 {
813     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
814 }
815
816 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
817 {
818     list<CAccountingEntry> entries;
819     ListAccountCreditDebit(strAccount, entries);
820
821     int64 nCreditDebit = 0;
822     BOOST_FOREACH (const CAccountingEntry& entry, entries)
823         nCreditDebit += entry.nCreditDebit;
824
825     return nCreditDebit;
826 }
827
828 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
829 {
830     bool fAllAccounts = (strAccount == "*");
831
832     Dbc* pcursor = GetCursor();
833     if (!pcursor)
834         throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
835     unsigned int fFlags = DB_SET_RANGE;
836     loop
837     {
838         // Read next record
839         CDataStream ssKey;
840         if (fFlags == DB_SET_RANGE)
841             ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
842         CDataStream ssValue;
843         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
844         fFlags = DB_NEXT;
845         if (ret == DB_NOTFOUND)
846             break;
847         else if (ret != 0)
848         {
849             pcursor->close();
850             throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
851         }
852
853         // Unserialize
854         string strType;
855         ssKey >> strType;
856         if (strType != "acentry")
857             break;
858         CAccountingEntry acentry;
859         ssKey >> acentry.strAccount;
860         if (!fAllAccounts && acentry.strAccount != strAccount)
861             break;
862
863         ssValue >> acentry;
864         entries.push_back(acentry);
865     }
866
867     pcursor->close();
868 }
869
870
871 int CWalletDB::LoadWallet(CWallet* pwallet)
872 {
873     pwallet->vchDefaultKey.clear();
874     int nFileVersion = 0;
875     vector<uint256> vWalletUpgrade;
876     bool fIsEncrypted = false;
877
878     //// todo: shouldn't we catch exceptions and try to recover and continue?
879     CRITICAL_BLOCK(pwallet->cs_wallet)
880     {
881         int nMinVersion = 0;
882         if (Read((string)"minversion", nMinVersion))
883         {
884             if (nMinVersion > CLIENT_VERSION)
885                 return DB_TOO_NEW;
886             pwallet->LoadMinVersion(nMinVersion);
887         }
888
889         // Get cursor
890         Dbc* pcursor = GetCursor();
891         if (!pcursor)
892         {
893             printf("Error getting wallet database cursor\n");
894             return DB_CORRUPT;
895         }
896
897         loop
898         {
899             // Read next record
900             CDataStream ssKey;
901             CDataStream ssValue;
902             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
903             if (ret == DB_NOTFOUND)
904                 break;
905             else if (ret != 0)
906             {
907                 printf("Error reading next record from wallet database\n");
908                 return DB_CORRUPT;
909             }
910
911             // Unserialize
912             // Taking advantage of the fact that pair serialization
913             // is just the two items serialized one after the other
914             string strType;
915             ssKey >> strType;
916             if (strType == "name")
917             {
918                 string strAddress;
919                 ssKey >> strAddress;
920                 ssValue >> pwallet->mapAddressBook[strAddress];
921             }
922             else if (strType == "tx")
923             {
924                 uint256 hash;
925                 ssKey >> hash;
926                 CWalletTx& wtx = pwallet->mapWallet[hash];
927                 ssValue >> wtx;
928                 wtx.BindWallet(pwallet);
929
930                 if (wtx.GetHash() != hash)
931                     printf("Error in wallet.dat, hash mismatch\n");
932
933                 // Undo serialize changes in 31600
934                 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
935                 {
936                     if (!ssValue.empty())
937                     {
938                         char fTmp;
939                         char fUnused;
940                         ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
941                         printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
942                         wtx.fTimeReceivedIsTxTime = fTmp;
943                     }
944                     else
945                     {
946                         printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
947                         wtx.fTimeReceivedIsTxTime = 0;
948                     }
949                     vWalletUpgrade.push_back(hash);
950                 }
951
952                 //// debug print
953                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
954                 //printf(" %12I64d  %s  %s  %s\n",
955                 //    wtx.vout[0].nValue,
956                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
957                 //    wtx.hashBlock.ToString().substr(0,20).c_str(),
958                 //    wtx.mapValue["message"].c_str());
959             }
960             else if (strType == "acentry")
961             {
962                 string strAccount;
963                 ssKey >> strAccount;
964                 uint64 nNumber;
965                 ssKey >> nNumber;
966                 if (nNumber > nAccountingEntryNumber)
967                     nAccountingEntryNumber = nNumber;
968             }
969             else if (strType == "key" || strType == "wkey")
970             {
971                 vector<unsigned char> vchPubKey;
972                 ssKey >> vchPubKey;
973                 CKey key;
974                 if (strType == "key")
975                 {
976                     CPrivKey pkey;
977                     ssValue >> pkey;
978                     key.SetPubKey(vchPubKey);
979                     key.SetPrivKey(pkey);
980                     if (key.GetPubKey() != vchPubKey)
981                     {
982                         printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
983                         return DB_CORRUPT;
984                     }
985                     if (!key.IsValid())
986                     {
987                         printf("Error reading wallet database: invalid CPrivKey\n");
988                         return DB_CORRUPT;
989                     }
990                 }
991                 else
992                 {
993                     CWalletKey wkey;
994                     ssValue >> wkey;
995                     key.SetPubKey(vchPubKey);
996                     key.SetPrivKey(wkey.vchPrivKey);
997                     if (key.GetPubKey() != vchPubKey)
998                     {
999                         printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1000                         return DB_CORRUPT;
1001                     }
1002                     if (!key.IsValid())
1003                     {
1004                         printf("Error reading wallet database: invalid CWalletKey\n");
1005                         return DB_CORRUPT;
1006                     }
1007                 }
1008                 if (!pwallet->LoadKey(key))
1009                 {
1010                     printf("Error reading wallet database: LoadKey failed\n");
1011                     return DB_CORRUPT;
1012                 }
1013             }
1014             else if (strType == "mkey")
1015             {
1016                 unsigned int nID;
1017                 ssKey >> nID;
1018                 CMasterKey kMasterKey;
1019                 ssValue >> kMasterKey;
1020                 if(pwallet->mapMasterKeys.count(nID) != 0)
1021                 {
1022                     printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1023                     return DB_CORRUPT;
1024                 }
1025                 pwallet->mapMasterKeys[nID] = kMasterKey;
1026                 if (pwallet->nMasterKeyMaxID < nID)
1027                     pwallet->nMasterKeyMaxID = nID;
1028             }
1029             else if (strType == "ckey")
1030             {
1031                 vector<unsigned char> vchPubKey;
1032                 ssKey >> vchPubKey;
1033                 vector<unsigned char> vchPrivKey;
1034                 ssValue >> vchPrivKey;
1035                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1036                 {
1037                     printf("Error reading wallet database: LoadCryptedKey failed\n");
1038                     return DB_CORRUPT;
1039                 }
1040                 fIsEncrypted = true;
1041             }
1042             else if (strType == "defaultkey")
1043             {
1044                 ssValue >> pwallet->vchDefaultKey;
1045             }
1046             else if (strType == "pool")
1047             {
1048                 int64 nIndex;
1049                 ssKey >> nIndex;
1050                 pwallet->setKeyPool.insert(nIndex);
1051             }
1052             else if (strType == "version")
1053             {
1054                 ssValue >> nFileVersion;
1055                 if (nFileVersion == 10300)
1056                     nFileVersion = 300;
1057             }
1058             else if (strType == "cscript")
1059             {
1060                 uint160 hash;
1061                 ssKey >> hash;
1062                 CScript script;
1063                 ssValue >> script;
1064                 if (!pwallet->LoadCScript(script))
1065                 {
1066                     printf("Error reading wallet database: LoadCScript failed\n");
1067                     return DB_CORRUPT;
1068                 }
1069             }
1070         }
1071         pcursor->close();
1072     }
1073
1074     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1075         WriteTx(hash, pwallet->mapWallet[hash]);
1076
1077     printf("nFileVersion = %d\n", nFileVersion);
1078
1079
1080     // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1081     if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1082         return DB_NEED_REWRITE;
1083
1084     if (nFileVersion < CLIENT_VERSION) // Update
1085     {
1086         // Get rid of old debug.log file in current directory
1087         if (nFileVersion <= 105 && !pszSetDataDir[0])
1088             unlink("debug.log");
1089
1090         WriteVersion(CLIENT_VERSION);
1091     }
1092
1093     return DB_LOAD_OK;
1094 }
1095
1096 void ThreadFlushWalletDB(void* parg)
1097 {
1098     const string& strFile = ((const string*)parg)[0];
1099     static bool fOneThread;
1100     if (fOneThread)
1101         return;
1102     fOneThread = true;
1103     if (!GetBoolArg("-flushwallet", true))
1104         return;
1105
1106     unsigned int nLastSeen = nWalletDBUpdated;
1107     unsigned int nLastFlushed = nWalletDBUpdated;
1108     int64 nLastWalletUpdate = GetTime();
1109     while (!fShutdown)
1110     {
1111         Sleep(500);
1112
1113         if (nLastSeen != nWalletDBUpdated)
1114         {
1115             nLastSeen = nWalletDBUpdated;
1116             nLastWalletUpdate = GetTime();
1117         }
1118
1119         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1120         {
1121             TRY_CRITICAL_BLOCK(cs_db)
1122             {
1123                 // Don't do this if any databases are in use
1124                 int nRefCount = 0;
1125                 map<string, int>::iterator mi = mapFileUseCount.begin();
1126                 while (mi != mapFileUseCount.end())
1127                 {
1128                     nRefCount += (*mi).second;
1129                     mi++;
1130                 }
1131
1132                 if (nRefCount == 0 && !fShutdown)
1133                 {
1134                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1135                     if (mi != mapFileUseCount.end())
1136                     {
1137                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1138                         printf("Flushing wallet.dat\n");
1139                         nLastFlushed = nWalletDBUpdated;
1140                         int64 nStart = GetTimeMillis();
1141
1142                         // Flush wallet.dat so it's self contained
1143                         CloseDb(strFile);
1144                         dbenv.txn_checkpoint(0, 0, 0);
1145                         dbenv.lsn_reset(strFile.c_str(), 0);
1146
1147                         mapFileUseCount.erase(mi++);
1148                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1149                     }
1150                 }
1151             }
1152         }
1153     }
1154 }
1155
1156 bool BackupWallet(const CWallet& wallet, const string& strDest)
1157 {
1158     if (!wallet.fFileBacked)
1159         return false;
1160     while (!fShutdown)
1161     {
1162         CRITICAL_BLOCK(cs_db)
1163         {
1164             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1165             {
1166                 // Flush log data to the dat file
1167                 CloseDb(wallet.strWalletFile);
1168                 dbenv.txn_checkpoint(0, 0, 0);
1169                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1170                 mapFileUseCount.erase(wallet.strWalletFile);
1171
1172                 // Copy wallet.dat
1173                 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1174                 filesystem::path pathDest(strDest);
1175                 if (filesystem::is_directory(pathDest))
1176                     pathDest = pathDest / wallet.strWalletFile;
1177
1178                 try {
1179 #if BOOST_VERSION >= 104000
1180                     filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1181 #else
1182                     filesystem::copy_file(pathSrc, pathDest);
1183 #endif
1184                     printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1185                     return true;
1186                 } catch(const filesystem::filesystem_error &e) {
1187                     printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
1188                     return false;
1189                 }
1190             }
1191         }
1192         Sleep(100);
1193     }
1194     return false;
1195 }