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