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