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