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