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