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