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