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