Fix CRLF
[novacoin.git] / db.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4
5 #include "headers.h"
6
7 void ThreadFlushWalletDB(void* parg);
8
9
10 unsigned int nWalletDBUpdated;
11
12
13
14
15 //
16 // CDB
17 //
18
19 static CCriticalSection cs_db;
20 static bool fDbEnvInit = false;
21 DbEnv dbenv(0);
22 static map<string, int> mapFileUseCount;
23 static map<string, Db*> mapDb;
24
25 class CDBInit
26 {
27 public:
28     CDBInit()
29     {
30     }
31     ~CDBInit()
32     {
33         if (fDbEnvInit)
34         {
35             dbenv.close(0);
36             fDbEnvInit = false;
37         }
38     }
39 }
40 instance_of_cdbinit;
41
42
43 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
44 {
45     int ret;
46     if (pszFile == NULL)
47         return;
48
49     fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
50     bool fCreate = strchr(pszMode, 'c');
51     unsigned int nFlags = DB_THREAD;
52     if (fCreate)
53         nFlags |= DB_CREATE;
54
55     CRITICAL_BLOCK(cs_db)
56     {
57         if (!fDbEnvInit)
58         {
59             if (fShutdown)
60                 return;
61             string strDataDir = GetDataDir();
62             string strLogDir = strDataDir + "/database";
63             _mkdir(strLogDir.c_str());
64             string strErrorFile = strDataDir + "/db.log";
65             printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
66
67             dbenv.set_lg_dir(strLogDir.c_str());
68             dbenv.set_lg_max(10000000);
69             dbenv.set_lk_max_locks(10000);
70             dbenv.set_lk_max_objects(10000);
71             dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
72             dbenv.set_flags(DB_AUTO_COMMIT, 1);
73             ret = dbenv.open(strDataDir.c_str(),
74                              DB_CREATE     |
75                              DB_INIT_LOCK  |
76                              DB_INIT_LOG   |
77                              DB_INIT_MPOOL |
78                              DB_INIT_TXN   |
79                              DB_THREAD     |
80                              DB_PRIVATE    |
81                              DB_RECOVER,
82                              S_IRUSR | S_IWUSR);
83             if (ret > 0)
84                 throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));
85             fDbEnvInit = true;
86         }
87
88         strFile = pszFile;
89         ++mapFileUseCount[strFile];
90         pdb = mapDb[strFile];
91         if (pdb == NULL)
92         {
93             pdb = new Db(&dbenv, 0);
94
95             ret = pdb->open(NULL,      // Txn pointer
96                             pszFile,   // Filename
97                             "main",    // Logical db name
98                             DB_BTREE,  // Database type
99                             nFlags,    // Flags
100                             0);
101
102             if (ret > 0)
103             {
104                 delete pdb;
105                 pdb = NULL;
106                 CRITICAL_BLOCK(cs_db)
107                     --mapFileUseCount[strFile];
108                 strFile = "";
109                 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));
110             }
111
112             if (fCreate && !Exists(string("version")))
113             {
114                 bool fTmp = fReadOnly;
115                 fReadOnly = false;
116                 WriteVersion(VERSION);
117                 fReadOnly = fTmp;
118             }
119
120             mapDb[strFile] = pdb;
121         }
122     }
123 }
124
125 void CDB::Close()
126 {
127     if (!pdb)
128         return;
129     if (!vTxn.empty())
130         vTxn.front()->abort();
131     vTxn.clear();
132     pdb = NULL;
133     dbenv.txn_checkpoint(0, 0, 0);
134
135     CRITICAL_BLOCK(cs_db)
136         --mapFileUseCount[strFile];
137 }
138
139 void CloseDb(const string& strFile)
140 {
141     CRITICAL_BLOCK(cs_db)
142     {
143         if (mapDb[strFile] != NULL)
144         {
145             // Close the database handle
146             Db* pdb = mapDb[strFile];
147             pdb->close(0);
148             delete pdb;
149             mapDb[strFile] = NULL;
150         }
151     }
152 }
153
154 void DBFlush(bool fShutdown)
155 {
156     // Flush log data to the actual data file
157     //  on all files that are not in use
158     printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
159     if (!fDbEnvInit)
160         return;
161     CRITICAL_BLOCK(cs_db)
162     {
163         map<string, int>::iterator mi = mapFileUseCount.begin();
164         while (mi != mapFileUseCount.end())
165         {
166             string strFile = (*mi).first;
167             int nRefCount = (*mi).second;
168             printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
169             if (nRefCount == 0)
170             {
171                 // Move log data to the dat file
172                 CloseDb(strFile);
173                 dbenv.txn_checkpoint(0, 0, 0);
174                 printf("%s flush\n", strFile.c_str());
175                 dbenv.lsn_reset(strFile.c_str(), 0);
176                 mapFileUseCount.erase(mi++);
177             }
178             else
179                 mi++;
180         }
181         if (fShutdown)
182         {
183             char** listp;
184             if (mapFileUseCount.empty())
185                 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
186             dbenv.close(0);
187             fDbEnvInit = false;
188         }
189     }
190 }
191
192
193
194
195
196
197 //
198 // CTxDB
199 //
200
201 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
202 {
203     assert(!fClient);
204     txindex.SetNull();
205     return Read(make_pair(string("tx"), hash), txindex);
206 }
207
208 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
209 {
210     assert(!fClient);
211     return Write(make_pair(string("tx"), hash), txindex);
212 }
213
214 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
215 {
216     assert(!fClient);
217
218     // Add to tx index
219     uint256 hash = tx.GetHash();
220     CTxIndex txindex(pos, tx.vout.size());
221     return Write(make_pair(string("tx"), hash), txindex);
222 }
223
224 bool CTxDB::EraseTxIndex(const CTransaction& tx)
225 {
226     assert(!fClient);
227     uint256 hash = tx.GetHash();
228
229     return Erase(make_pair(string("tx"), hash));
230 }
231
232 bool CTxDB::ContainsTx(uint256 hash)
233 {
234     assert(!fClient);
235     return Exists(make_pair(string("tx"), hash));
236 }
237
238 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
239 {
240     assert(!fClient);
241     vtx.clear();
242
243     // Get cursor
244     Dbc* pcursor = GetCursor();
245     if (!pcursor)
246         return false;
247
248     unsigned int fFlags = DB_SET_RANGE;
249     loop
250     {
251         // Read next record
252         CDataStream ssKey;
253         if (fFlags == DB_SET_RANGE)
254             ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
255         CDataStream ssValue;
256         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
257         fFlags = DB_NEXT;
258         if (ret == DB_NOTFOUND)
259             break;
260         else if (ret != 0)
261         {
262             pcursor->close();
263             return false;
264         }
265
266         // Unserialize
267         string strType;
268         uint160 hashItem;
269         CDiskTxPos pos;
270         ssKey >> strType >> hashItem >> pos;
271         int nItemHeight;
272         ssValue >> nItemHeight;
273
274         // Read transaction
275         if (strType != "owner" || hashItem != hash160)
276             break;
277         if (nItemHeight >= nMinHeight)
278         {
279             vtx.resize(vtx.size()+1);
280             if (!vtx.back().ReadFromDisk(pos))
281             {
282                 pcursor->close();
283                 return false;
284             }
285         }
286     }
287
288     pcursor->close();
289     return true;
290 }
291
292 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
293 {
294     assert(!fClient);
295     tx.SetNull();
296     if (!ReadTxIndex(hash, txindex))
297         return false;
298     return (tx.ReadFromDisk(txindex.pos));
299 }
300
301 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
302 {
303     CTxIndex txindex;
304     return ReadDiskTx(hash, tx, txindex);
305 }
306
307 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
308 {
309     return ReadDiskTx(outpoint.hash, tx, txindex);
310 }
311
312 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
313 {
314     CTxIndex txindex;
315     return ReadDiskTx(outpoint.hash, tx, txindex);
316 }
317
318 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
319 {
320     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
321 }
322
323 bool CTxDB::EraseBlockIndex(uint256 hash)
324 {
325     return Erase(make_pair(string("blockindex"), hash));
326 }
327
328 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
329 {
330     return Read(string("hashBestChain"), hashBestChain);
331 }
332
333 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
334 {
335     return Write(string("hashBestChain"), hashBestChain);
336 }
337
338 CBlockIndex* InsertBlockIndex(uint256 hash)
339 {
340     if (hash == 0)
341         return NULL;
342
343     // Return existing
344     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
345     if (mi != mapBlockIndex.end())
346         return (*mi).second;
347
348     // Create new
349     CBlockIndex* pindexNew = new CBlockIndex();
350     if (!pindexNew)
351         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
352     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
353     pindexNew->phashBlock = &((*mi).first);
354
355     return pindexNew;
356 }
357
358 bool CTxDB::LoadBlockIndex()
359 {
360     // Get cursor
361     Dbc* pcursor = GetCursor();
362     if (!pcursor)
363         return false;
364
365     unsigned int fFlags = DB_SET_RANGE;
366     loop
367     {
368         // Read next record
369         CDataStream ssKey;
370         if (fFlags == DB_SET_RANGE)
371             ssKey << make_pair(string("blockindex"), uint256(0));
372         CDataStream ssValue;
373         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
374         fFlags = DB_NEXT;
375         if (ret == DB_NOTFOUND)
376             break;
377         else if (ret != 0)
378             return false;
379
380         // Unserialize
381         string strType;
382         ssKey >> strType;
383         if (strType == "blockindex")
384         {
385             CDiskBlockIndex diskindex;
386             ssValue >> diskindex;
387
388             // Construct block index object
389             CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
390             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
391             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
392             pindexNew->nFile          = diskindex.nFile;
393             pindexNew->nBlockPos      = diskindex.nBlockPos;
394             pindexNew->nHeight        = diskindex.nHeight;
395             pindexNew->nVersion       = diskindex.nVersion;
396             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
397             pindexNew->nTime          = diskindex.nTime;
398             pindexNew->nBits          = diskindex.nBits;
399             pindexNew->nNonce         = diskindex.nNonce;
400
401             // Watch for genesis block and best block
402             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
403                 pindexGenesisBlock = pindexNew;
404         }
405         else
406         {
407             break;
408         }
409     }
410     pcursor->close();
411
412     if (!ReadHashBestChain(hashBestChain))
413     {
414         if (pindexGenesisBlock == NULL)
415             return true;
416         return error("CTxDB::LoadBlockIndex() : hashBestChain not found");
417     }
418
419     if (!mapBlockIndex.count(hashBestChain))
420         return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found");
421     pindexBest = mapBlockIndex[hashBestChain];
422     nBestHeight = pindexBest->nHeight;
423     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
424
425     return true;
426 }
427
428
429
430
431
432 //
433 // CAddrDB
434 //
435
436 bool CAddrDB::WriteAddress(const CAddress& addr)
437 {
438     return Write(make_pair(string("addr"), addr.GetKey()), addr);
439 }
440
441 bool CAddrDB::LoadAddresses()
442 {
443     CRITICAL_BLOCK(cs_mapAddresses)
444     {
445         // Load user provided addresses
446         CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
447         if (filein)
448         {
449             try
450             {
451                 char psz[1000];
452                 while (fgets(psz, sizeof(psz), filein))
453                 {
454                     CAddress addr(psz, NODE_NETWORK);
455                     addr.nTime = 0; // so it won't relay unless successfully connected
456                     if (addr.IsValid())
457                         AddAddress(addr);
458                 }
459             }
460             catch (...) { }
461         }
462
463         // Get cursor
464         Dbc* pcursor = GetCursor();
465         if (!pcursor)
466             return false;
467
468         loop
469         {
470             // Read next record
471             CDataStream ssKey;
472             CDataStream ssValue;
473             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
474             if (ret == DB_NOTFOUND)
475                 break;
476             else if (ret != 0)
477                 return false;
478
479             // Unserialize
480             string strType;
481             ssKey >> strType;
482             if (strType == "addr")
483             {
484                 CAddress addr;
485                 ssValue >> addr;
486                 mapAddresses.insert(make_pair(addr.GetKey(), addr));
487             }
488         }
489         pcursor->close();
490
491         printf("Loaded %d addresses\n", mapAddresses.size());
492
493         // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,
494         // just need to call count here and it doesn't happen there.  The bug was the
495         // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.
496         mapAddresses.count(vector<unsigned char>(18));
497     }
498
499     return true;
500 }
501
502 bool LoadAddresses()
503 {
504     return CAddrDB("cr+").LoadAddresses();
505 }
506
507
508
509
510 //
511 // CWalletDB
512 //
513
514 bool CWalletDB::LoadWallet()
515 {
516     vchDefaultKey.clear();
517     int nFileVersion = 0;
518
519     // Modify defaults
520 #ifndef __WXMSW__
521     // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
522     fMinimizeToTray = false;
523     fMinimizeOnClose = false;
524 #endif
525
526     //// todo: shouldn't we catch exceptions and try to recover and continue?
527     CRITICAL_BLOCK(cs_mapKeys)
528     CRITICAL_BLOCK(cs_mapWallet)
529     {
530         // Get cursor
531         Dbc* pcursor = GetCursor();
532         if (!pcursor)
533             return false;
534
535         loop
536         {
537             // Read next record
538             CDataStream ssKey;
539             CDataStream ssValue;
540             int ret = ReadAtCursor(pcursor, ssKey, ssValue);
541             if (ret == DB_NOTFOUND)
542                 break;
543             else if (ret != 0)
544                 return false;
545
546             // Unserialize
547             // Taking advantage of the fact that pair serialization
548             // is just the two items serialized one after the other
549             string strType;
550             ssKey >> strType;
551             if (strType == "name")
552             {
553                 string strAddress;
554                 ssKey >> strAddress;
555                 ssValue >> mapAddressBook[strAddress];
556             }
557             else if (strType == "tx")
558             {
559                 uint256 hash;
560                 ssKey >> hash;
561                 CWalletTx& wtx = mapWallet[hash];
562                 ssValue >> wtx;
563
564                 if (wtx.GetHash() != hash)
565                     printf("Error in wallet.dat, hash mismatch\n");
566
567                 //// debug print
568                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());
569                 //printf(" %12I64d  %s  %s  %s\n",
570                 //    wtx.vout[0].nValue,
571                 //    DateTimeStrFormat("%x %H:%M:%S", wtx.nTime).c_str(),
572                 //    wtx.hashBlock.ToString().substr(0,16).c_str(),
573                 //    wtx.mapValue["message"].c_str());
574             }
575             else if (strType == "key" || strType == "wkey")
576             {
577                 vector<unsigned char> vchPubKey;
578                 ssKey >> vchPubKey;
579                 CWalletKey wkey;
580                 if (strType == "key")
581                     ssValue >> wkey.vchPrivKey;
582                 else
583                     ssValue >> wkey;
584
585                 mapKeys[vchPubKey] = wkey.vchPrivKey;
586                 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;
587             }
588             else if (strType == "defaultkey")
589             {
590                 ssValue >> vchDefaultKey;
591             }
592             else if (strType == "version")
593             {
594                 ssValue >> nFileVersion;
595             }
596             else if (strType == "setting")
597             {
598                 string strKey;
599                 ssKey >> strKey;
600
601                 // Menu state
602                 if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;
603
604                 // Options
605                 if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;
606                 if (strKey == "addrIncoming")       ssValue >> addrIncoming;
607                 if (strKey == "fLimitProcessors")   ssValue >> fLimitProcessors;
608                 if (strKey == "nLimitProcessors")   ssValue >> nLimitProcessors;
609                 if (strKey == "fMinimizeToTray")    ssValue >> fMinimizeToTray;
610                 if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;
611                 if (strKey == "fUseProxy")          ssValue >> fUseProxy;
612                 if (strKey == "addrProxy")          ssValue >> addrProxy;
613
614             }
615         }
616         pcursor->close();
617     }
618
619     printf("nFileVersion = %d\n", nFileVersion);
620     printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
621     printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
622     printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());
623     printf("fMinimizeToTray = %d\n", fMinimizeToTray);
624     printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
625     printf("fUseProxy = %d\n", fUseProxy);
626     printf("addrProxy = %s\n", addrProxy.ToString().c_str());
627
628
629     // The transaction fee setting won't be needed for many years to come.
630     // Setting it to zero here in case they set it to something in an earlier version.
631     if (nTransactionFee != 0)
632     {
633         nTransactionFee = 0;
634         WriteSetting("nTransactionFee", nTransactionFee);
635     }
636
637     // Upgrade
638     if (nFileVersion < VERSION)
639     {
640         // Get rid of old debug.log file in current directory
641         if (nFileVersion <= 105 && !pszSetDataDir[0])
642             unlink("debug.log");
643
644         WriteVersion(VERSION);
645     }
646
647     return true;
648 }
649
650 bool LoadWallet(bool& fFirstRunRet)
651 {
652     fFirstRunRet = false;
653     if (!CWalletDB("cr+").LoadWallet())
654         return false;
655     fFirstRunRet = vchDefaultKey.empty();
656
657     if (mapKeys.count(vchDefaultKey))
658     {
659         // Set keyUser
660         keyUser.SetPubKey(vchDefaultKey);
661         keyUser.SetPrivKey(mapKeys[vchDefaultKey]);
662     }
663     else
664     {
665         // Create new keyUser and set as default key
666         RandAddSeedPerfmon();
667         keyUser.MakeNewKey();
668         if (!AddKey(keyUser))
669             return false;
670         if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))
671             return false;
672         CWalletDB().WriteDefaultKey(keyUser.GetPubKey());
673     }
674
675     CreateThread(ThreadFlushWalletDB, NULL);
676     return true;
677 }
678
679 void ThreadFlushWalletDB(void* parg)
680 {
681     static bool fOneThread;
682     if (fOneThread)
683         return;
684     fOneThread = true;
685     if (mapArgs.count("-noflushwallet"))
686         return;
687
688     unsigned int nLastSeen = nWalletDBUpdated;
689     unsigned int nLastFlushed = nWalletDBUpdated;
690     int64 nLastWalletUpdate = GetTime();
691     while (!fShutdown)
692     {
693         Sleep(500);
694
695         if (nLastSeen != nWalletDBUpdated)
696         {
697             nLastSeen = nWalletDBUpdated;
698             nLastWalletUpdate = GetTime();
699         }
700
701         if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
702         {
703             TRY_CRITICAL_BLOCK(cs_db)
704             {
705                 // Don't do this if any databases are in use
706                 int nRefCount = 0;
707                 map<string, int>::iterator mi = mapFileUseCount.begin();
708                 while (mi != mapFileUseCount.end())
709                 {
710                     nRefCount += (*mi).second;
711                     mi++;
712                 }
713
714                 if (nRefCount == 0 && !fShutdown)
715                 {
716                     string strFile = "wallet.dat";
717                     map<string, int>::iterator mi = mapFileUseCount.find(strFile);
718                     if (mi != mapFileUseCount.end())
719                     {
720                         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
721                         printf("Flushing wallet.dat\n");
722                         nLastFlushed = nWalletDBUpdated;
723                         int64 nStart = GetTimeMillis();
724
725                         // Flush wallet.dat so it's self contained
726                         CloseDb(strFile);
727                         dbenv.txn_checkpoint(0, 0, 0);
728                         dbenv.lsn_reset(strFile.c_str(), 0);
729
730                         mapFileUseCount.erase(mi++);
731                         printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
732                     }
733                 }
734             }
735         }
736     }
737 }