1 // Copyright (c) 2009 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
141 void CloseDb(const string& strFile)
\r
143 CRITICAL_BLOCK(cs_db)
\r
145 if (mapDb[strFile] != NULL)
\r
147 // Close the database handle
\r
148 Db* pdb = mapDb[strFile];
\r
151 mapDb[strFile] = NULL;
\r
156 void DBFlush(bool fShutdown)
\r
158 // Flush log data to the actual data file
\r
159 // on all files that are not in use
\r
160 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
\r
163 CRITICAL_BLOCK(cs_db)
\r
165 map<string, int>::iterator mi = mapFileUseCount.begin();
\r
166 while (mi != mapFileUseCount.end())
\r
168 string strFile = (*mi).first;
\r
169 int nRefCount = (*mi).second;
\r
170 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
\r
171 if (nRefCount == 0)
\r
173 // Move log data to the dat file
\r
175 dbenv.txn_checkpoint(0, 0, 0);
\r
176 printf("%s flush\n", strFile.c_str());
\r
177 dbenv.lsn_reset(strFile.c_str(), 0);
\r
178 mapFileUseCount.erase(mi++);
\r
186 if (mapFileUseCount.empty())
\r
187 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
\r
189 fDbEnvInit = false;
\r
203 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
\r
207 return Read(make_pair(string("tx"), hash), txindex);
\r
210 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
\r
213 return Write(make_pair(string("tx"), hash), txindex);
\r
216 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
\r
221 uint256 hash = tx.GetHash();
\r
222 CTxIndex txindex(pos, tx.vout.size());
\r
223 return Write(make_pair(string("tx"), hash), txindex);
\r
226 bool CTxDB::EraseTxIndex(const CTransaction& tx)
\r
229 uint256 hash = tx.GetHash();
\r
231 return Erase(make_pair(string("tx"), hash));
\r
234 bool CTxDB::ContainsTx(uint256 hash)
\r
237 return Exists(make_pair(string("tx"), hash));
\r
240 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
\r
246 Dbc* pcursor = GetCursor();
\r
250 unsigned int fFlags = DB_SET_RANGE;
\r
253 // Read next record
\r
255 if (fFlags == DB_SET_RANGE)
\r
256 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
\r
257 CDataStream ssValue;
\r
258 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
\r
260 if (ret == DB_NOTFOUND)
\r
272 ssKey >> strType >> hashItem >> pos;
\r
274 ssValue >> nItemHeight;
\r
276 // Read transaction
\r
277 if (strType != "owner" || hashItem != hash160)
\r
279 if (nItemHeight >= nMinHeight)
\r
281 vtx.resize(vtx.size()+1);
\r
282 if (!vtx.back().ReadFromDisk(pos))
\r
294 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
\r
298 if (!ReadTxIndex(hash, txindex))
\r
300 return (tx.ReadFromDisk(txindex.pos));
\r
303 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
\r
306 return ReadDiskTx(hash, tx, txindex);
\r
309 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
\r
311 return ReadDiskTx(outpoint.hash, tx, txindex);
\r
314 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
\r
317 return ReadDiskTx(outpoint.hash, tx, txindex);
\r
320 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
\r
322 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
\r
325 bool CTxDB::EraseBlockIndex(uint256 hash)
\r
327 return Erase(make_pair(string("blockindex"), hash));
\r
330 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
\r
332 return Read(string("hashBestChain"), hashBestChain);
\r
335 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
\r
337 return Write(string("hashBestChain"), hashBestChain);
\r
340 CBlockIndex* InsertBlockIndex(uint256 hash)
\r
346 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
347 if (mi != mapBlockIndex.end())
\r
348 return (*mi).second;
\r
351 CBlockIndex* pindexNew = new CBlockIndex();
\r
353 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
\r
354 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
\r
355 pindexNew->phashBlock = &((*mi).first);
\r
360 bool CTxDB::LoadBlockIndex()
\r
363 Dbc* pcursor = GetCursor();
\r
367 unsigned int fFlags = DB_SET_RANGE;
\r
370 // Read next record
\r
372 if (fFlags == DB_SET_RANGE)
\r
373 ssKey << make_pair(string("blockindex"), uint256(0));
\r
374 CDataStream ssValue;
\r
375 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
\r
377 if (ret == DB_NOTFOUND)
\r
385 if (strType == "blockindex")
\r
387 CDiskBlockIndex diskindex;
\r
388 ssValue >> diskindex;
\r
390 // Construct block index object
\r
391 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
\r
392 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
\r
393 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
\r
394 pindexNew->nFile = diskindex.nFile;
\r
395 pindexNew->nBlockPos = diskindex.nBlockPos;
\r
396 pindexNew->nHeight = diskindex.nHeight;
\r
397 pindexNew->nVersion = diskindex.nVersion;
\r
398 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
\r
399 pindexNew->nTime = diskindex.nTime;
\r
400 pindexNew->nBits = diskindex.nBits;
\r
401 pindexNew->nNonce = diskindex.nNonce;
\r
403 // Watch for genesis block and best block
\r
404 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
\r
405 pindexGenesisBlock = pindexNew;
\r
414 if (!ReadHashBestChain(hashBestChain))
\r
416 if (pindexGenesisBlock == NULL)
\r
418 return error("CTxDB::LoadBlockIndex() : hashBestChain not found");
\r
421 if (!mapBlockIndex.count(hashBestChain))
\r
422 return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found");
\r
423 pindexBest = mapBlockIndex[hashBestChain];
\r
424 nBestHeight = pindexBest->nHeight;
\r
425 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
\r
438 bool CAddrDB::WriteAddress(const CAddress& addr)
\r
440 return Write(make_pair(string("addr"), addr.GetKey()), addr);
\r
443 bool CAddrDB::LoadAddresses()
\r
445 CRITICAL_BLOCK(cs_mapAddresses)
\r
447 // Load user provided addresses
\r
448 CAutoFile filein = fopen("addr.txt", "rt");
\r
454 while (fgets(psz, sizeof(psz), filein))
\r
456 CAddress addr(psz, NODE_NETWORK);
\r
457 if (addr.IsValid())
\r
458 AddAddress(*this, addr);
\r
465 Dbc* pcursor = GetCursor();
\r
471 // Read next record
\r
473 CDataStream ssValue;
\r
474 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
\r
475 if (ret == DB_NOTFOUND)
\r
483 if (strType == "addr")
\r
487 mapAddresses.insert(make_pair(addr.GetKey(), addr));
\r
492 printf("Loaded %d addresses\n", mapAddresses.size());
\r
494 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,
\r
495 // just need to call count here and it doesn't happen there. The bug was the
\r
496 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.
\r
497 mapAddresses.count(vector<unsigned char>(18));
\r
503 bool LoadAddresses()
\r
505 return CAddrDB("cr+").LoadAddresses();
\r
515 bool CReviewDB::ReadReviews(uint256 hash, vector<CReview>& vReviews)
\r
517 vReviews.size(); // msvc workaround, just need to do anything with vReviews
\r
518 return Read(make_pair(string("reviews"), hash), vReviews);
\r
521 bool CReviewDB::WriteReviews(uint256 hash, const vector<CReview>& vReviews)
\r
523 return Write(make_pair(string("reviews"), hash), vReviews);
\r
536 bool CWalletDB::LoadWallet(vector<unsigned char>& vchDefaultKeyRet)
\r
538 vchDefaultKeyRet.clear();
\r
542 // Reports that tray icon can disappear on gnome, 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")
\r
598 vector<unsigned char> vchPubKey;
\r
599 ssKey >> vchPubKey;
\r
600 CPrivKey vchPrivKey;
\r
601 ssValue >> vchPrivKey;
\r
603 mapKeys[vchPubKey] = vchPrivKey;
\r
604 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;
\r
606 else if (strType == "defaultkey")
\r
608 ssValue >> vchDefaultKeyRet;
\r
610 else if (strType == "setting")
\r
616 if (strKey == "fShowGenerated") ssValue >> fShowGenerated;
\r
617 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
\r
620 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
\r
621 if (strKey == "addrIncoming") ssValue >> addrIncoming;
\r
622 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
\r
623 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
\r
624 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
\r
625 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
\r
626 if (strKey == "fUseProxy") ssValue >> fUseProxy;
\r
627 if (strKey == "addrProxy") ssValue >> addrProxy;
\r
634 printf("fShowGenerated = %d\n", fShowGenerated);
\r
635 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
\r
636 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
\r
637 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());
\r
638 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
\r
639 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
\r
640 printf("fUseProxy = %d\n", fUseProxy);
\r
641 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
\r
644 // The transaction fee setting won't be needed for many years to come.
\r
645 // Setting it to zero here in case they set it to something in an earlier version.
\r
646 if (nTransactionFee != 0)
\r
648 nTransactionFee = 0;
\r
649 WriteSetting("nTransactionFee", nTransactionFee);
\r
655 bool LoadWallet(bool& fFirstRunRet)
\r
657 fFirstRunRet = false;
\r
658 vector<unsigned char> vchDefaultKey;
\r
659 if (!CWalletDB("cr").LoadWallet(vchDefaultKey))
\r
661 fFirstRunRet = vchDefaultKey.empty();
\r
663 if (mapKeys.count(vchDefaultKey))
\r
666 keyUser.SetPubKey(vchDefaultKey);
\r
667 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);
\r
671 // Create new keyUser and set as default key
\r
672 RandAddSeedPerfmon();
\r
673 keyUser.MakeNewKey();
\r
674 if (!AddKey(keyUser))
\r
676 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))
\r
678 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());
\r
681 CreateThread(ThreadFlushWalletDB, NULL);
\r
685 void ThreadFlushWalletDB(void* parg)
\r
687 static bool fOneThread;
\r
691 if (mapArgs.count("-noflushwallet"))
\r
694 unsigned int nLastSeen = nWalletDBUpdated;
\r
695 unsigned int nLastFlushed = nWalletDBUpdated;
\r
696 int64 nLastWalletUpdate = GetTime();
\r
701 if (nLastSeen != nWalletDBUpdated)
\r
703 nLastSeen = nWalletDBUpdated;
\r
704 nLastWalletUpdate = GetTime();
\r
707 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
\r
709 TRY_CRITICAL_BLOCK(cs_db)
\r
711 // Don't do this if any databases are in use
\r
713 map<string, int>::iterator mi = mapFileUseCount.begin();
\r
714 while (mi != mapFileUseCount.end())
\r
716 nRefCount += (*mi).second;
\r
720 if (nRefCount == 0 && !fShutdown)
\r
722 string strFile = "wallet.dat";
\r
723 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
\r
724 if (mi != mapFileUseCount.end())
\r
726 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
\r
727 printf("Flushing wallet.dat\n");
\r
728 nLastFlushed = nWalletDBUpdated;
\r
729 int64 nStart = GetTimeMillis();
\r
731 // Flush wallet.dat so it's self contained
\r
733 dbenv.txn_checkpoint(0, 0, 0);
\r
734 dbenv.lsn_reset(strFile.c_str(), 0);
\r
736 mapFileUseCount.erase(mi++);
\r
737 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
\r