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         // Load user provided addresses
608         CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
609         if (filein)
610         {
611             try
612             {
613                 char psz[1000];
614                 while (fgets(psz, sizeof(psz), filein))
615                 {
616                     CAddress addr(psz, false, NODE_NETWORK);
617                     addr.nTime = 0; // so it won't relay unless successfully connected
618                     if (addr.IsValid())
619                         AddAddress(addr);
620                 }
621             }
622             catch (...) { }
623         }
624
625         // Get cursor
626         Dbc* pcursor = GetCursor();
627         if (!pcursor)
628             return false;
629
630         loop
631         {
632             // Read next record
633             CDataStream ssKey;
634             CDataStream ssValue;
635             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
636             if (ret == DB_NOTFOUND)
637                 break;
638             else if (ret != 0)
639                 return false;
640
641             // Unserialize
642             string strType;
643             ssKey >> strType;
644             if (strType == "addr")
645             {
646                 CAddress addr;
647                 ssValue >> addr;
648                 mapAddresses.insert(make_pair(addr.GetKey(), addr));
649             }
650         }
651         pcursor->close();
652
653         printf("Loaded %d addresses\n", mapAddresses.size());
654     }
655
656     return true;
657 }
658
659 bool LoadAddresses()
660 {
661     return CAddrDB("cr+").LoadAddresses();
662 }
663
664
665
666
667 //
668 // CWalletDB
669 //
670
671 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
672 {
673     nWalletDBUpdated++;
674     return Write(make_pair(string("name"), strAddress), strName);
675 }
676
677 bool CWalletDB::EraseName(const string& strAddress)
678 {
679     // This should only be used for sending addresses, never for receiving addresses,
680     // receiving addresses must always have an address book entry if they're not change return.
681     nWalletDBUpdated++;
682     return Erase(make_pair(string("name"), strAddress));
683 }
684
685 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
686 {
687     account.SetNull();
688     return Read(make_pair(string("acc"), strAccount), account);
689 }
690
691 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
692 {
693     return Write(make_pair(string("acc"), strAccount), account);
694 }
695
696 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
697 {
698     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
699 }
700
701 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
702 {
703     list<CAccountingEntry> entries;
704     ListAccountCreditDebit(strAccount, entries);
705
706     int64 nCreditDebit = 0;
707     BOOST_FOREACH (const CAccountingEntry& entry, entries)
708         nCreditDebit += entry.nCreditDebit;
709
710     return nCreditDebit;
711 }
712
713 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
714 {
715     bool fAllAccounts = (strAccount == "*");
716
717     Dbc* pcursor = GetCursor();
718     if (!pcursor)
719         throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
720     unsigned int fFlags = DB_SET_RANGE;
721     loop
722     {
723         // Read next record
724         CDataStream ssKey;
725         if (fFlags == DB_SET_RANGE)
726             ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
727         CDataStream ssValue;
728         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
729         fFlags = DB_NEXT;
730         if (ret == DB_NOTFOUND)
731             break;
732         else if (ret != 0)
733         {
734             pcursor->close();
735             throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
736         }
737
738         // Unserialize
739         string strType;
740         ssKey >> strType;
741         if (strType != "acentry")
742             break;
743         CAccountingEntry acentry;
744         ssKey >> acentry.strAccount;
745         if (!fAllAccounts && acentry.strAccount != strAccount)
746             break;
747
748         ssValue >> acentry;
749         entries.push_back(acentry);
750     }
751
752     pcursor->close();
753 }
754
755
756 int CWalletDB::LoadWallet(CWallet* pwallet)
757 {
758     pwallet->vchDefaultKey.clear();
759     int nFileVersion = 0;
760     vector<uint256> vWalletUpgrade;
761     bool fIsResilvered = false;
762     bool fIsEncrypted = false;
763
764     // Modify defaults
765 #ifndef __WXMSW__
766     // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
767     fMinimizeToTray = false;
768     fMinimizeOnClose = false;
769 #endif
770
771     //// todo: shouldn't we catch exceptions and try to recover and continue?
772     CRITICAL_BLOCK(pwallet->cs_wallet)
773     {
774         // Get cursor
775         Dbc* pcursor = GetCursor();
776         if (!pcursor)
777             return DB_CORRUPT;
778
779         loop
780         {
781             // Read next record
782             CDataStream ssKey;
783             CDataStream ssValue;
784             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
785             if (ret == DB_NOTFOUND)
786                 break;
787             else if (ret != 0)
788                 return DB_CORRUPT;
789
790             // Unserialize
791             // Taking advantage of the fact that pair serialization
792             // is just the two items serialized one after the other
793             string strType;
794             ssKey >> strType;
795             if (strType == "name")
796             {
797                 string strAddress;
798                 ssKey >> strAddress;
799                 ssValue >> pwallet->mapAddressBook[strAddress];
800             }
801             else if (strType == "tx")
802             {
803                 uint256 hash;
804                 ssKey >> hash;
805                 CWalletTx& wtx = pwallet->mapWallet[hash];
806                 ssValue >> wtx;
807                 wtx.pwallet = pwallet;
808
809                 if (wtx.GetHash() != hash)
810                     printf("Error in wallet.dat, hash mismatch\n");
811
812                 // Undo serialize changes in 31600
813                 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
814                 {
815                     if (!ssValue.empty())
816                     {
817                         char fTmp;
818                         char fUnused;
819                         ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
820                         printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
821                         wtx.fTimeReceivedIsTxTime = fTmp;
822                     }
823                     else
824                     {
825                         printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
826                         wtx.fTimeReceivedIsTxTime = 0;
827                     }
828                     vWalletUpgrade.push_back(hash);
829                 }
830
831                 //// debug print
832                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
833                 //printf(" %12I64d  %s  %s  %s\n",
834                 //    wtx.vout[0].nValue,
835                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
836                 //    wtx.hashBlock.ToString().substr(0,20).c_str(),
837                 //    wtx.mapValue["message"].c_str());
838             }
839             else if (strType == "acentry")
840             {
841                 string strAccount;
842                 ssKey >> strAccount;
843                 uint64 nNumber;
844                 ssKey >> nNumber;
845                 if (nNumber > nAccountingEntryNumber)
846                     nAccountingEntryNumber = nNumber;
847             }
848             else if (strType == "key" || strType == "wkey")
849             {
850                 vector<unsigned char> vchPubKey;
851                 ssKey >> vchPubKey;
852                 CKey key;
853                 if (strType == "key")
854                 {
855                     CPrivKey pkey;
856                     ssValue >> pkey;
857                     key.SetPrivKey(pkey);
858                 }
859                 else
860                 {
861                     CWalletKey wkey;
862                     ssValue >> wkey;
863                     key.SetPrivKey(wkey.vchPrivKey);
864                 }
865                 if (!pwallet->LoadKey(key))
866                     return DB_CORRUPT;
867             }
868             else if (strType == "mkey")
869             {
870                 unsigned int nID;
871                 ssKey >> nID;
872                 CMasterKey kMasterKey;
873                 ssValue >> kMasterKey;
874                 if(pwallet->mapMasterKeys.count(nID) != 0)
875                     return DB_CORRUPT;
876                 pwallet->mapMasterKeys[nID] = kMasterKey;
877                 if (pwallet->nMasterKeyMaxID < nID)
878                     pwallet->nMasterKeyMaxID = nID;
879             }
880             else if (strType == "ckey")
881             {
882                 vector<unsigned char> vchPubKey;
883                 ssKey >> vchPubKey;
884                 vector<unsigned char> vchPrivKey;
885                 ssValue >> vchPrivKey;
886                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
887                     return DB_CORRUPT;
888                 fIsEncrypted = true;
889             }
890             else if (strType == "defaultkey")
891             {
892                 ssValue >> pwallet->vchDefaultKey;
893             }
894             else if (strType == "pool")
895             {
896                 int64 nIndex;
897                 ssKey >> nIndex;
898                 pwallet->setKeyPool.insert(nIndex);
899             }
900             else if (strType == "version")
901             {
902                 ssValue >> nFileVersion;
903                 if (nFileVersion == 10300)
904                     nFileVersion = 300;
905             }
906             else if (strType == "setting")
907             {
908                 string strKey;
909                 ssKey >> strKey;
910
911                 // Options
912 #ifndef GUI
913                 if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;
914 #endif
915                 if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;
916                 if (strKey == "fLimitProcessors")   ssValue >> fLimitProcessors;
917                 if (strKey == "nLimitProcessors")   ssValue >> nLimitProcessors;
918                 if (strKey == "fMinimizeToTray")    ssValue >> fMinimizeToTray;
919                 if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;
920                 if (strKey == "fUseProxy")          ssValue >> fUseProxy;
921                 if (strKey == "addrProxy")          ssValue >> addrProxy;
922                 if (strKey == "fIsResilvered")      ssValue >> fIsResilvered;
923                 if (fHaveUPnP && strKey == "fUseUPnP")           ssValue >> fUseUPnP;
924             }
925             else if (strType == "minversion")
926             {
927                 int nMinVersion = 0;
928                 ssValue >> nMinVersion;
929                 if (nMinVersion > VERSION)
930                     return DB_TOO_NEW;
931             }
932         }
933         pcursor->close();
934     }
935
936     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
937         WriteTx(hash, pwallet->mapWallet[hash]);
938
939     printf("nFileVersion = %d\n", nFileVersion);
940     printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
941     printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
942     printf("fMinimizeToTray = %d\n", fMinimizeToTray);
943     printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
944     printf("fUseProxy = %d\n", fUseProxy);
945     printf("addrProxy = %s\n", addrProxy.ToString().c_str());
946     if (fHaveUPnP)
947         printf("fUseUPnP = %d\n", fUseUPnP);
948
949
950     // Upgrade
951     if (nFileVersion < VERSION)
952     {
953         // Get rid of old debug.log file in current directory
954         if (nFileVersion <= 105 && !pszSetDataDir[0])
955             unlink("debug.log");
956
957         WriteVersion(VERSION);
958     }
959
960     if (fIsEncrypted && !fIsResilvered)
961         return DB_NEED_RESILVER;
962
963     return DB_LOAD_OK;
964 }
965
966 void ThreadFlushWalletDB(void* parg)
967 {
968     const string& strFile = ((const string*)parg)[0];
969     static bool fOneThread;
970     if (fOneThread)
971         return;
972     fOneThread = true;
973     if (mapArgs.count("-noflushwallet"))
974         return;
975
976     unsigned int nLastSeen = nWalletDBUpdated;
977     unsigned int nLastFlushed = nWalletDBUpdated;
978     int64 nLastWalletUpdate = GetTime();
979     while (!fShutdown)
980     {
981         Sleep(500);
982
983         if (nLastSeen != nWalletDBUpdated)
984         {
985             nLastSeen = nWalletDBUpdated;
986             nLastWalletUpdate = GetTime();
987         }
988
989         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
990         {
991             TRY_CRITICAL_BLOCK(cs_db)
992             {
993                 // Don't do this if any databases are in use
994                 int nRefCount = 0;
995                 map<string, int>::iterator mi = mapFileUseCount.begin();
996                 while (mi != mapFileUseCount.end())
997                 {
998                     nRefCount += (*mi).second;
999                     mi++;
1000                 }
1001
1002                 if (nRefCount == 0 && !fShutdown)
1003                 {
1004                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1005                     if (mi != mapFileUseCount.end())
1006                     {
1007                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1008                         printf("Flushing wallet.dat\n");
1009                         nLastFlushed = nWalletDBUpdated;
1010                         int64 nStart = GetTimeMillis();
1011
1012                         // Flush wallet.dat so it's self contained
1013                         CloseDb(strFile);
1014                         dbenv.txn_checkpoint(0, 0, 0);
1015                         dbenv.lsn_reset(strFile.c_str(), 0);
1016
1017                         mapFileUseCount.erase(mi++);
1018                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1019                     }
1020                 }
1021             }
1022         }
1023     }
1024 }
1025
1026 bool BackupWallet(const CWallet& wallet, const string& strDest)
1027 {
1028     if (!wallet.fFileBacked)
1029         return false;
1030     while (!fShutdown)
1031     {
1032         CRITICAL_BLOCK(cs_db)
1033         {
1034             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1035             {
1036                 // Flush log data to the dat file
1037                 CloseDb(wallet.strWalletFile);
1038                 dbenv.txn_checkpoint(0, 0, 0);
1039                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1040                 mapFileUseCount.erase(wallet.strWalletFile);
1041
1042                 // Copy wallet.dat
1043                 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1044                 filesystem::path pathDest(strDest);
1045                 if (filesystem::is_directory(pathDest))
1046                     pathDest = pathDest / wallet.strWalletFile;
1047 #if BOOST_VERSION >= 104000
1048                 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1049 #else
1050                 filesystem::copy_file(pathSrc, pathDest);
1051 #endif
1052                 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1053
1054                 return true;
1055             }
1056         }
1057         Sleep(100);
1058     }
1059     return false;
1060 }