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