fix warnings: suggest explicit braces to avoid ambiguous 'else' [-Wparentheses]
[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().string().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             filesystem::path pathDataDir = GetDataDir();
82             filesystem::path pathLogDir = pathDataDir / "database";
83             filesystem::create_directory(pathLogDir);
84             filesystem::path pathErrorFile = pathDataDir / "db.log";
85             printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
86
87             int nDbCache = GetArg("-dbcache", 25);
88             dbenv.set_lg_dir(pathLogDir.string().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(pathErrorFile.string().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(pathDataDir.string().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                     {
646                         BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
647                         {
648                             if (!txpos.IsNull())
649                             {
650                                 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
651                                 if (!mapBlockPos.count(posFind))
652                                 {
653                                     printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
654                                     pindexFork = pindex->pprev;
655                                 }
656                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
657                                 if (nCheckLevel>5)
658                                 {
659                                     CTransaction txSpend;
660                                     if (!txSpend.ReadFromDisk(txpos))
661                                     {
662                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
663                                         pindexFork = pindex->pprev;
664                                     }
665                                     else if (!txSpend.CheckTransaction())
666                                     {
667                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
668                                         pindexFork = pindex->pprev;
669                                     }
670                                     else
671                                     {
672                                         bool fFound = false;
673                                         BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
674                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
675                                                 fFound = true;
676                                         if (!fFound)
677                                         {
678                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
679                                             pindexFork = pindex->pprev;
680                                         }
681                                     }
682                                 }
683                             }
684                             nOutput++;
685                         }
686                     }
687                 }
688                 // check level 5: check whether all prevouts are marked spent
689                 if (nCheckLevel>4)
690                 {
691                      BOOST_FOREACH(const CTxIn &txin, tx.vin)
692                      {
693                           CTxIndex txindex;
694                           if (ReadTxIndex(txin.prevout.hash, txindex))
695                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
696                               {
697                                   printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
698                                   pindexFork = pindex->pprev;
699                               }
700                      }
701                 }
702             }
703         }
704     }
705     if (pindexFork)
706     {
707         // Reorg back to the fork
708         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
709         CBlock block;
710         if (!block.ReadFromDisk(pindexFork))
711             return error("LoadBlockIndex() : block.ReadFromDisk failed");
712         CTxDB txdb;
713         block.SetBestChain(txdb, pindexFork);
714     }
715
716     return true;
717 }
718
719
720
721
722
723 //
724 // CAddrDB
725 //
726
727 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
728 {
729     return Write(string("addrman"), addrman);
730 }
731
732 bool CAddrDB::LoadAddresses()
733 {
734     if (Read(string("addrman"), addrman))
735     {
736         printf("Loaded %i addresses\n", addrman.size());
737         return true;
738     }
739     
740     // Read pre-0.6 addr records
741
742     vector<CAddress> vAddr;
743     vector<vector<unsigned char> > vDelete;
744
745     // Get cursor
746     Dbc* pcursor = GetCursor();
747     if (!pcursor)
748         return false;
749
750     loop
751     {
752         // Read next record
753         CDataStream ssKey;
754         CDataStream ssValue;
755         int ret = ReadAtCursor(pcursor, ssKey, ssValue);
756         if (ret == DB_NOTFOUND)
757             break;
758         else if (ret != 0)
759             return false;
760
761         // Unserialize
762         string strType;
763         ssKey >> strType;
764         if (strType == "addr")
765         {
766             CAddress addr;
767             ssValue >> addr;
768             vAddr.push_back(addr);
769         }
770     }
771     pcursor->close();
772
773     addrman.Add(vAddr, CNetAddr("0.0.0.0"));
774     printf("Loaded %i addresses\n", addrman.size());
775
776     // Note: old records left; we ran into hangs-on-startup
777     // bugs for some users who (we think) were running after
778     // an unclean shutdown.
779
780     return true;
781 }
782
783 bool LoadAddresses()
784 {
785     return CAddrDB("cr+").LoadAddresses();
786 }
787
788
789
790
791 //
792 // CWalletDB
793 //
794
795 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
796 {
797     nWalletDBUpdated++;
798     return Write(make_pair(string("name"), strAddress), strName);
799 }
800
801 bool CWalletDB::EraseName(const string& strAddress)
802 {
803     // This should only be used for sending addresses, never for receiving addresses,
804     // receiving addresses must always have an address book entry if they're not change return.
805     nWalletDBUpdated++;
806     return Erase(make_pair(string("name"), strAddress));
807 }
808
809 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
810 {
811     account.SetNull();
812     return Read(make_pair(string("acc"), strAccount), account);
813 }
814
815 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
816 {
817     return Write(make_pair(string("acc"), strAccount), account);
818 }
819
820 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
821 {
822     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
823 }
824
825 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
826 {
827     list<CAccountingEntry> entries;
828     ListAccountCreditDebit(strAccount, entries);
829
830     int64 nCreditDebit = 0;
831     BOOST_FOREACH (const CAccountingEntry& entry, entries)
832         nCreditDebit += entry.nCreditDebit;
833
834     return nCreditDebit;
835 }
836
837 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
838 {
839     bool fAllAccounts = (strAccount == "*");
840
841     Dbc* pcursor = GetCursor();
842     if (!pcursor)
843         throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
844     unsigned int fFlags = DB_SET_RANGE;
845     loop
846     {
847         // Read next record
848         CDataStream ssKey;
849         if (fFlags == DB_SET_RANGE)
850             ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
851         CDataStream ssValue;
852         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
853         fFlags = DB_NEXT;
854         if (ret == DB_NOTFOUND)
855             break;
856         else if (ret != 0)
857         {
858             pcursor->close();
859             throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
860         }
861
862         // Unserialize
863         string strType;
864         ssKey >> strType;
865         if (strType != "acentry")
866             break;
867         CAccountingEntry acentry;
868         ssKey >> acentry.strAccount;
869         if (!fAllAccounts && acentry.strAccount != strAccount)
870             break;
871
872         ssValue >> acentry;
873         entries.push_back(acentry);
874     }
875
876     pcursor->close();
877 }
878
879
880 int CWalletDB::LoadWallet(CWallet* pwallet)
881 {
882     pwallet->vchDefaultKey.clear();
883     int nFileVersion = 0;
884     vector<uint256> vWalletUpgrade;
885     bool fIsEncrypted = false;
886
887     //// todo: shouldn't we catch exceptions and try to recover and continue?
888     {
889         LOCK(pwallet->cs_wallet);
890         int nMinVersion = 0;
891         if (Read((string)"minversion", nMinVersion))
892         {
893             if (nMinVersion > CLIENT_VERSION)
894                 return DB_TOO_NEW;
895             pwallet->LoadMinVersion(nMinVersion);
896         }
897
898         // Get cursor
899         Dbc* pcursor = GetCursor();
900         if (!pcursor)
901         {
902             printf("Error getting wallet database cursor\n");
903             return DB_CORRUPT;
904         }
905
906         loop
907         {
908             // Read next record
909             CDataStream ssKey;
910             CDataStream ssValue;
911             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
912             if (ret == DB_NOTFOUND)
913                 break;
914             else if (ret != 0)
915             {
916                 printf("Error reading next record from wallet database\n");
917                 return DB_CORRUPT;
918             }
919
920             // Unserialize
921             // Taking advantage of the fact that pair serialization
922             // is just the two items serialized one after the other
923             string strType;
924             ssKey >> strType;
925             if (strType == "name")
926             {
927                 string strAddress;
928                 ssKey >> strAddress;
929                 ssValue >> pwallet->mapAddressBook[strAddress];
930             }
931             else if (strType == "tx")
932             {
933                 uint256 hash;
934                 ssKey >> hash;
935                 CWalletTx& wtx = pwallet->mapWallet[hash];
936                 ssValue >> wtx;
937                 wtx.BindWallet(pwallet);
938
939                 if (wtx.GetHash() != hash)
940                     printf("Error in wallet.dat, hash mismatch\n");
941
942                 // Undo serialize changes in 31600
943                 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
944                 {
945                     if (!ssValue.empty())
946                     {
947                         char fTmp;
948                         char fUnused;
949                         ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
950                         printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
951                         wtx.fTimeReceivedIsTxTime = fTmp;
952                     }
953                     else
954                     {
955                         printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
956                         wtx.fTimeReceivedIsTxTime = 0;
957                     }
958                     vWalletUpgrade.push_back(hash);
959                 }
960
961                 //// debug print
962                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
963                 //printf(" %12I64d  %s  %s  %s\n",
964                 //    wtx.vout[0].nValue,
965                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
966                 //    wtx.hashBlock.ToString().substr(0,20).c_str(),
967                 //    wtx.mapValue["message"].c_str());
968             }
969             else if (strType == "acentry")
970             {
971                 string strAccount;
972                 ssKey >> strAccount;
973                 uint64 nNumber;
974                 ssKey >> nNumber;
975                 if (nNumber > nAccountingEntryNumber)
976                     nAccountingEntryNumber = nNumber;
977             }
978             else if (strType == "key" || strType == "wkey")
979             {
980                 vector<unsigned char> vchPubKey;
981                 ssKey >> vchPubKey;
982                 CKey key;
983                 if (strType == "key")
984                 {
985                     CPrivKey pkey;
986                     ssValue >> pkey;
987                     key.SetPubKey(vchPubKey);
988                     key.SetPrivKey(pkey);
989                     if (key.GetPubKey() != vchPubKey)
990                     {
991                         printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
992                         return DB_CORRUPT;
993                     }
994                     if (!key.IsValid())
995                     {
996                         printf("Error reading wallet database: invalid CPrivKey\n");
997                         return DB_CORRUPT;
998                     }
999                 }
1000                 else
1001                 {
1002                     CWalletKey wkey;
1003                     ssValue >> wkey;
1004                     key.SetPubKey(vchPubKey);
1005                     key.SetPrivKey(wkey.vchPrivKey);
1006                     if (key.GetPubKey() != vchPubKey)
1007                     {
1008                         printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1009                         return DB_CORRUPT;
1010                     }
1011                     if (!key.IsValid())
1012                     {
1013                         printf("Error reading wallet database: invalid CWalletKey\n");
1014                         return DB_CORRUPT;
1015                     }
1016                 }
1017                 if (!pwallet->LoadKey(key))
1018                 {
1019                     printf("Error reading wallet database: LoadKey failed\n");
1020                     return DB_CORRUPT;
1021                 }
1022             }
1023             else if (strType == "mkey")
1024             {
1025                 unsigned int nID;
1026                 ssKey >> nID;
1027                 CMasterKey kMasterKey;
1028                 ssValue >> kMasterKey;
1029                 if(pwallet->mapMasterKeys.count(nID) != 0)
1030                 {
1031                     printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1032                     return DB_CORRUPT;
1033                 }
1034                 pwallet->mapMasterKeys[nID] = kMasterKey;
1035                 if (pwallet->nMasterKeyMaxID < nID)
1036                     pwallet->nMasterKeyMaxID = nID;
1037             }
1038             else if (strType == "ckey")
1039             {
1040                 vector<unsigned char> vchPubKey;
1041                 ssKey >> vchPubKey;
1042                 vector<unsigned char> vchPrivKey;
1043                 ssValue >> vchPrivKey;
1044                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1045                 {
1046                     printf("Error reading wallet database: LoadCryptedKey failed\n");
1047                     return DB_CORRUPT;
1048                 }
1049                 fIsEncrypted = true;
1050             }
1051             else if (strType == "defaultkey")
1052             {
1053                 ssValue >> pwallet->vchDefaultKey;
1054             }
1055             else if (strType == "pool")
1056             {
1057                 int64 nIndex;
1058                 ssKey >> nIndex;
1059                 pwallet->setKeyPool.insert(nIndex);
1060             }
1061             else if (strType == "version")
1062             {
1063                 ssValue >> nFileVersion;
1064                 if (nFileVersion == 10300)
1065                     nFileVersion = 300;
1066             }
1067             else if (strType == "cscript")
1068             {
1069                 uint160 hash;
1070                 ssKey >> hash;
1071                 CScript script;
1072                 ssValue >> script;
1073                 if (!pwallet->LoadCScript(script))
1074                 {
1075                     printf("Error reading wallet database: LoadCScript failed\n");
1076                     return DB_CORRUPT;
1077                 }
1078             }
1079         }
1080         pcursor->close();
1081     }
1082
1083     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1084         WriteTx(hash, pwallet->mapWallet[hash]);
1085
1086     printf("nFileVersion = %d\n", nFileVersion);
1087
1088
1089     // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1090     if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1091         return DB_NEED_REWRITE;
1092
1093     if (nFileVersion < CLIENT_VERSION) // Update
1094         WriteVersion(CLIENT_VERSION);
1095
1096     return DB_LOAD_OK;
1097 }
1098
1099 void ThreadFlushWalletDB(void* parg)
1100 {
1101     const string& strFile = ((const string*)parg)[0];
1102     static bool fOneThread;
1103     if (fOneThread)
1104         return;
1105     fOneThread = true;
1106     if (!GetBoolArg("-flushwallet", true))
1107         return;
1108
1109     unsigned int nLastSeen = nWalletDBUpdated;
1110     unsigned int nLastFlushed = nWalletDBUpdated;
1111     int64 nLastWalletUpdate = GetTime();
1112     while (!fShutdown)
1113     {
1114         Sleep(500);
1115
1116         if (nLastSeen != nWalletDBUpdated)
1117         {
1118             nLastSeen = nWalletDBUpdated;
1119             nLastWalletUpdate = GetTime();
1120         }
1121
1122         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1123         {
1124             TRY_LOCK(cs_db,lockDb);
1125             if (lockDb)
1126             {
1127                 // Don't do this if any databases are in use
1128                 int nRefCount = 0;
1129                 map<string, int>::iterator mi = mapFileUseCount.begin();
1130                 while (mi != mapFileUseCount.end())
1131                 {
1132                     nRefCount += (*mi).second;
1133                     mi++;
1134                 }
1135
1136                 if (nRefCount == 0 && !fShutdown)
1137                 {
1138                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1139                     if (mi != mapFileUseCount.end())
1140                     {
1141                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1142                         printf("Flushing wallet.dat\n");
1143                         nLastFlushed = nWalletDBUpdated;
1144                         int64 nStart = GetTimeMillis();
1145
1146                         // Flush wallet.dat so it's self contained
1147                         CloseDb(strFile);
1148                         dbenv.txn_checkpoint(0, 0, 0);
1149                         dbenv.lsn_reset(strFile.c_str(), 0);
1150
1151                         mapFileUseCount.erase(mi++);
1152                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1153                     }
1154                 }
1155             }
1156         }
1157     }
1158 }
1159
1160 bool BackupWallet(const CWallet& wallet, const string& strDest)
1161 {
1162     if (!wallet.fFileBacked)
1163         return false;
1164     while (!fShutdown)
1165     {
1166         {
1167             LOCK(cs_db);
1168             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1169             {
1170                 // Flush log data to the dat file
1171                 CloseDb(wallet.strWalletFile);
1172                 dbenv.txn_checkpoint(0, 0, 0);
1173                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1174                 mapFileUseCount.erase(wallet.strWalletFile);
1175
1176                 // Copy wallet.dat
1177                 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
1178                 filesystem::path pathDest(strDest);
1179                 if (filesystem::is_directory(pathDest))
1180                     pathDest /= wallet.strWalletFile;
1181
1182                 try {
1183 #if BOOST_VERSION >= 104000
1184                     filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1185 #else
1186                     filesystem::copy_file(pathSrc, pathDest);
1187 #endif
1188                     printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1189                     return true;
1190                 } catch(const filesystem::filesystem_error &e) {
1191                     printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
1192                     return false;
1193                 }
1194             }
1195         }
1196         Sleep(100);
1197     }
1198     return false;
1199 }