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