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