Merge pull request #458 from TheBlueMatt/copyright
[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 class CDBInit
32 {
33 public:
34     CDBInit()
35     {
36     }
37     ~CDBInit()
38     {
39         if (fDbEnvInit)
40         {
41             dbenv.close(0);
42             fDbEnvInit = false;
43         }
44     }
45 }
46 instance_of_cdbinit;
47
48
49 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
50 {
51     int ret;
52     if (pszFile == NULL)
53         return;
54
55     fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
56     bool fCreate = strchr(pszMode, 'c');
57     unsigned int nFlags = DB_THREAD;
58     if (fCreate)
59         nFlags |= DB_CREATE;
60
61     CRITICAL_BLOCK(cs_db)
62     {
63         if (!fDbEnvInit)
64         {
65             if (fShutdown)
66                 return;
67             string strDataDir = GetDataDir();
68             string strLogDir = strDataDir + "/database";
69             filesystem::create_directory(strLogDir.c_str());
70             string strErrorFile = strDataDir + "/db.log";
71             printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
72
73             dbenv.set_lg_dir(strLogDir.c_str());
74             dbenv.set_lg_max(10000000);
75             dbenv.set_lk_max_locks(10000);
76             dbenv.set_lk_max_objects(10000);
77             dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
78             dbenv.set_flags(DB_AUTO_COMMIT, 1);
79             ret = dbenv.open(strDataDir.c_str(),
80                              DB_CREATE     |
81                              DB_INIT_LOCK  |
82                              DB_INIT_LOG   |
83                              DB_INIT_MPOOL |
84                              DB_INIT_TXN   |
85                              DB_THREAD     |
86                              DB_RECOVER,
87                              S_IRUSR | S_IWUSR);
88             if (ret > 0)
89                 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
90             fDbEnvInit = true;
91         }
92
93         strFile = pszFile;
94         ++mapFileUseCount[strFile];
95         pdb = mapDb[strFile];
96         if (pdb == NULL)
97         {
98             pdb = new Db(&dbenv, 0);
99
100             ret = pdb->open(NULL,      // Txn pointer
101                             pszFile,   // Filename
102                             "main",    // Logical db name
103                             DB_BTREE,  // Database type
104                             nFlags,    // Flags
105                             0);
106
107             if (ret > 0)
108             {
109                 delete pdb;
110                 pdb = NULL;
111                 CRITICAL_BLOCK(cs_db)
112                     --mapFileUseCount[strFile];
113                 strFile = "";
114                 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
115             }
116
117             if (fCreate && !Exists(string("version")))
118             {
119                 bool fTmp = fReadOnly;
120                 fReadOnly = false;
121                 WriteVersion(VERSION);
122                 fReadOnly = fTmp;
123             }
124
125             mapDb[strFile] = pdb;
126         }
127     }
128 }
129
130 void CDB::Close()
131 {
132     if (!pdb)
133         return;
134     if (!vTxn.empty())
135         vTxn.front()->abort();
136     vTxn.clear();
137     pdb = NULL;
138
139     // Flush database activity from memory pool to disk log
140     unsigned int nMinutes = 0;
141     if (fReadOnly)
142         nMinutes = 1;
143     if (strFile == "addr.dat")
144         nMinutes = 2;
145     if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
146         nMinutes = 1;
147     dbenv.txn_checkpoint(0, nMinutes, 0);
148
149     CRITICAL_BLOCK(cs_db)
150         --mapFileUseCount[strFile];
151 }
152
153 void static CloseDb(const string& strFile)
154 {
155     CRITICAL_BLOCK(cs_db)
156     {
157         if (mapDb[strFile] != NULL)
158         {
159             // Close the database handle
160             Db* pdb = mapDb[strFile];
161             pdb->close(0);
162             delete pdb;
163             mapDb[strFile] = NULL;
164         }
165     }
166 }
167
168 void DBFlush(bool fShutdown)
169 {
170     // Flush log data to the actual data file
171     //  on all files that are not in use
172     printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
173     if (!fDbEnvInit)
174         return;
175     CRITICAL_BLOCK(cs_db)
176     {
177         map<string, int>::iterator mi = mapFileUseCount.begin();
178         while (mi != mapFileUseCount.end())
179         {
180             string strFile = (*mi).first;
181             int nRefCount = (*mi).second;
182             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
183             if (nRefCount == 0)
184             {
185                 // Move log data to the dat file
186                 CloseDb(strFile);
187                 dbenv.txn_checkpoint(0, 0, 0);
188                 printf("%s flush\n", strFile.c_str());
189                 dbenv.lsn_reset(strFile.c_str(), 0);
190                 mapFileUseCount.erase(mi++);
191             }
192             else
193                 mi++;
194         }
195         if (fShutdown)
196         {
197             char** listp;
198             if (mapFileUseCount.empty())
199                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
200             dbenv.close(0);
201             fDbEnvInit = false;
202         }
203     }
204 }
205
206
207
208
209
210
211 //
212 // CTxDB
213 //
214
215 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
216 {
217     assert(!fClient);
218     txindex.SetNull();
219     return Read(make_pair(string("tx"), hash), txindex);
220 }
221
222 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
223 {
224     assert(!fClient);
225     return Write(make_pair(string("tx"), hash), txindex);
226 }
227
228 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
229 {
230     assert(!fClient);
231
232     // Add to tx index
233     uint256 hash = tx.GetHash();
234     CTxIndex txindex(pos, tx.vout.size());
235     return Write(make_pair(string("tx"), hash), txindex);
236 }
237
238 bool CTxDB::EraseTxIndex(const CTransaction& tx)
239 {
240     assert(!fClient);
241     uint256 hash = tx.GetHash();
242
243     return Erase(make_pair(string("tx"), hash));
244 }
245
246 bool CTxDB::ContainsTx(uint256 hash)
247 {
248     assert(!fClient);
249     return Exists(make_pair(string("tx"), hash));
250 }
251
252 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
253 {
254     assert(!fClient);
255     vtx.clear();
256
257     // Get cursor
258     Dbc* pcursor = GetCursor();
259     if (!pcursor)
260         return false;
261
262     unsigned int fFlags = DB_SET_RANGE;
263     loop
264     {
265         // Read next record
266         CDataStream ssKey;
267         if (fFlags == DB_SET_RANGE)
268             ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
269         CDataStream ssValue;
270         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
271         fFlags = DB_NEXT;
272         if (ret == DB_NOTFOUND)
273             break;
274         else if (ret != 0)
275         {
276             pcursor->close();
277             return false;
278         }
279
280         // Unserialize
281         string strType;
282         uint160 hashItem;
283         CDiskTxPos pos;
284         ssKey >> strType >> hashItem >> pos;
285         int nItemHeight;
286         ssValue >> nItemHeight;
287
288         // Read transaction
289         if (strType != "owner" || hashItem != hash160)
290             break;
291         if (nItemHeight >= nMinHeight)
292         {
293             vtx.resize(vtx.size()+1);
294             if (!vtx.back().ReadFromDisk(pos))
295             {
296                 pcursor->close();
297                 return false;
298             }
299         }
300     }
301
302     pcursor->close();
303     return true;
304 }
305
306 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
307 {
308     assert(!fClient);
309     tx.SetNull();
310     if (!ReadTxIndex(hash, txindex))
311         return false;
312     return (tx.ReadFromDisk(txindex.pos));
313 }
314
315 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
316 {
317     CTxIndex txindex;
318     return ReadDiskTx(hash, tx, txindex);
319 }
320
321 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
322 {
323     return ReadDiskTx(outpoint.hash, tx, txindex);
324 }
325
326 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
327 {
328     CTxIndex txindex;
329     return ReadDiskTx(outpoint.hash, tx, txindex);
330 }
331
332 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
333 {
334     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
335 }
336
337 bool CTxDB::EraseBlockIndex(uint256 hash)
338 {
339     return Erase(make_pair(string("blockindex"), hash));
340 }
341
342 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
343 {
344     return Read(string("hashBestChain"), hashBestChain);
345 }
346
347 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
348 {
349     return Write(string("hashBestChain"), hashBestChain);
350 }
351
352 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
353 {
354     return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
355 }
356
357 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
358 {
359     return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
360 }
361
362 CBlockIndex static * InsertBlockIndex(uint256 hash)
363 {
364     if (hash == 0)
365         return NULL;
366
367     // Return existing
368     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
369     if (mi != mapBlockIndex.end())
370         return (*mi).second;
371
372     // Create new
373     CBlockIndex* pindexNew = new CBlockIndex();
374     if (!pindexNew)
375         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
376     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
377     pindexNew->phashBlock = &((*mi).first);
378
379     return pindexNew;
380 }
381
382 bool CTxDB::LoadBlockIndex()
383 {
384     // Get database cursor
385     Dbc* pcursor = GetCursor();
386     if (!pcursor)
387         return false;
388
389     // Load mapBlockIndex
390     unsigned int fFlags = DB_SET_RANGE;
391     loop
392     {
393         // Read next record
394         CDataStream ssKey;
395         if (fFlags == DB_SET_RANGE)
396             ssKey << make_pair(string("blockindex"), uint256(0));
397         CDataStream ssValue;
398         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
399         fFlags = DB_NEXT;
400         if (ret == DB_NOTFOUND)
401             break;
402         else if (ret != 0)
403             return false;
404
405         // Unserialize
406         string strType;
407         ssKey >> strType;
408         if (strType == "blockindex")
409         {
410             CDiskBlockIndex diskindex;
411             ssValue >> diskindex;
412
413             // Construct block index object
414             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
415             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
416             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
417             pindexNew->nFile          = diskindex.nFile;
418             pindexNew->nBlockPos      = diskindex.nBlockPos;
419             pindexNew->nHeight        = diskindex.nHeight;
420             pindexNew->nVersion       = diskindex.nVersion;
421             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
422             pindexNew->nTime          = diskindex.nTime;
423             pindexNew->nBits          = diskindex.nBits;
424             pindexNew->nNonce         = diskindex.nNonce;
425
426             // Watch for genesis block
427             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
428                 pindexGenesisBlock = pindexNew;
429
430             if (!pindexNew->CheckIndex())
431                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
432         }
433         else
434         {
435             break;
436         }
437     }
438     pcursor->close();
439
440     // Calculate bnChainWork
441     vector<pair<int, CBlockIndex*> > vSortedByHeight;
442     vSortedByHeight.reserve(mapBlockIndex.size());
443     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
444     {
445         CBlockIndex* pindex = item.second;
446         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
447     }
448     sort(vSortedByHeight.begin(), vSortedByHeight.end());
449     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
450     {
451         CBlockIndex* pindex = item.second;
452         pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
453     }
454
455     // Load hashBestChain pointer to end of best chain
456     if (!ReadHashBestChain(hashBestChain))
457     {
458         if (pindexGenesisBlock == NULL)
459             return true;
460         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
461     }
462     if (!mapBlockIndex.count(hashBestChain))
463         return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
464     pindexBest = mapBlockIndex[hashBestChain];
465     nBestHeight = pindexBest->nHeight;
466     bnBestChainWork = pindexBest->bnChainWork;
467     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
468
469     // Load bnBestInvalidWork, OK if it doesn't exist
470     ReadBestInvalidWork(bnBestInvalidWork);
471
472     // Verify blocks in the best chain
473     CBlockIndex* pindexFork = NULL;
474     for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
475     {
476         if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
477             break;
478         CBlock block;
479         if (!block.ReadFromDisk(pindex))
480             return error("LoadBlockIndex() : block.ReadFromDisk failed");
481         if (!block.CheckBlock())
482         {
483             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
484             pindexFork = pindex->pprev;
485         }
486     }
487     if (pindexFork)
488     {
489         // Reorg back to the fork
490         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
491         CBlock block;
492         if (!block.ReadFromDisk(pindexFork))
493             return error("LoadBlockIndex() : block.ReadFromDisk failed");
494         CTxDB txdb;
495         block.SetBestChain(txdb, pindexFork);
496     }
497
498     return true;
499 }
500
501
502
503
504
505 //
506 // CAddrDB
507 //
508
509 bool CAddrDB::WriteAddress(const CAddress& addr)
510 {
511     return Write(make_pair(string("addr"), addr.GetKey()), addr);
512 }
513
514 bool CAddrDB::EraseAddress(const CAddress& addr)
515 {
516     return Erase(make_pair(string("addr"), addr.GetKey()));
517 }
518
519 bool CAddrDB::LoadAddresses()
520 {
521     CRITICAL_BLOCK(cs_mapAddresses)
522     {
523         // Load user provided addresses
524         CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
525         if (filein)
526         {
527             try
528             {
529                 char psz[1000];
530                 while (fgets(psz, sizeof(psz), filein))
531                 {
532                     CAddress addr(psz, false, NODE_NETWORK);
533                     addr.nTime = 0; // so it won't relay unless successfully connected
534                     if (addr.IsValid())
535                         AddAddress(addr);
536                 }
537             }
538             catch (...) { }
539         }
540
541         // Get cursor
542         Dbc* pcursor = GetCursor();
543         if (!pcursor)
544             return false;
545
546         loop
547         {
548             // Read next record
549             CDataStream ssKey;
550             CDataStream ssValue;
551             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
552             if (ret == DB_NOTFOUND)
553                 break;
554             else if (ret != 0)
555                 return false;
556
557             // Unserialize
558             string strType;
559             ssKey >> strType;
560             if (strType == "addr")
561             {
562                 CAddress addr;
563                 ssValue >> addr;
564                 mapAddresses.insert(make_pair(addr.GetKey(), addr));
565             }
566         }
567         pcursor->close();
568
569         printf("Loaded %d addresses\n", mapAddresses.size());
570     }
571
572     return true;
573 }
574
575 bool LoadAddresses()
576 {
577     return CAddrDB("cr+").LoadAddresses();
578 }
579
580
581
582
583 //
584 // CWalletDB
585 //
586
587 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
588 {
589     nWalletDBUpdated++;
590     return Write(make_pair(string("name"), strAddress), strName);
591 }
592
593 bool CWalletDB::EraseName(const string& strAddress)
594 {
595     // This should only be used for sending addresses, never for receiving addresses,
596     // receiving addresses must always have an address book entry if they're not change return.
597     nWalletDBUpdated++;
598     return Erase(make_pair(string("name"), strAddress));
599 }
600
601 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
602 {
603     account.SetNull();
604     return Read(make_pair(string("acc"), strAccount), account);
605 }
606
607 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
608 {
609     return Write(make_pair(string("acc"), strAccount), account);
610 }
611
612 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
613 {
614     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
615 }
616
617 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
618 {
619     list<CAccountingEntry> entries;
620     ListAccountCreditDebit(strAccount, entries);
621
622     int64 nCreditDebit = 0;
623     BOOST_FOREACH (const CAccountingEntry& entry, entries)
624         nCreditDebit += entry.nCreditDebit;
625
626     return nCreditDebit;
627 }
628
629 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
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 << boost::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 int 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_KeyStore)
688     {
689         // Get cursor
690         Dbc* pcursor = GetCursor();
691         if (!pcursor)
692             return DB_CORRUPT;
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 DB_CORRUPT;
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                 CKey key;
768                 if (strType == "key")
769                 {
770                     CPrivKey pkey;
771                     ssValue >> pkey;
772                     key.SetPrivKey(pkey);
773                 }
774                 else
775                 {
776                     CWalletKey wkey;
777                     ssValue >> wkey;
778                     key.SetPrivKey(wkey.vchPrivKey);
779                 }
780                 if (!pwallet->LoadKey(key))
781                     return DB_CORRUPT;
782             }
783             else if (strType == "mkey")
784             {
785                 unsigned int nID;
786                 ssKey >> nID;
787                 CMasterKey kMasterKey;
788                 ssValue >> kMasterKey;
789                 if(pwallet->mapMasterKeys.count(nID) != 0)
790                     return DB_CORRUPT;
791                 pwallet->mapMasterKeys[nID] = kMasterKey;
792                 if (pwallet->nMasterKeyMaxID < nID)
793                     pwallet->nMasterKeyMaxID = nID;
794             }
795             else if (strType == "ckey")
796             {
797                 vector<unsigned char> vchPubKey;
798                 ssKey >> vchPubKey;
799                 vector<unsigned char> vchPrivKey;
800                 ssValue >> vchPrivKey;
801                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
802                     return DB_CORRUPT;
803             }
804             else if (strType == "defaultkey")
805             {
806                 ssValue >> pwallet->vchDefaultKey;
807             }
808             else if (strType == "pool")
809             {
810                 int64 nIndex;
811                 ssKey >> nIndex;
812                 pwallet->setKeyPool.insert(nIndex);
813             }
814             else if (strType == "version")
815             {
816                 ssValue >> nFileVersion;
817                 if (nFileVersion == 10300)
818                     nFileVersion = 300;
819             }
820             else if (strType == "setting")
821             {
822                 string strKey;
823                 ssKey >> strKey;
824
825                 // Options
826 #ifndef GUI
827                 if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;
828 #endif
829                 if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;
830                 if (strKey == "fLimitProcessors")   ssValue >> fLimitProcessors;
831                 if (strKey == "nLimitProcessors")   ssValue >> nLimitProcessors;
832                 if (strKey == "fMinimizeToTray")    ssValue >> fMinimizeToTray;
833                 if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;
834                 if (strKey == "fUseProxy")          ssValue >> fUseProxy;
835                 if (strKey == "addrProxy")          ssValue >> addrProxy;
836                 if (fHaveUPnP && strKey == "fUseUPnP")           ssValue >> fUseUPnP;
837             }
838             else if (strType == "minversion")
839             {
840                 int nMinVersion = 0;
841                 ssValue >> nMinVersion;
842                 if (nMinVersion > VERSION)
843                     return DB_TOO_NEW;
844             }
845         }
846         pcursor->close();
847     }
848
849     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
850         WriteTx(hash, pwallet->mapWallet[hash]);
851
852     printf("nFileVersion = %d\n", nFileVersion);
853     printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
854     printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
855     printf("fMinimizeToTray = %d\n", fMinimizeToTray);
856     printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
857     printf("fUseProxy = %d\n", fUseProxy);
858     printf("addrProxy = %s\n", addrProxy.ToString().c_str());
859     if (fHaveUPnP)
860         printf("fUseUPnP = %d\n", fUseUPnP);
861
862
863     // Upgrade
864     if (nFileVersion < VERSION)
865     {
866         // Get rid of old debug.log file in current directory
867         if (nFileVersion <= 105 && !pszSetDataDir[0])
868             unlink("debug.log");
869
870         WriteVersion(VERSION);
871     }
872
873
874     return DB_LOAD_OK;
875 }
876
877 void ThreadFlushWalletDB(void* parg)
878 {
879     const string& strFile = ((const string*)parg)[0];
880     static bool fOneThread;
881     if (fOneThread)
882         return;
883     fOneThread = true;
884     if (mapArgs.count("-noflushwallet"))
885         return;
886
887     unsigned int nLastSeen = nWalletDBUpdated;
888     unsigned int nLastFlushed = nWalletDBUpdated;
889     int64 nLastWalletUpdate = GetTime();
890     while (!fShutdown)
891     {
892         Sleep(500);
893
894         if (nLastSeen != nWalletDBUpdated)
895         {
896             nLastSeen = nWalletDBUpdated;
897             nLastWalletUpdate = GetTime();
898         }
899
900         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
901         {
902             TRY_CRITICAL_BLOCK(cs_db)
903             {
904                 // Don't do this if any databases are in use
905                 int nRefCount = 0;
906                 map<string, int>::iterator mi = mapFileUseCount.begin();
907                 while (mi != mapFileUseCount.end())
908                 {
909                     nRefCount += (*mi).second;
910                     mi++;
911                 }
912
913                 if (nRefCount == 0 && !fShutdown)
914                 {
915                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
916                     if (mi != mapFileUseCount.end())
917                     {
918                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
919                         printf("Flushing wallet.dat\n");
920                         nLastFlushed = nWalletDBUpdated;
921                         int64 nStart = GetTimeMillis();
922
923                         // Flush wallet.dat so it's self contained
924                         CloseDb(strFile);
925                         dbenv.txn_checkpoint(0, 0, 0);
926                         dbenv.lsn_reset(strFile.c_str(), 0);
927
928                         mapFileUseCount.erase(mi++);
929                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
930                     }
931                 }
932             }
933         }
934     }
935 }
936
937 bool BackupWallet(const CWallet& wallet, const string& strDest)
938 {
939     if (!wallet.fFileBacked)
940         return false;
941     while (!fShutdown)
942     {
943         CRITICAL_BLOCK(cs_db)
944         {
945             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
946             {
947                 // Flush log data to the dat file
948                 CloseDb(wallet.strWalletFile);
949                 dbenv.txn_checkpoint(0, 0, 0);
950                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
951                 mapFileUseCount.erase(wallet.strWalletFile);
952
953                 // Copy wallet.dat
954                 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
955                 filesystem::path pathDest(strDest);
956                 if (filesystem::is_directory(pathDest))
957                     pathDest = pathDest / wallet.strWalletFile;
958 #if BOOST_VERSION >= 104000
959                 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
960 #else
961                 filesystem::copy_file(pathSrc, pathDest);
962 #endif
963                 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
964
965                 return true;
966             }
967         }
968         Sleep(100);
969     }
970     return false;
971 }