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