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