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