You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.cpp 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "db.h"
  6. #include "util.h"
  7. #include "main.h"
  8. #include <boost/version.hpp>
  9. #include <boost/filesystem.hpp>
  10. #include <boost/filesystem/fstream.hpp>
  11. #ifndef WIN32
  12. #include "sys/stat.h"
  13. #endif
  14. using namespace std;
  15. using namespace boost;
  16. unsigned int nWalletDBUpdated;
  17. //
  18. // CDB
  19. //
  20. CDBEnv bitdb;
  21. void CDBEnv::EnvShutdown()
  22. {
  23. if (!fDbEnvInit)
  24. return;
  25. fDbEnvInit = false;
  26. int ret = dbenv.close(0);
  27. if (ret != 0)
  28. printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
  29. if (!fMockDb)
  30. DbEnv(0).remove(GetDataDir().string().c_str(), 0);
  31. }
  32. CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
  33. {
  34. }
  35. CDBEnv::~CDBEnv()
  36. {
  37. EnvShutdown();
  38. }
  39. void CDBEnv::Close()
  40. {
  41. EnvShutdown();
  42. }
  43. bool CDBEnv::Open(boost::filesystem::path pathEnv_)
  44. {
  45. if (fDbEnvInit)
  46. return true;
  47. if (fShutdown)
  48. return false;
  49. pathEnv = pathEnv_;
  50. filesystem::path pathDataDir = pathEnv;
  51. filesystem::path pathLogDir = pathDataDir / "database";
  52. filesystem::create_directory(pathLogDir);
  53. filesystem::path pathErrorFile = pathDataDir / "db.log";
  54. printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
  55. unsigned int nEnvFlags = 0;
  56. if (GetBoolArg("-privdb", true))
  57. nEnvFlags |= DB_PRIVATE;
  58. int nDbCache = GetArg("-dbcache", 25);
  59. dbenv.set_lg_dir(pathLogDir.string().c_str());
  60. dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
  61. dbenv.set_lg_bsize(1048576);
  62. dbenv.set_lg_max(10485760);
  63. dbenv.set_lk_max_locks(10000);
  64. dbenv.set_lk_max_objects(10000);
  65. dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
  66. dbenv.set_flags(DB_AUTO_COMMIT, 1);
  67. dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
  68. dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
  69. int ret = dbenv.open(pathDataDir.string().c_str(),
  70. DB_CREATE |
  71. DB_INIT_LOCK |
  72. DB_INIT_LOG |
  73. DB_INIT_MPOOL |
  74. DB_INIT_TXN |
  75. DB_THREAD |
  76. DB_RECOVER |
  77. nEnvFlags,
  78. S_IRUSR | S_IWUSR);
  79. if (ret != 0)
  80. return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
  81. fDbEnvInit = true;
  82. fMockDb = false;
  83. return true;
  84. }
  85. void CDBEnv::MakeMock()
  86. {
  87. if (fDbEnvInit)
  88. throw runtime_error("CDBEnv::MakeMock(): already initialized");
  89. if (fShutdown)
  90. throw runtime_error("CDBEnv::MakeMock(): during shutdown");
  91. printf("CDBEnv::MakeMock()\n");
  92. dbenv.set_cachesize(1, 0, 1);
  93. dbenv.set_lg_bsize(10485760*4);
  94. dbenv.set_lg_max(10485760);
  95. dbenv.set_lk_max_locks(10000);
  96. dbenv.set_lk_max_objects(10000);
  97. dbenv.set_flags(DB_AUTO_COMMIT, 1);
  98. dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
  99. int ret = dbenv.open(NULL,
  100. DB_CREATE |
  101. DB_INIT_LOCK |
  102. DB_INIT_LOG |
  103. DB_INIT_MPOOL |
  104. DB_INIT_TXN |
  105. DB_THREAD |
  106. DB_PRIVATE,
  107. S_IRUSR | S_IWUSR);
  108. if (ret > 0)
  109. throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
  110. fDbEnvInit = true;
  111. fMockDb = true;
  112. }
  113. CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
  114. {
  115. LOCK(cs_db);
  116. assert(mapFileUseCount.count(strFile) == 0);
  117. Db db(&dbenv, 0);
  118. int result = db.verify(strFile.c_str(), NULL, NULL, 0);
  119. if (result == 0)
  120. return VERIFY_OK;
  121. else if (recoverFunc == NULL)
  122. return RECOVER_FAIL;
  123. // Try to recover:
  124. bool fRecovered = (*recoverFunc)(*this, strFile);
  125. return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
  126. }
  127. bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
  128. std::vector<CDBEnv::KeyValPair >& vResult)
  129. {
  130. LOCK(cs_db);
  131. assert(mapFileUseCount.count(strFile) == 0);
  132. u_int32_t flags = DB_SALVAGE;
  133. if (fAggressive) flags |= DB_AGGRESSIVE;
  134. stringstream strDump;
  135. Db db(&dbenv, 0);
  136. int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
  137. if (result != 0)
  138. {
  139. printf("ERROR: db salvage failed\n");
  140. return false;
  141. }
  142. // Format of bdb dump is ascii lines:
  143. // header lines...
  144. // HEADER=END
  145. // hexadecimal key
  146. // hexadecimal value
  147. // ... repeated
  148. // DATA=END
  149. string strLine;
  150. while (!strDump.eof() && strLine != "HEADER=END")
  151. getline(strDump, strLine); // Skip past header
  152. std::string keyHex, valueHex;
  153. while (!strDump.eof() && keyHex != "DATA=END")
  154. {
  155. getline(strDump, keyHex);
  156. if (keyHex != "DATA_END")
  157. {
  158. getline(strDump, valueHex);
  159. vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
  160. }
  161. }
  162. return (result == 0);
  163. }
  164. void CDBEnv::CheckpointLSN(std::string strFile)
  165. {
  166. dbenv.txn_checkpoint(0, 0, 0);
  167. if (fMockDb)
  168. return;
  169. dbenv.lsn_reset(strFile.c_str(), 0);
  170. }
  171. CDB::CDB(const char *pszFile, const char* pszMode) :
  172. pdb(NULL), activeTxn(NULL)
  173. {
  174. int ret;
  175. if (pszFile == NULL)
  176. return;
  177. fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
  178. bool fCreate = strchr(pszMode, 'c');
  179. unsigned int nFlags = DB_THREAD;
  180. if (fCreate)
  181. nFlags |= DB_CREATE;
  182. {
  183. LOCK(bitdb.cs_db);
  184. if (!bitdb.Open(GetDataDir()))
  185. throw runtime_error("env open failed");
  186. strFile = pszFile;
  187. ++bitdb.mapFileUseCount[strFile];
  188. pdb = bitdb.mapDb[strFile];
  189. if (pdb == NULL)
  190. {
  191. pdb = new Db(&bitdb.dbenv, 0);
  192. bool fMockDb = bitdb.IsMock();
  193. if (fMockDb)
  194. {
  195. DbMpoolFile*mpf = pdb->get_mpf();
  196. ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
  197. if (ret != 0)
  198. throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
  199. }
  200. ret = pdb->open(NULL, // Txn pointer
  201. fMockDb ? NULL : pszFile, // Filename
  202. "main", // Logical db name
  203. DB_BTREE, // Database type
  204. nFlags, // Flags
  205. 0);
  206. if (ret != 0)
  207. {
  208. delete pdb;
  209. pdb = NULL;
  210. --bitdb.mapFileUseCount[strFile];
  211. strFile = "";
  212. throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
  213. }
  214. if (fCreate && !Exists(string("version")))
  215. {
  216. bool fTmp = fReadOnly;
  217. fReadOnly = false;
  218. WriteVersion(CLIENT_VERSION);
  219. fReadOnly = fTmp;
  220. }
  221. bitdb.mapDb[strFile] = pdb;
  222. }
  223. }
  224. }
  225. static bool IsChainFile(std::string strFile)
  226. {
  227. if (strFile == "blkindex.dat")
  228. return true;
  229. return false;
  230. }
  231. void CDB::Close()
  232. {
  233. if (!pdb)
  234. return;
  235. if (activeTxn)
  236. activeTxn->abort();
  237. activeTxn = NULL;
  238. pdb = NULL;
  239. // Flush database activity from memory pool to disk log
  240. unsigned int nMinutes = 0;
  241. if (fReadOnly)
  242. nMinutes = 1;
  243. if (IsChainFile(strFile))
  244. nMinutes = 2;
  245. if (IsChainFile(strFile) && IsInitialBlockDownload())
  246. nMinutes = 5;
  247. bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
  248. {
  249. LOCK(bitdb.cs_db);
  250. --bitdb.mapFileUseCount[strFile];
  251. }
  252. }
  253. void CDBEnv::CloseDb(const string& strFile)
  254. {
  255. {
  256. LOCK(cs_db);
  257. if (mapDb[strFile] != NULL)
  258. {
  259. // Close the database handle
  260. Db* pdb = mapDb[strFile];
  261. pdb->close(0);
  262. delete pdb;
  263. mapDb[strFile] = NULL;
  264. }
  265. }
  266. }
  267. bool CDBEnv::RemoveDb(const string& strFile)
  268. {
  269. this->CloseDb(strFile);
  270. LOCK(cs_db);
  271. int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
  272. return (rc == 0);
  273. }
  274. bool CDB::Rewrite(const string& strFile, const char* pszSkip)
  275. {
  276. while (!fShutdown)
  277. {
  278. {
  279. LOCK(bitdb.cs_db);
  280. if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
  281. {
  282. // Flush log data to the dat file
  283. bitdb.CloseDb(strFile);
  284. bitdb.CheckpointLSN(strFile);
  285. bitdb.mapFileUseCount.erase(strFile);
  286. bool fSuccess = true;
  287. printf("Rewriting %s...\n", strFile.c_str());
  288. string strFileRes = strFile + ".rewrite";
  289. { // surround usage of db with extra {}
  290. CDB db(strFile.c_str(), "r");
  291. Db* pdbCopy = new Db(&bitdb.dbenv, 0);
  292. int ret = pdbCopy->open(NULL, // Txn pointer
  293. strFileRes.c_str(), // Filename
  294. "main", // Logical db name
  295. DB_BTREE, // Database type
  296. DB_CREATE, // Flags
  297. 0);
  298. if (ret > 0)
  299. {
  300. printf("Cannot create database file %s\n", strFileRes.c_str());
  301. fSuccess = false;
  302. }
  303. Dbc* pcursor = db.GetCursor();
  304. if (pcursor)
  305. while (fSuccess)
  306. {
  307. CDataStream ssKey(SER_DISK, CLIENT_VERSION);
  308. CDataStream ssValue(SER_DISK, CLIENT_VERSION);
  309. int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
  310. if (ret == DB_NOTFOUND)
  311. {
  312. pcursor->close();
  313. break;
  314. }
  315. else if (ret != 0)
  316. {
  317. pcursor->close();
  318. fSuccess = false;
  319. break;
  320. }
  321. if (pszSkip &&
  322. strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
  323. continue;
  324. if (strncmp(&ssKey[0], "\x07version", 8) == 0)
  325. {
  326. // Update version:
  327. ssValue.clear();
  328. ssValue << CLIENT_VERSION;
  329. }
  330. Dbt datKey(&ssKey[0], ssKey.size());
  331. Dbt datValue(&ssValue[0], ssValue.size());
  332. int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
  333. if (ret2 > 0)
  334. fSuccess = false;
  335. }
  336. if (fSuccess)
  337. {
  338. db.Close();
  339. bitdb.CloseDb(strFile);
  340. if (pdbCopy->close(0))
  341. fSuccess = false;
  342. delete pdbCopy;
  343. }
  344. }
  345. if (fSuccess)
  346. {
  347. Db dbA(&bitdb.dbenv, 0);
  348. if (dbA.remove(strFile.c_str(), NULL, 0))
  349. fSuccess = false;
  350. Db dbB(&bitdb.dbenv, 0);
  351. if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
  352. fSuccess = false;
  353. }
  354. if (!fSuccess)
  355. printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
  356. return fSuccess;
  357. }
  358. }
  359. Sleep(100);
  360. }
  361. return false;
  362. }
  363. void CDBEnv::Flush(bool fShutdown)
  364. {
  365. int64 nStart = GetTimeMillis();
  366. // Flush log data to the actual data file
  367. // on all files that are not in use
  368. printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
  369. if (!fDbEnvInit)
  370. return;
  371. {
  372. LOCK(cs_db);
  373. map<string, int>::iterator mi = mapFileUseCount.begin();
  374. while (mi != mapFileUseCount.end())
  375. {
  376. string strFile = (*mi).first;
  377. int nRefCount = (*mi).second;
  378. printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
  379. if (nRefCount == 0)
  380. {
  381. // Move log data to the dat file
  382. CloseDb(strFile);
  383. printf("%s checkpoint\n", strFile.c_str());
  384. dbenv.txn_checkpoint(0, 0, 0);
  385. if (!IsChainFile(strFile) || fDetachDB) {
  386. printf("%s detach\n", strFile.c_str());
  387. if (!fMockDb)
  388. dbenv.lsn_reset(strFile.c_str(), 0);
  389. }
  390. printf("%s closed\n", strFile.c_str());
  391. mapFileUseCount.erase(mi++);
  392. }
  393. else
  394. mi++;
  395. }
  396. printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
  397. if (fShutdown)
  398. {
  399. char** listp;
  400. if (mapFileUseCount.empty())
  401. {
  402. dbenv.log_archive(&listp, DB_ARCH_REMOVE);
  403. Close();
  404. }
  405. }
  406. }
  407. }
  408. //
  409. // CTxDB
  410. //
  411. bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
  412. {
  413. assert(!fClient);
  414. txindex.SetNull();
  415. return Read(make_pair(string("tx"), hash), txindex);
  416. }
  417. bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
  418. {
  419. assert(!fClient);
  420. return Write(make_pair(string("tx"), hash), txindex);
  421. }
  422. bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
  423. {
  424. assert(!fClient);
  425. // Add to tx index
  426. uint256 hash = tx.GetHash();
  427. CTxIndex txindex(pos, tx.vout.size());
  428. return Write(make_pair(string("tx"), hash), txindex);
  429. }
  430. bool CTxDB::EraseTxIndex(const CTransaction& tx)
  431. {
  432. assert(!fClient);
  433. uint256 hash = tx.GetHash();
  434. return Erase(make_pair(string("tx"), hash));
  435. }
  436. bool CTxDB::ContainsTx(uint256 hash)
  437. {
  438. assert(!fClient);
  439. return Exists(make_pair(string("tx"), hash));
  440. }
  441. bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
  442. {
  443. assert(!fClient);
  444. tx.SetNull();
  445. if (!ReadTxIndex(hash, txindex))
  446. return false;
  447. return (tx.ReadFromDisk(txindex.pos));
  448. }
  449. bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
  450. {
  451. CTxIndex txindex;
  452. return ReadDiskTx(hash, tx, txindex);
  453. }
  454. bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
  455. {
  456. return ReadDiskTx(outpoint.hash, tx, txindex);
  457. }
  458. bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
  459. {
  460. CTxIndex txindex;
  461. return ReadDiskTx(outpoint.hash, tx, txindex);
  462. }
  463. bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
  464. {
  465. return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
  466. }
  467. bool CTxDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
  468. return Write(make_pair(string("blockfile"), nFile), info);
  469. }
  470. bool CTxDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
  471. return Read(make_pair(string("blockfile"), nFile), info);
  472. }
  473. bool CTxDB::WriteLastBlockFile(int nFile) {
  474. return Write(string("lastblockfile"), nFile);
  475. }
  476. bool CTxDB::ReadLastBlockFile(int &nFile) {
  477. return Read(string("lastblockfile"), nFile);
  478. }
  479. bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
  480. {
  481. return Read(string("hashBestChain"), hashBestChain);
  482. }
  483. bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
  484. {
  485. return Write(string("hashBestChain"), hashBestChain);
  486. }
  487. bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
  488. {
  489. return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
  490. }
  491. bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
  492. {
  493. return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
  494. }
  495. CBlockIndex static * InsertBlockIndex(uint256 hash)
  496. {
  497. if (hash == 0)
  498. return NULL;
  499. // Return existing
  500. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  501. if (mi != mapBlockIndex.end())
  502. return (*mi).second;
  503. // Create new
  504. CBlockIndex* pindexNew = new CBlockIndex();
  505. if (!pindexNew)
  506. throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
  507. mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  508. pindexNew->phashBlock = &((*mi).first);
  509. return pindexNew;
  510. }
  511. bool CTxDB::LoadBlockIndex()
  512. {
  513. if (!LoadBlockIndexGuts())
  514. return false;
  515. if (fRequestShutdown)
  516. return true;
  517. // Calculate bnChainWork
  518. vector<pair<int, CBlockIndex*> > vSortedByHeight;
  519. vSortedByHeight.reserve(mapBlockIndex.size());
  520. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  521. {
  522. CBlockIndex* pindex = item.second;
  523. vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
  524. }
  525. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  526. BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
  527. {
  528. CBlockIndex* pindex = item.second;
  529. pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
  530. }
  531. // Load block file info
  532. ReadLastBlockFile(nLastBlockFile);
  533. printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
  534. if (ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  535. printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
  536. // Load hashBestChain pointer to end of best chain
  537. if (!ReadHashBestChain(hashBestChain))
  538. {
  539. if (pindexGenesisBlock == NULL)
  540. return true;
  541. return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
  542. }
  543. if (!mapBlockIndex.count(hashBestChain))
  544. return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
  545. pindexBest = mapBlockIndex[hashBestChain];
  546. nBestHeight = pindexBest->nHeight;
  547. bnBestChainWork = pindexBest->bnChainWork;
  548. printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
  549. hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
  550. DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
  551. // Load bnBestInvalidWork, OK if it doesn't exist
  552. ReadBestInvalidWork(bnBestInvalidWork);
  553. // Verify blocks in the best chain
  554. int nCheckLevel = GetArg("-checklevel", 1);
  555. int nCheckDepth = GetArg( "-checkblocks", 2500);
  556. if (nCheckDepth == 0)
  557. nCheckDepth = 1000000000; // suffices until the year 19000
  558. if (nCheckDepth > nBestHeight)
  559. nCheckDepth = nBestHeight;
  560. printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  561. CBlockIndex* pindexFork = NULL;
  562. for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
  563. {
  564. if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
  565. break;
  566. CBlock block;
  567. CDiskBlockPos blockPos = pindex->GetBlockPos();
  568. if (!block.ReadFromDisk(pindex))
  569. return error("LoadBlockIndex() : block.ReadFromDisk failed");
  570. // check level 1: verify block validity
  571. if (nCheckLevel>0 && !block.CheckBlock())
  572. {
  573. printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  574. pindexFork = pindex->pprev;
  575. }
  576. // check level 2: verify transaction index validity
  577. if (nCheckLevel>1)
  578. {
  579. BOOST_FOREACH(const CTransaction &tx, block.vtx)
  580. {
  581. uint256 hashTx = tx.GetHash();
  582. CTxIndex txindex;
  583. if (ReadTxIndex(hashTx, txindex))
  584. {
  585. // check level 3: checker transaction hashes
  586. if (nCheckLevel>2 || blockPos != txindex.pos.blockPos)
  587. {
  588. // either an error or a duplicate transaction
  589. CTransaction txFound;
  590. if (!txFound.ReadFromDisk(txindex.pos))
  591. {
  592. printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
  593. pindexFork = pindex->pprev;
  594. }
  595. else
  596. if (txFound.GetHash() != hashTx) // not a duplicate tx
  597. {
  598. printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
  599. pindexFork = pindex->pprev;
  600. }
  601. }
  602. // check level 4: check whether spent txouts were spent within the main chain
  603. unsigned int nOutput = 0;
  604. if (nCheckLevel>3)
  605. {
  606. BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
  607. {
  608. if (!txpos.IsNull())
  609. {
  610. // check level 6: check whether spent txouts were spent by a valid transaction that consume them
  611. if (nCheckLevel>5)
  612. {
  613. CTransaction txSpend;
  614. if (!txSpend.ReadFromDisk(txpos))
  615. {
  616. printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
  617. pindexFork = pindex->pprev;
  618. }
  619. else if (!txSpend.CheckTransaction())
  620. {
  621. printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
  622. pindexFork = pindex->pprev;
  623. }
  624. else
  625. {
  626. bool fFound = false;
  627. BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
  628. if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
  629. fFound = true;
  630. if (!fFound)
  631. {
  632. printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
  633. pindexFork = pindex->pprev;
  634. }
  635. }
  636. }
  637. }
  638. nOutput++;
  639. }
  640. }
  641. }
  642. // check level 5: check whether all prevouts are marked spent
  643. if (nCheckLevel>4)
  644. {
  645. BOOST_FOREACH(const CTxIn &txin, tx.vin)
  646. {
  647. CTxIndex txindex;
  648. if (ReadTxIndex(txin.prevout.hash, txindex))
  649. if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
  650. {
  651. printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
  652. pindexFork = pindex->pprev;
  653. }
  654. }
  655. }
  656. }
  657. }
  658. }
  659. if (pindexFork && !fRequestShutdown)
  660. {
  661. // Reorg back to the fork
  662. printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
  663. CBlock block;
  664. if (!block.ReadFromDisk(pindexFork))
  665. return error("LoadBlockIndex() : block.ReadFromDisk failed");
  666. CTxDB txdb;
  667. block.SetBestChain(txdb, pindexFork);
  668. }
  669. return true;
  670. }
  671. bool CTxDB::LoadBlockIndexGuts()
  672. {
  673. // Get database cursor
  674. Dbc* pcursor = GetCursor();
  675. if (!pcursor)
  676. return false;
  677. // Load mapBlockIndex
  678. unsigned int fFlags = DB_SET_RANGE;
  679. loop
  680. {
  681. // Read next record
  682. CDataStream ssKey(SER_DISK, CLIENT_VERSION);
  683. if (fFlags == DB_SET_RANGE)
  684. ssKey << make_pair(string("blockindex"), uint256(0));
  685. CDataStream ssValue(SER_DISK, CLIENT_VERSION);
  686. int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
  687. fFlags = DB_NEXT;
  688. if (ret == DB_NOTFOUND)
  689. break;
  690. else if (ret != 0)
  691. return false;
  692. // Unserialize
  693. try {
  694. string strType;
  695. ssKey >> strType;
  696. if (strType == "blockindex" && !fRequestShutdown)
  697. {
  698. CDiskBlockIndex diskindex;
  699. ssValue >> diskindex;
  700. // Construct block index object
  701. CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
  702. pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
  703. pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
  704. pindexNew->nHeight = diskindex.nHeight;
  705. pindexNew->pos = diskindex.pos;
  706. pindexNew->nUndoPos = diskindex.nUndoPos;
  707. pindexNew->nVersion = diskindex.nVersion;
  708. pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
  709. pindexNew->nTime = diskindex.nTime;
  710. pindexNew->nBits = diskindex.nBits;
  711. pindexNew->nNonce = diskindex.nNonce;
  712. // Watch for genesis block
  713. if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
  714. pindexGenesisBlock = pindexNew;
  715. if (!pindexNew->CheckIndex())
  716. return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
  717. }
  718. else
  719. {
  720. break; // if shutdown requested or finished loading block index
  721. }
  722. } // try
  723. catch (std::exception &e) {
  724. return error("%s() : deserialize error", __PRETTY_FUNCTION__);
  725. }
  726. }
  727. pcursor->close();
  728. return true;
  729. }
  730. //
  731. // CAddrDB
  732. //
  733. CAddrDB::CAddrDB()
  734. {
  735. pathAddr = GetDataDir() / "peers.dat";
  736. }
  737. bool CAddrDB::Write(const CAddrMan& addr)
  738. {
  739. // Generate random temporary filename
  740. unsigned short randv = 0;
  741. RAND_bytes((unsigned char *)&randv, sizeof(randv));
  742. std::string tmpfn = strprintf("peers.dat.%04x", randv);
  743. // serialize addresses, checksum data up to that point, then append csum
  744. CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
  745. ssPeers << FLATDATA(pchMessageStart);
  746. ssPeers << addr;
  747. uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
  748. ssPeers << hash;
  749. // open temp output file, and associate with CAutoFile
  750. boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
  751. FILE *file = fopen(pathTmp.string().c_str(), "wb");
  752. CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
  753. if (!fileout)
  754. return error("CAddrman::Write() : open failed");
  755. // Write and commit header, data
  756. try {
  757. fileout << ssPeers;
  758. }
  759. catch (std::exception &e) {
  760. return error("CAddrman::Write() : I/O error");
  761. }
  762. FileCommit(fileout);
  763. fileout.fclose();
  764. // replace existing peers.dat, if any, with new peers.dat.XXXX
  765. if (!RenameOver(pathTmp, pathAddr))
  766. return error("CAddrman::Write() : Rename-into-place failed");
  767. return true;
  768. }
  769. bool CAddrDB::Read(CAddrMan& addr)
  770. {
  771. // open input file, and associate with CAutoFile
  772. FILE *file = fopen(pathAddr.string().c_str(), "rb");
  773. CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
  774. if (!filein)
  775. return error("CAddrman::Read() : open failed");
  776. // use file size to size memory buffer
  777. int fileSize = GetFilesize(filein);
  778. int dataSize = fileSize - sizeof(uint256);
  779. vector<unsigned char> vchData;
  780. vchData.resize(dataSize);
  781. uint256 hashIn;
  782. // read data and checksum from file
  783. try {
  784. filein.read((char *)&vchData[0], dataSize);
  785. filein >> hashIn;
  786. }
  787. catch (std::exception &e) {
  788. return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
  789. }
  790. filein.fclose();
  791. CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
  792. // verify stored checksum matches input data
  793. uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
  794. if (hashIn != hashTmp)
  795. return error("CAddrman::Read() : checksum mismatch; data corrupted");
  796. // de-serialize address data
  797. unsigned char pchMsgTmp[4];
  798. try {
  799. ssPeers >> FLATDATA(pchMsgTmp);
  800. ssPeers >> addr;
  801. }
  802. catch (std::exception &e) {
  803. return error("CAddrman::Read() : I/O error or stream data corrupted");
  804. }
  805. // finally, verify the network matches ours
  806. if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
  807. return error("CAddrman::Read() : invalid network magic number");
  808. return true;
  809. }