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