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.
7 void ThreadFlushWalletDB(void* parg);
10 unsigned int nWalletDBUpdated;
19 static CCriticalSection cs_db;
20 static bool fDbEnvInit = false;
22 static map<string, int> mapFileUseCount;
23 static map<string, Db*> mapDb;
43 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
49 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
50 bool fCreate = strchr(pszMode, 'c');
51 unsigned int nFlags = DB_THREAD;
61 string strDataDir = GetDataDir();
62 string strLogDir = strDataDir + "/database";
63 filesystem::create_directory(strLogDir.c_str());
64 string strErrorFile = strDataDir + "/db.log";
65 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
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(),
84 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
89 ++mapFileUseCount[strFile];
93 pdb = new Db(&dbenv, 0);
95 ret = pdb->open(NULL, // Txn pointer
97 "main", // Logical db name
98 DB_BTREE, // Database type
106 CRITICAL_BLOCK(cs_db)
107 --mapFileUseCount[strFile];
109 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
112 if (fCreate && !Exists(string("version")))
114 bool fTmp = fReadOnly;
116 WriteVersion(VERSION);
120 mapDb[strFile] = pdb;
130 vTxn.front()->abort();
134 // Flush database activity from memory pool to disk log
135 unsigned int nMinutes = 0;
136 if (strFile == "addr.dat")
138 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
140 dbenv.txn_checkpoint(0, nMinutes, 0);
142 CRITICAL_BLOCK(cs_db)
143 --mapFileUseCount[strFile];
146 void CloseDb(const string& strFile)
148 CRITICAL_BLOCK(cs_db)
150 if (mapDb[strFile] != NULL)
152 // Close the database handle
153 Db* pdb = mapDb[strFile];
156 mapDb[strFile] = NULL;
161 void DBFlush(bool fShutdown)
163 // Flush log data to the actual data file
164 // on all files that are not in use
165 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
168 CRITICAL_BLOCK(cs_db)
170 map<string, int>::iterator mi = mapFileUseCount.begin();
171 while (mi != mapFileUseCount.end())
173 string strFile = (*mi).first;
174 int nRefCount = (*mi).second;
175 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
178 // Move log data to the dat file
180 dbenv.txn_checkpoint(0, 0, 0);
181 printf("%s flush\n", strFile.c_str());
182 dbenv.lsn_reset(strFile.c_str(), 0);
183 mapFileUseCount.erase(mi++);
191 if (mapFileUseCount.empty())
192 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
208 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
212 return Read(make_pair(string("tx"), hash), txindex);
215 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
218 return Write(make_pair(string("tx"), hash), txindex);
221 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
226 uint256 hash = tx.GetHash();
227 CTxIndex txindex(pos, tx.vout.size());
228 return Write(make_pair(string("tx"), hash), txindex);
231 bool CTxDB::EraseTxIndex(const CTransaction& tx)
234 uint256 hash = tx.GetHash();
236 return Erase(make_pair(string("tx"), hash));
239 bool CTxDB::ContainsTx(uint256 hash)
242 return Exists(make_pair(string("tx"), hash));
245 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
251 Dbc* pcursor = GetCursor();
255 unsigned int fFlags = DB_SET_RANGE;
260 if (fFlags == DB_SET_RANGE)
261 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
263 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
265 if (ret == DB_NOTFOUND)
277 ssKey >> strType >> hashItem >> pos;
279 ssValue >> nItemHeight;
282 if (strType != "owner" || hashItem != hash160)
284 if (nItemHeight >= nMinHeight)
286 vtx.resize(vtx.size()+1);
287 if (!vtx.back().ReadFromDisk(pos))
299 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
303 if (!ReadTxIndex(hash, txindex))
305 return (tx.ReadFromDisk(txindex.pos));
308 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
311 return ReadDiskTx(hash, tx, txindex);
314 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
316 return ReadDiskTx(outpoint.hash, tx, txindex);
319 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
322 return ReadDiskTx(outpoint.hash, tx, txindex);
325 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
327 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
330 bool CTxDB::EraseBlockIndex(uint256 hash)
332 return Erase(make_pair(string("blockindex"), hash));
335 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
337 return Read(string("hashBestChain"), hashBestChain);
340 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
342 return Write(string("hashBestChain"), hashBestChain);
345 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
347 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
350 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
352 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
355 CBlockIndex* InsertBlockIndex(uint256 hash)
361 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
362 if (mi != mapBlockIndex.end())
366 CBlockIndex* pindexNew = new CBlockIndex();
368 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
369 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
370 pindexNew->phashBlock = &((*mi).first);
375 bool CTxDB::LoadBlockIndex()
377 // Get database cursor
378 Dbc* pcursor = GetCursor();
382 // Load mapBlockIndex
383 unsigned int fFlags = DB_SET_RANGE;
388 if (fFlags == DB_SET_RANGE)
389 ssKey << make_pair(string("blockindex"), uint256(0));
391 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
393 if (ret == DB_NOTFOUND)
401 if (strType == "blockindex")
403 CDiskBlockIndex diskindex;
404 ssValue >> diskindex;
406 // Construct block index object
407 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
408 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
409 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
410 pindexNew->nFile = diskindex.nFile;
411 pindexNew->nBlockPos = diskindex.nBlockPos;
412 pindexNew->nHeight = diskindex.nHeight;
413 pindexNew->nVersion = diskindex.nVersion;
414 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
415 pindexNew->nTime = diskindex.nTime;
416 pindexNew->nBits = diskindex.nBits;
417 pindexNew->nNonce = diskindex.nNonce;
419 // Watch for genesis block
420 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
421 pindexGenesisBlock = pindexNew;
423 if (!pindexNew->CheckIndex())
424 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
433 // Calculate bnChainWork
434 vector<pair<int, CBlockIndex*> > vSortedByHeight;
435 vSortedByHeight.reserve(mapBlockIndex.size());
436 foreach(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
438 CBlockIndex* pindex = item.second;
439 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
441 sort(vSortedByHeight.begin(), vSortedByHeight.end());
442 foreach(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
444 CBlockIndex* pindex = item.second;
445 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
448 // Load hashBestChain pointer to end of best chain
449 if (!ReadHashBestChain(hashBestChain))
451 if (pindexGenesisBlock == NULL)
453 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
455 if (!mapBlockIndex.count(hashBestChain))
456 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
457 pindexBest = mapBlockIndex[hashBestChain];
458 nBestHeight = pindexBest->nHeight;
459 bnBestChainWork = pindexBest->bnChainWork;
460 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
462 // Load bnBestInvalidWork, OK if it doesn't exist
463 ReadBestInvalidWork(bnBestInvalidWork);
465 // Verify blocks in the best chain
466 CBlockIndex* pindexFork = NULL;
467 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
469 if (pindex->nHeight < 74000 && !mapArgs.count("-checkblocks"))
472 if (!block.ReadFromDisk(pindex))
473 return error("LoadBlockIndex() : block.ReadFromDisk failed");
474 if (!block.CheckBlock())
476 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
477 pindexFork = pindex->pprev;
482 // Reorg back to the fork
483 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
485 if (!block.ReadFromDisk(pindexFork))
486 return error("LoadBlockIndex() : block.ReadFromDisk failed");
488 block.SetBestChain(txdb, pindexFork);
502 bool CAddrDB::WriteAddress(const CAddress& addr)
504 return Write(make_pair(string("addr"), addr.GetKey()), addr);
507 bool CAddrDB::LoadAddresses()
509 CRITICAL_BLOCK(cs_mapAddresses)
511 // Load user provided addresses
512 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
518 while (fgets(psz, sizeof(psz), filein))
520 CAddress addr(psz, NODE_NETWORK);
521 addr.nTime = 0; // so it won't relay unless successfully connected
530 Dbc* pcursor = GetCursor();
539 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
540 if (ret == DB_NOTFOUND)
548 if (strType == "addr")
552 mapAddresses.insert(make_pair(addr.GetKey(), addr));
557 printf("Loaded %d addresses\n", mapAddresses.size());
559 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,
560 // just need to call count here and it doesn't happen there. The bug was the
561 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.
562 mapAddresses.count(vector<unsigned char>(18));
570 return CAddrDB("cr+").LoadAddresses();
580 bool CWalletDB::LoadWallet()
582 vchDefaultKey.clear();
583 int nFileVersion = 0;
587 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
588 fMinimizeToTray = false;
589 fMinimizeOnClose = false;
592 //// todo: shouldn't we catch exceptions and try to recover and continue?
593 CRITICAL_BLOCK(cs_mapKeys)
594 CRITICAL_BLOCK(cs_mapWallet)
597 Dbc* pcursor = GetCursor();
606 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
607 if (ret == DB_NOTFOUND)
613 // Taking advantage of the fact that pair serialization
614 // is just the two items serialized one after the other
617 if (strType == "name")
621 ssValue >> mapAddressBook[strAddress];
623 else if (strType == "tx")
627 CWalletTx& wtx = mapWallet[hash];
630 if (wtx.GetHash() != hash)
631 printf("Error in wallet.dat, hash mismatch\n");
634 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
635 //printf(" %12I64d %s %s %s\n",
636 // wtx.vout[0].nValue,
637 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
638 // wtx.hashBlock.ToString().substr(0,20).c_str(),
639 // wtx.mapValue["message"].c_str());
641 else if (strType == "key" || strType == "wkey")
643 vector<unsigned char> vchPubKey;
646 if (strType == "key")
647 ssValue >> wkey.vchPrivKey;
651 mapKeys[vchPubKey] = wkey.vchPrivKey;
652 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;
654 else if (strType == "defaultkey")
656 ssValue >> vchDefaultKey;
658 else if (strType == "version")
660 ssValue >> nFileVersion;
661 if (nFileVersion == 10300)
664 else if (strType == "setting")
670 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
673 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
674 if (strKey == "addrIncoming") ssValue >> addrIncoming;
675 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
676 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
677 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
678 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
679 if (strKey == "fUseProxy") ssValue >> fUseProxy;
680 if (strKey == "addrProxy") ssValue >> addrProxy;
687 printf("nFileVersion = %d\n", nFileVersion);
688 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
689 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
690 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());
691 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
692 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
693 printf("fUseProxy = %d\n", fUseProxy);
694 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
697 // The transaction fee setting won't be needed for many years to come.
698 // Setting it to zero here in case they set it to something in an earlier version.
699 if (nTransactionFee != 0)
702 WriteSetting("nTransactionFee", nTransactionFee);
706 if (nFileVersion < VERSION)
708 // Get rid of old debug.log file in current directory
709 if (nFileVersion <= 105 && !pszSetDataDir[0])
712 WriteVersion(VERSION);
718 bool LoadWallet(bool& fFirstRunRet)
720 fFirstRunRet = false;
721 if (!CWalletDB("cr+").LoadWallet())
723 fFirstRunRet = vchDefaultKey.empty();
725 if (mapKeys.count(vchDefaultKey))
728 keyUser.SetPubKey(vchDefaultKey);
729 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);
733 // Create new keyUser and set as default key
734 RandAddSeedPerfmon();
735 keyUser.MakeNewKey();
736 if (!AddKey(keyUser))
738 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))
740 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());
743 CreateThread(ThreadFlushWalletDB, NULL);
747 void ThreadFlushWalletDB(void* parg)
749 static bool fOneThread;
753 if (mapArgs.count("-noflushwallet"))
756 unsigned int nLastSeen = nWalletDBUpdated;
757 unsigned int nLastFlushed = nWalletDBUpdated;
758 int64 nLastWalletUpdate = GetTime();
763 if (nLastSeen != nWalletDBUpdated)
765 nLastSeen = nWalletDBUpdated;
766 nLastWalletUpdate = GetTime();
769 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
771 TRY_CRITICAL_BLOCK(cs_db)
773 // Don't do this if any databases are in use
775 map<string, int>::iterator mi = mapFileUseCount.begin();
776 while (mi != mapFileUseCount.end())
778 nRefCount += (*mi).second;
782 if (nRefCount == 0 && !fShutdown)
784 string strFile = "wallet.dat";
785 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
786 if (mi != mapFileUseCount.end())
788 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
789 printf("Flushing wallet.dat\n");
790 nLastFlushed = nWalletDBUpdated;
791 int64 nStart = GetTimeMillis();
793 // Flush wallet.dat so it's self contained
795 dbenv.txn_checkpoint(0, 0, 0);
796 dbenv.lsn_reset(strFile.c_str(), 0);
798 mapFileUseCount.erase(mi++);
799 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
807 void BackupWallet(const string& strDest)
811 CRITICAL_BLOCK(cs_db)
813 const string strFile = "wallet.dat";
814 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
816 // Flush log data to the dat file
818 dbenv.txn_checkpoint(0, 0, 0);
819 dbenv.lsn_reset(strFile.c_str(), 0);
820 mapFileUseCount.erase(strFile);
823 filesystem::path pathDest(strDest);
824 if (filesystem::is_directory(pathDest))
825 pathDest = pathDest / strFile;
826 filesystem::copy_file(filesystem::path(GetDataDir() + "/" + strFile), pathDest, filesystem::copy_option::overwrite_if_exists);
827 printf("copied wallet.dat to %s\n", pathDest.string().c_str());