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