PPCoin: Include coinstake timestamp in duplicate-stake check
[novacoin.git] / src / db.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6
7 #include "headers.h"
8 #include "db.h"
9 #include "net.h"
10 #include "checkpoints.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 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(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 << 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::ReadBestInvalidTrust(uint64& nBestInvalidTrust)
464 {
465     return Read(string("nBestInvalidTrust"), nBestInvalidTrust);
466 }
467
468 bool CTxDB::WriteBestInvalidTrust(uint64 nBestInvalidTrust)
469 {
470     return Write(string("nBestInvalidTrust"), nBestInvalidTrust);
471 }
472
473 bool CTxDB::ReadAutoCheckpoint(int& nAutoCheckpoint)
474 {
475     return Read(string("nAutoCheckpoint"), nAutoCheckpoint);
476 }
477
478 bool CTxDB::WriteAutoCheckpoint(int nCheckpoint, bool fReset)
479 {
480     nCheckpoint = fReset? nCheckpoint : max(Checkpoints::nAutoCheckpoint, nCheckpoint);
481     return Write(string("nAutoCheckpoint"), nCheckpoint);
482 }
483
484 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
485 {
486     return Read(string("hashSyncCheckpoint"), hashCheckpoint);
487 }
488
489 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
490 {
491     return Write(string("hashSyncCheckpoint"), hashCheckpoint);
492 }
493
494 CBlockIndex static * InsertBlockIndex(uint256 hash)
495 {
496     if (hash == 0)
497         return NULL;
498
499     // Return existing
500     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
501     if (mi != mapBlockIndex.end())
502         return (*mi).second;
503
504     // Create new
505     CBlockIndex* pindexNew = new CBlockIndex();
506     if (!pindexNew)
507         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
508     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
509     pindexNew->phashBlock = &((*mi).first);
510
511     return pindexNew;
512 }
513
514 bool CTxDB::LoadBlockIndex()
515 {
516     // Get database cursor
517     Dbc* pcursor = GetCursor();
518     if (!pcursor)
519         return false;
520
521     // Load mapBlockIndex
522     unsigned int fFlags = DB_SET_RANGE;
523     loop
524     {
525         // Read next record
526         CDataStream ssKey;
527         if (fFlags == DB_SET_RANGE)
528             ssKey << make_pair(string("blockindex"), uint256(0));
529         CDataStream ssValue;
530         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
531         fFlags = DB_NEXT;
532         if (ret == DB_NOTFOUND)
533             break;
534         else if (ret != 0)
535             return false;
536
537         // Unserialize
538         string strType;
539         ssKey >> strType;
540         if (strType == "blockindex")
541         {
542             CDiskBlockIndex diskindex;
543             ssValue >> diskindex;
544
545             // Construct block index object
546             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
547             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
548             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
549             pindexNew->nFile          = diskindex.nFile;
550             pindexNew->nBlockPos      = diskindex.nBlockPos;
551             pindexNew->nChainTrust    = diskindex.nChainTrust;
552             pindexNew->nHeight        = diskindex.nHeight;
553             pindexNew->nCheckpoint    = diskindex.nCheckpoint;
554             pindexNew->fProofOfStake  = diskindex.fProofOfStake;
555             pindexNew->prevoutStake   = diskindex.prevoutStake;
556             pindexNew->nVersion       = diskindex.nVersion;
557             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
558             pindexNew->nTime          = diskindex.nTime;
559             pindexNew->nBits          = diskindex.nBits;
560             pindexNew->nNonce         = diskindex.nNonce;
561
562             // Watch for genesis block
563             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
564                 pindexGenesisBlock = pindexNew;
565
566             if (!pindexNew->CheckIndex())
567                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
568
569             // ppcoin: build setStakeSeen
570             if (pindexNew->fProofOfStake)
571                 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
572         }
573         else
574         {
575             break;
576         }
577     }
578     pcursor->close();
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     nBestChainTrust = pindexBest->nChainTrust;
592     printf("LoadBlockIndex(): hashBestChain=%s  height=%d  trust=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, nBestChainTrust);
593
594     // ppcoin: load nAutoCheckpoint
595     if (!ReadAutoCheckpoint(Checkpoints::nAutoCheckpoint))
596         return error("CTxDB::LoadBlockIndex() : nAutoCheckpoint not loaded");
597     printf("LoadBlockIndex(): automatic checkpoint at height=%d\n", Checkpoints::nAutoCheckpoint);
598
599     // ppcoin: load hashSyncCheckpoint
600     if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
601         return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
602     printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
603
604     // Load nBestInvalidTrust, OK if it doesn't exist
605     ReadBestInvalidTrust(nBestInvalidTrust);
606
607     // Verify blocks in the best chain
608     CBlockIndex* pindexFork = NULL;
609     for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
610     {
611         if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
612             break;
613         CBlock block;
614         if (!block.ReadFromDisk(pindex))
615             return error("LoadBlockIndex() : block.ReadFromDisk failed");
616         if (!block.CheckBlock())
617         {
618             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
619             pindexFork = pindex->pprev;
620         }
621     }
622     if (pindexFork)
623     {
624         // Reorg back to the fork
625         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
626         CBlock block;
627         if (!block.ReadFromDisk(pindexFork))
628             return error("LoadBlockIndex() : block.ReadFromDisk failed");
629         CTxDB txdb;
630         block.SetBestChain(txdb, pindexFork);
631     }
632
633     return true;
634 }
635
636
637
638
639
640 //
641 // CAddrDB
642 //
643
644 bool CAddrDB::WriteAddress(const CAddress& addr)
645 {
646     return Write(make_pair(string("addr"), addr.GetKey()), addr);
647 }
648
649 bool CAddrDB::EraseAddress(const CAddress& addr)
650 {
651     return Erase(make_pair(string("addr"), addr.GetKey()));
652 }
653
654 bool CAddrDB::LoadAddresses()
655 {
656     CRITICAL_BLOCK(cs_mapAddresses)
657     {
658         // Get cursor
659         Dbc* pcursor = GetCursor();
660         if (!pcursor)
661             return false;
662
663         loop
664         {
665             // Read next record
666             CDataStream ssKey;
667             CDataStream ssValue;
668             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
669             if (ret == DB_NOTFOUND)
670                 break;
671             else if (ret != 0)
672                 return false;
673
674             // Unserialize
675             string strType;
676             ssKey >> strType;
677             if (strType == "addr")
678             {
679                 CAddress addr;
680                 ssValue >> addr;
681                 mapAddresses.insert(make_pair(addr.GetKey(), addr));
682             }
683         }
684         pcursor->close();
685
686         printf("Loaded %d addresses\n", mapAddresses.size());
687     }
688
689     return true;
690 }
691
692 bool LoadAddresses()
693 {
694     return CAddrDB("cr+").LoadAddresses();
695 }
696
697
698
699
700 //
701 // CWalletDB
702 //
703
704 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
705 {
706     nWalletDBUpdated++;
707     return Write(make_pair(string("name"), strAddress), strName);
708 }
709
710 bool CWalletDB::EraseName(const string& strAddress)
711 {
712     // This should only be used for sending addresses, never for receiving addresses,
713     // receiving addresses must always have an address book entry if they're not change return.
714     nWalletDBUpdated++;
715     return Erase(make_pair(string("name"), strAddress));
716 }
717
718 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
719 {
720     account.SetNull();
721     return Read(make_pair(string("acc"), strAccount), account);
722 }
723
724 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
725 {
726     return Write(make_pair(string("acc"), strAccount), account);
727 }
728
729 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
730 {
731     return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
732 }
733
734 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
735 {
736     list<CAccountingEntry> entries;
737     ListAccountCreditDebit(strAccount, entries);
738
739     int64 nCreditDebit = 0;
740     BOOST_FOREACH (const CAccountingEntry& entry, entries)
741         nCreditDebit += entry.nCreditDebit;
742
743     return nCreditDebit;
744 }
745
746 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
747 {
748     bool fAllAccounts = (strAccount == "*");
749
750     Dbc* pcursor = GetCursor();
751     if (!pcursor)
752         throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
753     unsigned int fFlags = DB_SET_RANGE;
754     loop
755     {
756         // Read next record
757         CDataStream ssKey;
758         if (fFlags == DB_SET_RANGE)
759             ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
760         CDataStream ssValue;
761         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
762         fFlags = DB_NEXT;
763         if (ret == DB_NOTFOUND)
764             break;
765         else if (ret != 0)
766         {
767             pcursor->close();
768             throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
769         }
770
771         // Unserialize
772         string strType;
773         ssKey >> strType;
774         if (strType != "acentry")
775             break;
776         CAccountingEntry acentry;
777         ssKey >> acentry.strAccount;
778         if (!fAllAccounts && acentry.strAccount != strAccount)
779             break;
780
781         ssValue >> acentry;
782         entries.push_back(acentry);
783     }
784
785     pcursor->close();
786 }
787
788
789 int CWalletDB::LoadWallet(CWallet* pwallet)
790 {
791     pwallet->vchDefaultKey.clear();
792     int nFileVersion = 0;
793     vector<uint256> vWalletUpgrade;
794     bool fIsEncrypted = false;
795
796     // Modify defaults
797 #ifndef WIN32
798     // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
799     fMinimizeToTray = false;
800     fMinimizeOnClose = false;
801 #endif
802
803     //// todo: shouldn't we catch exceptions and try to recover and continue?
804     CRITICAL_BLOCK(pwallet->cs_wallet)
805     {
806         // Get cursor
807         Dbc* pcursor = GetCursor();
808         if (!pcursor)
809             return DB_CORRUPT;
810
811         loop
812         {
813             // Read next record
814             CDataStream ssKey;
815             CDataStream ssValue;
816             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
817             if (ret == DB_NOTFOUND)
818                 break;
819             else if (ret != 0)
820                 return DB_CORRUPT;
821
822             // Unserialize
823             // Taking advantage of the fact that pair serialization
824             // is just the two items serialized one after the other
825             string strType;
826             ssKey >> strType;
827             if (strType == "name")
828             {
829                 string strAddress;
830                 ssKey >> strAddress;
831                 ssValue >> pwallet->mapAddressBook[strAddress];
832             }
833             else if (strType == "tx")
834             {
835                 uint256 hash;
836                 ssKey >> hash;
837                 CWalletTx& wtx = pwallet->mapWallet[hash];
838                 ssValue >> wtx;
839                 wtx.pwallet = pwallet;
840
841                 if (wtx.GetHash() != hash)
842                     printf("Error in wallet.dat, hash mismatch\n");
843
844                 // Undo serialize changes in 31600
845                 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
846                 {
847                     if (!ssValue.empty())
848                     {
849                         char fTmp;
850                         char fUnused;
851                         ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
852                         printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
853                         wtx.fTimeReceivedIsTxTime = fTmp;
854                     }
855                     else
856                     {
857                         printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
858                         wtx.fTimeReceivedIsTxTime = 0;
859                     }
860                     vWalletUpgrade.push_back(hash);
861                 }
862
863                 //// debug print
864                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
865                 //printf(" %12I64d  %s  %s  %s\n",
866                 //    wtx.vout[0].nValue,
867                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
868                 //    wtx.hashBlock.ToString().substr(0,20).c_str(),
869                 //    wtx.mapValue["message"].c_str());
870             }
871             else if (strType == "acentry")
872             {
873                 string strAccount;
874                 ssKey >> strAccount;
875                 uint64 nNumber;
876                 ssKey >> nNumber;
877                 if (nNumber > nAccountingEntryNumber)
878                     nAccountingEntryNumber = nNumber;
879             }
880             else if (strType == "key" || strType == "wkey")
881             {
882                 vector<unsigned char> vchPubKey;
883                 ssKey >> vchPubKey;
884                 CKey key;
885                 if (strType == "key")
886                 {
887                     CPrivKey pkey;
888                     ssValue >> pkey;
889                     key.SetPrivKey(pkey);
890                 }
891                 else
892                 {
893                     CWalletKey wkey;
894                     ssValue >> wkey;
895                     key.SetPrivKey(wkey.vchPrivKey);
896                 }
897                 if (!pwallet->LoadKey(key))
898                     return DB_CORRUPT;
899             }
900             else if (strType == "mkey")
901             {
902                 unsigned int nID;
903                 ssKey >> nID;
904                 CMasterKey kMasterKey;
905                 ssValue >> kMasterKey;
906                 if(pwallet->mapMasterKeys.count(nID) != 0)
907                     return DB_CORRUPT;
908                 pwallet->mapMasterKeys[nID] = kMasterKey;
909                 if (pwallet->nMasterKeyMaxID < nID)
910                     pwallet->nMasterKeyMaxID = nID;
911             }
912             else if (strType == "ckey")
913             {
914                 vector<unsigned char> vchPubKey;
915                 ssKey >> vchPubKey;
916                 vector<unsigned char> vchPrivKey;
917                 ssValue >> vchPrivKey;
918                 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
919                     return DB_CORRUPT;
920                 fIsEncrypted = true;
921             }
922             else if (strType == "defaultkey")
923             {
924                 ssValue >> pwallet->vchDefaultKey;
925             }
926             else if (strType == "pool")
927             {
928                 int64 nIndex;
929                 ssKey >> nIndex;
930                 pwallet->setKeyPool.insert(nIndex);
931             }
932             else if (strType == "version")
933             {
934                 ssValue >> nFileVersion;
935                 if (nFileVersion == 10300)
936                     nFileVersion = 300;
937             }
938             else if (strType == "setting")
939             {
940                 string strKey;
941                 ssKey >> strKey;
942
943                 // Options
944 #ifndef QT_GUI
945                 if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;
946 #endif
947                 if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;
948                 if (strKey == "fLimitProcessors")   ssValue >> fLimitProcessors;
949                 if (strKey == "nLimitProcessors")   ssValue >> nLimitProcessors;
950                 if (strKey == "fMinimizeToTray")    ssValue >> fMinimizeToTray;
951                 if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;
952                 if (strKey == "fUseProxy")          ssValue >> fUseProxy;
953                 if (strKey == "addrProxy")          ssValue >> addrProxy;
954                 if (fHaveUPnP && strKey == "fUseUPnP")           ssValue >> fUseUPnP;
955                 if (strKey == "nBalanceReserve")    ssValue >> nBalanceReserve;
956             }
957             else if (strType == "minversion")
958             {
959                 int nMinVersion = 0;
960                 ssValue >> nMinVersion;
961                 if (nMinVersion > VERSION)
962                     return DB_TOO_NEW;
963             }
964         }
965         pcursor->close();
966     }
967
968     BOOST_FOREACH(uint256 hash, vWalletUpgrade)
969         WriteTx(hash, pwallet->mapWallet[hash]);
970
971     printf("nFileVersion = %d\n", nFileVersion);
972     printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
973     printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
974     printf("fMinimizeToTray = %d\n", fMinimizeToTray);
975     printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
976     printf("fUseProxy = %d\n", fUseProxy);
977     printf("addrProxy = %s\n", addrProxy.ToString().c_str());
978     if (fHaveUPnP)
979         printf("fUseUPnP = %d\n", fUseUPnP);
980
981
982     // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
983     if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
984         return DB_NEED_REWRITE;
985
986     if (nFileVersion < VERSION) // Update
987     {
988         // Get rid of old debug.log file in current directory
989         if (nFileVersion <= 105 && !pszSetDataDir[0])
990             unlink("debug.log");
991
992         WriteVersion(VERSION);
993     }
994
995     return DB_LOAD_OK;
996 }
997
998 void ThreadFlushWalletDB(void* parg)
999 {
1000     const string& strFile = ((const string*)parg)[0];
1001     static bool fOneThread;
1002     if (fOneThread)
1003         return;
1004     fOneThread = true;
1005     if (mapArgs.count("-noflushwallet"))
1006         return;
1007
1008     unsigned int nLastSeen = nWalletDBUpdated;
1009     unsigned int nLastFlushed = nWalletDBUpdated;
1010     int64 nLastWalletUpdate = GetTime();
1011     while (!fShutdown)
1012     {
1013         Sleep(500);
1014
1015         if (nLastSeen != nWalletDBUpdated)
1016         {
1017             nLastSeen = nWalletDBUpdated;
1018             nLastWalletUpdate = GetTime();
1019         }
1020
1021         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1022         {
1023             TRY_CRITICAL_BLOCK(cs_db)
1024             {
1025                 // Don't do this if any databases are in use
1026                 int nRefCount = 0;
1027                 map<string, int>::iterator mi = mapFileUseCount.begin();
1028                 while (mi != mapFileUseCount.end())
1029                 {
1030                     nRefCount += (*mi).second;
1031                     mi++;
1032                 }
1033
1034                 if (nRefCount == 0 && !fShutdown)
1035                 {
1036                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1037                     if (mi != mapFileUseCount.end())
1038                     {
1039                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1040                         printf("Flushing wallet.dat\n");
1041                         nLastFlushed = nWalletDBUpdated;
1042                         int64 nStart = GetTimeMillis();
1043
1044                         // Flush wallet.dat so it's self contained
1045                         CloseDb(strFile);
1046                         dbenv.txn_checkpoint(0, 0, 0);
1047                         dbenv.lsn_reset(strFile.c_str(), 0);
1048
1049                         mapFileUseCount.erase(mi++);
1050                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1051                     }
1052                 }
1053             }
1054         }
1055     }
1056 }
1057
1058 bool BackupWallet(const CWallet& wallet, const string& strDest)
1059 {
1060     if (!wallet.fFileBacked)
1061         return false;
1062     while (!fShutdown)
1063     {
1064         CRITICAL_BLOCK(cs_db)
1065         {
1066             if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1067             {
1068                 // Flush log data to the dat file
1069                 CloseDb(wallet.strWalletFile);
1070                 dbenv.txn_checkpoint(0, 0, 0);
1071                 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1072                 mapFileUseCount.erase(wallet.strWalletFile);
1073
1074                 // Copy wallet.dat
1075                 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1076                 filesystem::path pathDest(strDest);
1077                 if (filesystem::is_directory(pathDest))
1078                     pathDest = pathDest / wallet.strWalletFile;
1079 #if BOOST_VERSION >= 104000
1080                 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1081 #else
1082                 filesystem::copy_file(pathSrc, pathDest);
1083 #endif
1084                 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1085
1086                 return true;
1087             }
1088         }
1089         Sleep(100);
1090     }
1091     return false;
1092 }