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