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