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