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