1 // Copyright (c) 2009-2010 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
7 void ThreadFlushWalletDB(void* parg);
\r
10 unsigned int nWalletDBUpdated;
\r
19 static CCriticalSection cs_db;
\r
20 static bool fDbEnvInit = false;
\r
22 static map<string, int> mapFileUseCount;
\r
23 static map<string, Db*> mapDb;
\r
40 instance_of_cdbinit;
\r
43 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
\r
46 if (pszFile == NULL)
\r
49 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
\r
50 bool fCreate = strchr(pszMode, 'c');
\r
51 unsigned int nFlags = DB_THREAD;
\r
53 nFlags |= DB_CREATE;
\r
55 CRITICAL_BLOCK(cs_db)
\r
61 string strDataDir = GetDataDir();
\r
62 string strLogDir = strDataDir + "/database";
\r
63 _mkdir(strLogDir.c_str());
\r
64 string strErrorFile = strDataDir + "/db.log";
\r
65 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
\r
67 dbenv.set_lg_dir(strLogDir.c_str());
\r
68 dbenv.set_lg_max(10000000);
\r
69 dbenv.set_lk_max_locks(10000);
\r
70 dbenv.set_lk_max_objects(10000);
\r
71 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
\r
72 dbenv.set_flags(DB_AUTO_COMMIT, 1);
\r
73 ret = dbenv.open(strDataDir.c_str(),
\r
84 throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));
\r
89 ++mapFileUseCount[strFile];
\r
90 pdb = mapDb[strFile];
\r
93 pdb = new Db(&dbenv, 0);
\r
95 ret = pdb->open(NULL, // Txn pointer
\r
96 pszFile, // Filename
\r
97 "main", // Logical db name
\r
98 DB_BTREE, // Database type
\r
106 CRITICAL_BLOCK(cs_db)
\r
107 --mapFileUseCount[strFile];
\r
109 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));
\r
112 if (fCreate && !Exists(string("version")))
\r
114 bool fTmp = fReadOnly;
\r
116 WriteVersion(VERSION);
\r
120 mapDb[strFile] = pdb;
\r
130 vTxn.front()->abort();
\r
133 dbenv.txn_checkpoint(0, 0, 0);
\r
135 CRITICAL_BLOCK(cs_db)
\r
136 --mapFileUseCount[strFile];
\r
139 void CloseDb(const string& strFile)
\r
141 CRITICAL_BLOCK(cs_db)
\r
143 if (mapDb[strFile] != NULL)
\r
145 // Close the database handle
\r
146 Db* pdb = mapDb[strFile];
\r
149 mapDb[strFile] = NULL;
\r
154 void DBFlush(bool fShutdown)
\r
156 // Flush log data to the actual data file
\r
157 // on all files that are not in use
\r
158 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
\r
161 CRITICAL_BLOCK(cs_db)
\r
163 map<string, int>::iterator mi = mapFileUseCount.begin();
\r
164 while (mi != mapFileUseCount.end())
\r
166 string strFile = (*mi).first;
\r
167 int nRefCount = (*mi).second;
\r
168 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
\r
169 if (nRefCount == 0)
\r
171 // Move log data to the dat file
\r
173 dbenv.txn_checkpoint(0, 0, 0);
\r
174 printf("%s flush\n", strFile.c_str());
\r
175 dbenv.lsn_reset(strFile.c_str(), 0);
\r
176 mapFileUseCount.erase(mi++);
\r
184 if (mapFileUseCount.empty())
\r
185 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
\r
187 fDbEnvInit = false;
\r
201 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
\r
205 return Read(make_pair(string("tx"), hash), txindex);
\r
208 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
\r
211 return Write(make_pair(string("tx"), hash), txindex);
\r
214 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
\r
219 uint256 hash = tx.GetHash();
\r
220 CTxIndex txindex(pos, tx.vout.size());
\r
221 return Write(make_pair(string("tx"), hash), txindex);
\r
224 bool CTxDB::EraseTxIndex(const CTransaction& tx)
\r
227 uint256 hash = tx.GetHash();
\r
229 return Erase(make_pair(string("tx"), hash));
\r
232 bool CTxDB::ContainsTx(uint256 hash)
\r
235 return Exists(make_pair(string("tx"), hash));
\r
238 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
\r
244 Dbc* pcursor = GetCursor();
\r
248 unsigned int fFlags = DB_SET_RANGE;
\r
251 // Read next record
\r
253 if (fFlags == DB_SET_RANGE)
\r
254 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
\r
255 CDataStream ssValue;
\r
256 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
\r
258 if (ret == DB_NOTFOUND)
\r
270 ssKey >> strType >> hashItem >> pos;
\r
272 ssValue >> nItemHeight;
\r
274 // Read transaction
\r
275 if (strType != "owner" || hashItem != hash160)
\r
277 if (nItemHeight >= nMinHeight)
\r
279 vtx.resize(vtx.size()+1);
\r
280 if (!vtx.back().ReadFromDisk(pos))
\r
292 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
\r
296 if (!ReadTxIndex(hash, txindex))
\r
298 return (tx.ReadFromDisk(txindex.pos));
\r
301 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
\r
304 return ReadDiskTx(hash, tx, txindex);
\r
307 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
\r
309 return ReadDiskTx(outpoint.hash, tx, txindex);
\r
312 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
\r
315 return ReadDiskTx(outpoint.hash, tx, txindex);
\r
318 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
\r
320 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
\r
323 bool CTxDB::EraseBlockIndex(uint256 hash)
\r
325 return Erase(make_pair(string("blockindex"), hash));
\r
328 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
\r
330 return Read(string("hashBestChain"), hashBestChain);
\r
333 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
\r
335 return Write(string("hashBestChain"), hashBestChain);
\r
338 CBlockIndex* InsertBlockIndex(uint256 hash)
\r
344 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
345 if (mi != mapBlockIndex.end())
\r
346 return (*mi).second;
\r
349 CBlockIndex* pindexNew = new CBlockIndex();
\r
351 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
\r
352 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
\r
353 pindexNew->phashBlock = &((*mi).first);
\r
358 bool CTxDB::LoadBlockIndex()
\r
361 Dbc* pcursor = GetCursor();
\r
365 unsigned int fFlags = DB_SET_RANGE;
\r
368 // Read next record
\r
370 if (fFlags == DB_SET_RANGE)
\r
371 ssKey << make_pair(string("blockindex"), uint256(0));
\r
372 CDataStream ssValue;
\r
373 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
\r
375 if (ret == DB_NOTFOUND)
\r
383 if (strType == "blockindex")
\r
385 CDiskBlockIndex diskindex;
\r
386 ssValue >> diskindex;
\r
388 // Construct block index object
\r
389 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
\r
390 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
\r
391 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
\r
392 pindexNew->nFile = diskindex.nFile;
\r
393 pindexNew->nBlockPos = diskindex.nBlockPos;
\r
394 pindexNew->nHeight = diskindex.nHeight;
\r
395 pindexNew->nVersion = diskindex.nVersion;
\r
396 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
\r
397 pindexNew->nTime = diskindex.nTime;
\r
398 pindexNew->nBits = diskindex.nBits;
\r
399 pindexNew->nNonce = diskindex.nNonce;
\r
401 // Watch for genesis block and best block
\r
402 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
\r
403 pindexGenesisBlock = pindexNew;
\r
412 if (!ReadHashBestChain(hashBestChain))
\r
414 if (pindexGenesisBlock == NULL)
\r
416 return error("CTxDB::LoadBlockIndex() : hashBestChain not found");
\r
419 if (!mapBlockIndex.count(hashBestChain))
\r
420 return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found");
\r
421 pindexBest = mapBlockIndex[hashBestChain];
\r
422 nBestHeight = pindexBest->nHeight;
\r
423 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
\r
436 bool CAddrDB::WriteAddress(const CAddress& addr)
\r
438 return Write(make_pair(string("addr"), addr.GetKey()), addr);
\r
441 bool CAddrDB::LoadAddresses()
\r
443 CRITICAL_BLOCK(cs_mapAddresses)
\r
445 // Load user provided addresses
\r
446 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
\r
452 while (fgets(psz, sizeof(psz), filein))
\r
454 CAddress addr(psz, NODE_NETWORK);
\r
455 addr.nTime = 0; // so it won't relay unless successfully connected
\r
456 if (addr.IsValid())
\r
464 Dbc* pcursor = GetCursor();
\r
470 // Read next record
\r
472 CDataStream ssValue;
\r
473 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
\r
474 if (ret == DB_NOTFOUND)
\r
482 if (strType == "addr")
\r
486 mapAddresses.insert(make_pair(addr.GetKey(), addr));
\r
491 printf("Loaded %d addresses\n", mapAddresses.size());
\r
493 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,
\r
494 // just need to call count here and it doesn't happen there. The bug was the
\r
495 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.
\r
496 mapAddresses.count(vector<unsigned char>(18));
\r
502 bool LoadAddresses()
\r
504 return CAddrDB("cr+").LoadAddresses();
\r
514 bool CReviewDB::ReadReviews(uint256 hash, vector<CReview>& vReviews)
\r
516 vReviews.size(); // msvc workaround, just need to do anything with vReviews
\r
517 return Read(make_pair(string("reviews"), hash), vReviews);
\r
520 bool CReviewDB::WriteReviews(uint256 hash, const vector<CReview>& vReviews)
\r
522 return Write(make_pair(string("reviews"), hash), vReviews);
\r
535 bool CWalletDB::LoadWallet(vector<unsigned char>& vchDefaultKeyRet)
\r
537 vchDefaultKeyRet.clear();
\r
538 int nFileVersion = 0;
\r
542 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
\r
543 fMinimizeToTray = false;
\r
544 fMinimizeOnClose = false;
\r
547 //// todo: shouldn't we catch exceptions and try to recover and continue?
\r
548 CRITICAL_BLOCK(cs_mapKeys)
\r
549 CRITICAL_BLOCK(cs_mapWallet)
\r
552 Dbc* pcursor = GetCursor();
\r
558 // Read next record
\r
560 CDataStream ssValue;
\r
561 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
\r
562 if (ret == DB_NOTFOUND)
\r
568 // Taking advantage of the fact that pair serialization
\r
569 // is just the two items serialized one after the other
\r
572 if (strType == "name")
\r
575 ssKey >> strAddress;
\r
576 ssValue >> mapAddressBook[strAddress];
\r
578 else if (strType == "tx")
\r
582 CWalletTx& wtx = mapWallet[hash];
\r
585 if (wtx.GetHash() != hash)
\r
586 printf("Error in wallet.dat, hash mismatch\n");
\r
589 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
\r
590 //printf(" %12I64d %s %s %s\n",
\r
591 // wtx.vout[0].nValue,
\r
592 // DateTimeStrFormat("%x %H:%M:%S", wtx.nTime).c_str(),
\r
593 // wtx.hashBlock.ToString().substr(0,16).c_str(),
\r
594 // wtx.mapValue["message"].c_str());
\r
596 else if (strType == "key" || strType == "wkey")
\r
598 vector<unsigned char> vchPubKey;
\r
599 ssKey >> vchPubKey;
\r
601 if (strType == "key")
\r
602 ssValue >> wkey.vchPrivKey;
\r
606 mapKeys[vchPubKey] = wkey.vchPrivKey;
\r
607 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;
\r
609 else if (strType == "defaultkey")
\r
611 ssValue >> vchDefaultKeyRet;
\r
613 else if (strType == "version")
\r
615 ssValue >> nFileVersion;
\r
617 else if (strType == "setting")
\r
623 if (strKey == "fShowGenerated") ssValue >> fShowGenerated;
\r
624 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
\r
627 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
\r
628 if (strKey == "addrIncoming") ssValue >> addrIncoming;
\r
629 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
\r
630 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
\r
631 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
\r
632 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
\r
633 if (strKey == "fUseProxy") ssValue >> fUseProxy;
\r
634 if (strKey == "addrProxy") ssValue >> addrProxy;
\r
641 printf("nFileVersion = %d\n", nFileVersion);
\r
642 printf("fShowGenerated = %d\n", fShowGenerated);
\r
643 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
\r
644 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
\r
645 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());
\r
646 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
\r
647 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
\r
648 printf("fUseProxy = %d\n", fUseProxy);
\r
649 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
\r
652 // The transaction fee setting won't be needed for many years to come.
\r
653 // Setting it to zero here in case they set it to something in an earlier version.
\r
654 if (nTransactionFee != 0)
\r
656 nTransactionFee = 0;
\r
657 WriteSetting("nTransactionFee", nTransactionFee);
\r
661 if (nFileVersion < VERSION)
\r
663 // Get rid of old debug.log file in current directory
\r
664 if (nFileVersion <= 105 && !pszSetDataDir[0])
\r
665 unlink("debug.log");
\r
667 WriteVersion(VERSION);
\r
673 bool LoadWallet(bool& fFirstRunRet)
\r
675 fFirstRunRet = false;
\r
676 vector<unsigned char> vchDefaultKey;
\r
677 if (!CWalletDB("cr+").LoadWallet(vchDefaultKey))
\r
679 fFirstRunRet = vchDefaultKey.empty();
\r
681 if (mapKeys.count(vchDefaultKey))
\r
684 keyUser.SetPubKey(vchDefaultKey);
\r
685 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);
\r
689 // Create new keyUser and set as default key
\r
690 RandAddSeedPerfmon();
\r
691 keyUser.MakeNewKey();
\r
692 if (!AddKey(keyUser))
\r
694 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))
\r
696 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());
\r
699 CreateThread(ThreadFlushWalletDB, NULL);
\r
703 void ThreadFlushWalletDB(void* parg)
\r
705 static bool fOneThread;
\r
709 if (mapArgs.count("-noflushwallet"))
\r
712 unsigned int nLastSeen = nWalletDBUpdated;
\r
713 unsigned int nLastFlushed = nWalletDBUpdated;
\r
714 int64 nLastWalletUpdate = GetTime();
\r
719 if (nLastSeen != nWalletDBUpdated)
\r
721 nLastSeen = nWalletDBUpdated;
\r
722 nLastWalletUpdate = GetTime();
\r
725 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
\r
727 TRY_CRITICAL_BLOCK(cs_db)
\r
729 // Don't do this if any databases are in use
\r
731 map<string, int>::iterator mi = mapFileUseCount.begin();
\r
732 while (mi != mapFileUseCount.end())
\r
734 nRefCount += (*mi).second;
\r
738 if (nRefCount == 0 && !fShutdown)
\r
740 string strFile = "wallet.dat";
\r
741 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
\r
742 if (mi != mapFileUseCount.end())
\r
744 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
\r
745 printf("Flushing wallet.dat\n");
\r
746 nLastFlushed = nWalletDBUpdated;
\r
747 int64 nStart = GetTimeMillis();
\r
749 // Flush wallet.dat so it's self contained
\r
751 dbenv.txn_checkpoint(0, 0, 0);
\r
752 dbenv.lsn_reset(strFile.c_str(), 0);
\r
754 mapFileUseCount.erase(mi++);
\r
755 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
\r