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