Auto-remove logs, and decrease logfile size to 10M
[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     bool fAddrMan = false;
726     if (Read(string("addrman"), addrman))
727     {
728         printf("Loaded %i addresses\n", addrman.size());
729         fAddrMan = true;
730     }
731
732     vector<CAddress> vAddr;
733     vector<vector<unsigned char> > vDelete;
734
735     // Get cursor
736     Dbc* pcursor = GetCursor();
737     if (!pcursor)
738         return false;
739
740     loop
741     {
742         // Read next record
743         CDataStream ssKey;
744         CDataStream ssValue;
745         int ret = ReadAtCursor(pcursor, ssKey, ssValue);
746         if (ret == DB_NOTFOUND)
747             break;
748         else if (ret != 0)
749             return false;
750
751         // Unserialize
752         string strType;
753         ssKey >> strType;
754         if (strType == "addr")
755         {
756             if (fAddrMan)
757             {
758                 vector<unsigned char> vchKey;
759                 ssKey >> vchKey;
760                 vDelete.push_back(vchKey);
761             }
762             else
763             {
764                 CAddress addr;
765                 ssValue >> addr;
766                 vAddr.push_back(addr);
767             }
768
769         }
770     }
771     pcursor->close();
772
773     BOOST_FOREACH(const vector<unsigned char> &vchKey, vDelete)
774         Erase(make_pair(string("addr"), vchKey));
775
776     if (!fAddrMan)
777     {
778         addrman.Add(vAddr, CNetAddr("0.0.0.0"));
779         printf("Loaded %i addresses\n", addrman.size());
780     }
781
782     return true;
783 }
784
785 bool LoadAddresses()
786 {
787     return CAddrDB("cr+").LoadAddresses();
788 }
789
790
791
792
793 //
794 // CWalletDB
795 //
796
797 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
798 {
799     nWalletDBUpdated++;
800     return Write(make_pair(string("name"), strAddress), strName);
801 }
802
803 bool CWalletDB::EraseName(const string& strAddress)
804 {
805     // This should only be used for sending addresses, never for receiving addresses,
806     // receiving addresses must always have an address book entry if they're not change return.
807     nWalletDBUpdated++;
808     return Erase(make_pair(string("name"), strAddress));
809 }
810
811 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
812 {
813     account.SetNull();
814     return Read(make_pair(string("acc"), strAccount), account);
815 }
816
817 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
818 {
819     return Write(make_pair(string("acc"), strAccount), account);
820 }
821
822 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
823 {
824     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
825 }
826
827 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
828 {
829     list<CAccountingEntry> entries;
830     ListAccountCreditDebit(strAccount, entries);
831
832     int64 nCreditDebit = 0;
833     BOOST_FOREACH (const CAccountingEntry& entry, entries)
834         nCreditDebit += entry.nCreditDebit;
835
836     return nCreditDebit;
837 }
838
839 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
840 {
841     bool fAllAccounts = (strAccount == "*");
842
843     Dbc* pcursor = GetCursor();
844     if (!pcursor)
845         throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
846     unsigned int fFlags = DB_SET_RANGE;
847     loop
848     {
849         // Read next record
850         CDataStream ssKey;
851         if (fFlags == DB_SET_RANGE)
852             ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
853         CDataStream ssValue;
854         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
855         fFlags = DB_NEXT;
856         if (ret == DB_NOTFOUND)
857             break;
858         else if (ret != 0)
859         {
860             pcursor->close();
861             throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
862         }
863
864         // Unserialize
865         string strType;
866         ssKey >> strType;
867         if (strType != "acentry")
868             break;
869         CAccountingEntry acentry;
870         ssKey >> acentry.strAccount;
871         if (!fAllAccounts && acentry.strAccount != strAccount)
872             break;
873
874         ssValue >> acentry;
875         entries.push_back(acentry);
876     }
877
878     pcursor->close();
879 }
880
881
882 int CWalletDB::LoadWallet(CWallet* pwallet)
883 {
884     pwallet->vchDefaultKey.clear();
885     int nFileVersion = 0;
886     vector<uint256> vWalletUpgrade;
887     bool fIsEncrypted = false;
888
889     //// todo: shouldn't we catch exceptions and try to recover and continue?
890     CRITICAL_BLOCK(pwallet->cs_wallet)
891     {
892         int nMinVersion = 0;
893         if (Read((string)"minversion", nMinVersion))
894         {
895             if (nMinVersion > CLIENT_VERSION)
896                 return DB_TOO_NEW;
897             pwallet->LoadMinVersion(nMinVersion);
898         }
899
900         // Get cursor
901         Dbc* pcursor = GetCursor();
902         if (!pcursor)
903         {
904             printf("Error getting wallet database cursor\n");
905             return DB_CORRUPT;
906         }
907
908         loop
909         {
910             // Read next record
911             CDataStream ssKey;
912             CDataStream ssValue;
913             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
914             if (ret == DB_NOTFOUND)
915                 break;
916             else if (ret != 0)
917             {
918                 printf("Error reading next record from wallet database\n");
919                 return DB_CORRUPT;
920             }
921
922             // Unserialize
923             // Taking advantage of the fact that pair serialization
924             // is just the two items serialized one after the other
925             string strType;
926             ssKey >> strType;
927             if (strType == "name")
928             {
929                 string strAddress;
930                 ssKey >> strAddress;
931                 ssValue >> pwallet->mapAddressBook[strAddress];
932             }
933             else if (strType == "tx")
934             {
935                 uint256 hash;
936                 ssKey >> hash;
937                 CWalletTx& wtx = pwallet->mapWallet[hash];
938                 ssValue >> wtx;
939                 wtx.BindWallet(pwallet);
940
941                 if (wtx.GetHash() != hash)
942                     printf("Error in wallet.dat, hash mismatch\n");
943
944                 // Undo serialize changes in 31600
945                 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
946                 {
947                     if (!ssValue.empty())
948                     {
949                         char fTmp;
950                         char fUnused;
951                         ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
952                         printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
953                         wtx.fTimeReceivedIsTxTime = fTmp;
954                     }
955                     else
956                     {
957                         printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
958                         wtx.fTimeReceivedIsTxTime = 0;
959                     }
960                     vWalletUpgrade.push_back(hash);
961                 }
962
963                 //// debug print
964                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
965                 //printf(" %12I64d  %s  %s  %s\n",
966                 //    wtx.vout[0].nValue,
967                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
968                 //    wtx.hashBlock.ToString().substr(0,20).c_str(),
969                 //    wtx.mapValue["message"].c_str());
970             }
971             else if (strType == "acentry")
972             {
973                 string strAccount;
974                 ssKey >> strAccount;
975                 uint64 nNumber;
976                 ssKey >> nNumber;
977                 if (nNumber > nAccountingEntryNumber)
978                     nAccountingEntryNumber = nNumber;
979             }
980             else if (strType == "key" || strType == "wkey")
981             {
982                 vector<unsigned char> vchPubKey;
983                 ssKey >> vchPubKey;
984                 CKey key;
985                 if (strType == "key")
986                 {
987                     CPrivKey pkey;
988                     ssValue >> pkey;
989                     key.SetPubKey(vchPubKey);
990                     key.SetPrivKey(pkey);
991                     if (key.GetPubKey() != vchPubKey)
992                     {
993                         printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
994                         return DB_CORRUPT;
995                     }
996                     if (!key.IsValid())
997                     {
998                         printf("Error reading wallet database: invalid CPrivKey\n");
999                         return DB_CORRUPT;
1000                     }
1001                 }
1002                 else
1003                 {
1004                     CWalletKey wkey;
1005                     ssValue >> wkey;
1006                     key.SetPubKey(vchPubKey);
1007                     key.SetPrivKey(wkey.vchPrivKey);
1008                     if (key.GetPubKey() != vchPubKey)
1009                     {
1010                         printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1011                         return DB_CORRUPT;
1012                     }
1013                     if (!key.IsValid())
1014                     {
1015                         printf("Error reading wallet database: invalid CWalletKey\n");
1016                         return DB_CORRUPT;
1017                     }
1018                 }
1019                 if (!pwallet->LoadKey(key))
1020                 {
1021                     printf("Error reading wallet database: LoadKey failed\n");
1022                     return DB_CORRUPT;
1023                 }
1024             }
1025             else if (strType == "mkey")
1026             {
1027                 unsigned int nID;
1028                 ssKey >> nID;
1029                 CMasterKey kMasterKey;
1030                 ssValue >> kMasterKey;
1031                 if(pwallet->mapMasterKeys.count(nID) != 0)
1032                 {
1033                     printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1034                     return DB_CORRUPT;
1035                 }
1036                 pwallet->mapMasterKeys[nID] = kMasterKey;
1037                 if (pwallet->nMasterKeyMaxID < nID)
1038                     pwallet->nMasterKeyMaxID = nID;
1039             }
1040             else if (strType == "ckey")
1041             {
1042                 vector<unsigned char> vchPubKey;
1043                 ssKey >> vchPubKey;
1044                 vector<unsigned char> vchPrivKey;
1045                 ssValue >> vchPrivKey;
1046                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1047                 {
1048                     printf("Error reading wallet database: LoadCryptedKey failed\n");
1049                     return DB_CORRUPT;
1050                 }
1051                 fIsEncrypted = true;
1052             }
1053             else if (strType == "defaultkey")
1054             {
1055                 ssValue >> pwallet->vchDefaultKey;
1056             }
1057             else if (strType == "pool")
1058             {
1059                 int64 nIndex;
1060                 ssKey >> nIndex;
1061                 pwallet->setKeyPool.insert(nIndex);
1062             }
1063             else if (strType == "version")
1064             {
1065                 ssValue >> nFileVersion;
1066                 if (nFileVersion == 10300)
1067                     nFileVersion = 300;
1068             }
1069             else if (strType == "cscript")
1070             {
1071                 uint160 hash;
1072                 ssKey >> hash;
1073                 CScript script;
1074                 ssValue >> script;
1075                 if (!pwallet->LoadCScript(script))
1076                 {
1077                     printf("Error reading wallet database: LoadCScript failed\n");
1078                     return DB_CORRUPT;
1079                 }
1080             }
1081         }
1082         pcursor->close();
1083     }
1084
1085     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1086         WriteTx(hash, pwallet->mapWallet[hash]);
1087
1088     printf("nFileVersion = %d\n", nFileVersion);
1089
1090
1091     // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1092     if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1093         return DB_NEED_REWRITE;
1094
1095     if (nFileVersion < CLIENT_VERSION) // Update
1096     {
1097         // Get rid of old debug.log file in current directory
1098         if (nFileVersion <= 105 && !pszSetDataDir[0])
1099             unlink("debug.log");
1100
1101         WriteVersion(CLIENT_VERSION);
1102     }
1103
1104     return DB_LOAD_OK;
1105 }
1106
1107 void ThreadFlushWalletDB(void* parg)
1108 {
1109     const string& strFile = ((const string*)parg)[0];
1110     static bool fOneThread;
1111     if (fOneThread)
1112         return;
1113     fOneThread = true;
1114     if (!GetBoolArg("-flushwallet", true))
1115         return;
1116
1117     unsigned int nLastSeen = nWalletDBUpdated;
1118     unsigned int nLastFlushed = nWalletDBUpdated;
1119     int64 nLastWalletUpdate = GetTime();
1120     while (!fShutdown)
1121     {
1122         Sleep(500);
1123
1124         if (nLastSeen != nWalletDBUpdated)
1125         {
1126             nLastSeen = nWalletDBUpdated;
1127             nLastWalletUpdate = GetTime();
1128         }
1129
1130         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1131         {
1132             TRY_CRITICAL_BLOCK(cs_db)
1133             {
1134                 // Don't do this if any databases are in use
1135                 int nRefCount = 0;
1136                 map<string, int>::iterator mi = mapFileUseCount.begin();
1137                 while (mi != mapFileUseCount.end())
1138                 {
1139                     nRefCount += (*mi).second;
1140                     mi++;
1141                 }
1142
1143                 if (nRefCount == 0 && !fShutdown)
1144                 {
1145                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1146                     if (mi != mapFileUseCount.end())
1147                     {
1148                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1149                         printf("Flushing wallet.dat\n");
1150                         nLastFlushed = nWalletDBUpdated;
1151                         int64 nStart = GetTimeMillis();
1152
1153                         // Flush wallet.dat so it's self contained
1154                         CloseDb(strFile);
1155                         dbenv.txn_checkpoint(0, 0, 0);
1156                         dbenv.lsn_reset(strFile.c_str(), 0);
1157
1158                         mapFileUseCount.erase(mi++);
1159                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1160                     }
1161                 }
1162             }
1163         }
1164     }
1165 }
1166
1167 bool BackupWallet(const CWallet& wallet, const string& strDest)
1168 {
1169     if (!wallet.fFileBacked)
1170         return false;
1171     while (!fShutdown)
1172     {
1173         CRITICAL_BLOCK(cs_db)
1174         {
1175             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1176             {
1177                 // Flush log data to the dat file
1178                 CloseDb(wallet.strWalletFile);
1179                 dbenv.txn_checkpoint(0, 0, 0);
1180                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1181                 mapFileUseCount.erase(wallet.strWalletFile);
1182
1183                 // Copy wallet.dat
1184                 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1185                 filesystem::path pathDest(strDest);
1186                 if (filesystem::is_directory(pathDest))
1187                     pathDest = pathDest / wallet.strWalletFile;
1188
1189                 try {
1190 #if BOOST_VERSION >= 104000
1191                     filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1192 #else
1193                     filesystem::copy_file(pathSrc, pathDest);
1194 #endif
1195                     printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1196                     return true;
1197                 } catch(const filesystem::filesystem_error &e) {
1198                     printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
1199                     return false;
1200                 }
1201             }
1202         }
1203         Sleep(100);
1204     }
1205     return false;
1206 }