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