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