raw
genesis                 1 // Copyright (c) 2009-2010 Satoshi Nakamoto
genesis 2 // Copyright (c) 2009-2012 The Bitcoin developers
genesis 3 // Distributed under the MIT/X11 software license, see the accompanying
genesis 4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
genesis 5
genesis 6 #include "headers.h"
genesis 7 #include "db.h"
genesis 8 #include "net.h"
genesis 9 #include <boost/filesystem.hpp>
genesis 10 #include <boost/filesystem/fstream.hpp>
genesis 11
mod6_manifest 12 // v0.5.4 RELEASE (keccak)
makefiles 13
genesis 14 using namespace std;
genesis 15 using namespace boost;
genesis 16
genesis 17
genesis 18 unsigned int nWalletDBUpdated;
genesis 19 uint64 nAccountingEntryNumber = 0;
genesis 20
genesis 21
genesis 22
genesis 23 //
genesis 24 // CDB
genesis 25 //
genesis 26
genesis 27 static CCriticalSection cs_db;
genesis 28 static bool fDbEnvInit = false;
genesis 29 DbEnv dbenv(0);
genesis 30 static map<string, int> mapFileUseCount;
genesis 31 static map<string, Db*> mapDb;
genesis 32
genesis 33 static void EnvShutdown()
genesis 34 {
genesis 35 if (!fDbEnvInit)
genesis 36 return;
genesis 37
genesis 38 fDbEnvInit = false;
genesis 39 try
genesis 40 {
genesis 41 dbenv.close(0);
genesis 42 }
genesis 43 catch (const DbException& e)
genesis 44 {
genesis 45 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
genesis 46 }
genesis 47 DbEnv(0).remove(GetDataDir().c_str(), 0);
genesis 48 }
genesis 49
genesis 50 class CDBInit
genesis 51 {
genesis 52 public:
genesis 53 CDBInit()
genesis 54 {
genesis 55 }
genesis 56 ~CDBInit()
genesis 57 {
genesis 58 EnvShutdown();
genesis 59 }
genesis 60 }
genesis 61 instance_of_cdbinit;
genesis 62
genesis 63
genesis 64 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
genesis 65 {
genesis 66 int ret;
genesis 67 if (pszFile == NULL)
genesis 68 return;
genesis 69
genesis 70 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
genesis 71 bool fCreate = strchr(pszMode, 'c');
genesis 72 unsigned int nFlags = DB_THREAD;
genesis 73 if (fCreate)
genesis 74 nFlags |= DB_CREATE;
genesis 75
genesis 76 CRITICAL_BLOCK(cs_db)
genesis 77 {
genesis 78 if (!fDbEnvInit)
genesis 79 {
genesis 80 if (fShutdown)
genesis 81 return;
genesis 82 string strDataDir = GetDataDir();
genesis 83 string strLogDir = strDataDir + "/database";
genesis 84 filesystem::create_directory(strLogDir.c_str());
genesis 85 string strErrorFile = strDataDir + "/db.log";
genesis 86 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
genesis 87
genesis 88 dbenv.set_lg_dir(strLogDir.c_str());
bitcoin-v0_5_3-db... 89 dbenv.set_lg_max(1000000);
asciilifeform_max... 90 dbenv.set_lk_max_locks(2737000);
asciilifeform_max... 91 dbenv.set_lk_max_objects(1119200);
asciilifeform_max... 92 dbenv.set_lk_max_lockers(1119200);
genesis 93 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
genesis 94 dbenv.set_flags(DB_AUTO_COMMIT, 1);
bitcoin-v0_5_3-db... 95 dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
bitcoin-v0_5_3-db... 96 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
genesis 97 ret = dbenv.open(strDataDir.c_str(),
genesis 98 DB_CREATE |
genesis 99 DB_INIT_LOCK |
genesis 100 DB_INIT_LOG |
genesis 101 DB_INIT_MPOOL |
genesis 102 DB_INIT_TXN |
genesis 103 DB_THREAD |
genesis 104 DB_RECOVER,
genesis 105 S_IRUSR | S_IWUSR);
genesis 106 if (ret > 0)
genesis 107 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
genesis 108 fDbEnvInit = true;
genesis 109 }
genesis 110
genesis 111 strFile = pszFile;
genesis 112 ++mapFileUseCount[strFile];
genesis 113 pdb = mapDb[strFile];
genesis 114 if (pdb == NULL)
genesis 115 {
genesis 116 pdb = new Db(&dbenv, 0);
genesis 117
genesis 118 ret = pdb->open(NULL, // Txn pointer
genesis 119 pszFile, // Filename
genesis 120 "main", // Logical db name
genesis 121 DB_BTREE, // Database type
genesis 122 nFlags, // Flags
genesis 123 0);
genesis 124
genesis 125 if (ret > 0)
genesis 126 {
genesis 127 delete pdb;
genesis 128 pdb = NULL;
genesis 129 CRITICAL_BLOCK(cs_db)
genesis 130 --mapFileUseCount[strFile];
genesis 131 strFile = "";
genesis 132 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
genesis 133 }
genesis 134
genesis 135 if (fCreate && !Exists(string("version")))
genesis 136 {
genesis 137 bool fTmp = fReadOnly;
genesis 138 fReadOnly = false;
genesis 139 WriteVersion(VERSION);
genesis 140 fReadOnly = fTmp;
genesis 141 }
genesis 142
genesis 143 mapDb[strFile] = pdb;
genesis 144 }
genesis 145 }
genesis 146 }
genesis 147
genesis 148 void CDB::Close()
genesis 149 {
genesis 150 if (!pdb)
genesis 151 return;
genesis 152 if (!vTxn.empty())
genesis 153 vTxn.front()->abort();
genesis 154 vTxn.clear();
genesis 155 pdb = NULL;
genesis 156
genesis 157 // Flush database activity from memory pool to disk log
genesis 158 unsigned int nMinutes = 0;
genesis 159 if (fReadOnly)
genesis 160 nMinutes = 1;
genesis 161 if (strFile == "addr.dat")
genesis 162 nMinutes = 2;
genesis 163 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
genesis 164 nMinutes = 1;
genesis 165 dbenv.txn_checkpoint(0, nMinutes, 0);
genesis 166
genesis 167 CRITICAL_BLOCK(cs_db)
genesis 168 --mapFileUseCount[strFile];
genesis 169 }
genesis 170
genesis 171 void static CloseDb(const string& strFile)
genesis 172 {
genesis 173 CRITICAL_BLOCK(cs_db)
genesis 174 {
genesis 175 if (mapDb[strFile] != NULL)
genesis 176 {
genesis 177 // Close the database handle
genesis 178 Db* pdb = mapDb[strFile];
genesis 179 pdb->close(0);
genesis 180 delete pdb;
genesis 181 mapDb[strFile] = NULL;
genesis 182 }
genesis 183 }
genesis 184 }
genesis 185
genesis 186 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
genesis 187 {
genesis 188 while (!fShutdown)
genesis 189 {
genesis 190 CRITICAL_BLOCK(cs_db)
genesis 191 {
genesis 192 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
genesis 193 {
genesis 194 // Flush log data to the dat file
genesis 195 CloseDb(strFile);
genesis 196 dbenv.txn_checkpoint(0, 0, 0);
genesis 197 dbenv.lsn_reset(strFile.c_str(), 0);
genesis 198 mapFileUseCount.erase(strFile);
genesis 199
genesis 200 bool fSuccess = true;
genesis 201 printf("Rewriting %s...\n", strFile.c_str());
genesis 202 string strFileRes = strFile + ".rewrite";
genesis 203 { // surround usage of db with extra {}
genesis 204 CDB db(strFile.c_str(), "r");
genesis 205 Db* pdbCopy = new Db(&dbenv, 0);
genesis 206
genesis 207 int ret = pdbCopy->open(NULL, // Txn pointer
genesis 208 strFileRes.c_str(), // Filename
genesis 209 "main", // Logical db name
genesis 210 DB_BTREE, // Database type
genesis 211 DB_CREATE, // Flags
genesis 212 0);
genesis 213 if (ret > 0)
genesis 214 {
genesis 215 printf("Cannot create database file %s\n", strFileRes.c_str());
genesis 216 fSuccess = false;
genesis 217 }
genesis 218
genesis 219 Dbc* pcursor = db.GetCursor();
genesis 220 if (pcursor)
genesis 221 while (fSuccess)
genesis 222 {
genesis 223 CDataStream ssKey;
genesis 224 CDataStream ssValue;
genesis 225 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
genesis 226 if (ret == DB_NOTFOUND)
genesis 227 {
genesis 228 pcursor->close();
genesis 229 break;
genesis 230 }
genesis 231 else if (ret != 0)
genesis 232 {
genesis 233 pcursor->close();
genesis 234 fSuccess = false;
genesis 235 break;
genesis 236 }
genesis 237 if (pszSkip &&
genesis 238 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
genesis 239 continue;
genesis 240 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
genesis 241 {
genesis 242 // Update version:
genesis 243 ssValue.clear();
genesis 244 ssValue << VERSION;
genesis 245 }
genesis 246 Dbt datKey(&ssKey[0], ssKey.size());
genesis 247 Dbt datValue(&ssValue[0], ssValue.size());
genesis 248 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
genesis 249 if (ret2 > 0)
genesis 250 fSuccess = false;
genesis 251 }
genesis 252 if (fSuccess)
genesis 253 {
genesis 254 db.Close();
genesis 255 CloseDb(strFile);
genesis 256 if (pdbCopy->close(0))
genesis 257 fSuccess = false;
genesis 258 delete pdbCopy;
genesis 259 }
genesis 260 }
genesis 261 if (fSuccess)
genesis 262 {
genesis 263 Db dbA(&dbenv, 0);
genesis 264 if (dbA.remove(strFile.c_str(), NULL, 0))
genesis 265 fSuccess = false;
genesis 266 Db dbB(&dbenv, 0);
genesis 267 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
genesis 268 fSuccess = false;
genesis 269 }
genesis 270 if (!fSuccess)
genesis 271 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
genesis 272 return fSuccess;
genesis 273 }
genesis 274 }
genesis 275 Sleep(100);
genesis 276 }
genesis 277 return false;
genesis 278 }
genesis 279
genesis 280
genesis 281 void DBFlush(bool fShutdown)
genesis 282 {
genesis 283 // Flush log data to the actual data file
genesis 284 // on all files that are not in use
genesis 285 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
genesis 286 if (!fDbEnvInit)
genesis 287 return;
genesis 288 CRITICAL_BLOCK(cs_db)
genesis 289 {
genesis 290 map<string, int>::iterator mi = mapFileUseCount.begin();
genesis 291 while (mi != mapFileUseCount.end())
genesis 292 {
genesis 293 string strFile = (*mi).first;
genesis 294 int nRefCount = (*mi).second;
genesis 295 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
genesis 296 if (nRefCount == 0)
genesis 297 {
genesis 298 // Move log data to the dat file
genesis 299 CloseDb(strFile);
genesis 300 dbenv.txn_checkpoint(0, 0, 0);
genesis 301 printf("%s flush\n", strFile.c_str());
genesis 302 dbenv.lsn_reset(strFile.c_str(), 0);
genesis 303 mapFileUseCount.erase(mi++);
genesis 304 }
genesis 305 else
genesis 306 mi++;
genesis 307 }
genesis 308 if (fShutdown)
genesis 309 {
genesis 310 char** listp;
genesis 311 if (mapFileUseCount.empty())
genesis 312 {
genesis 313 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
genesis 314 EnvShutdown();
genesis 315 }
genesis 316 }
genesis 317 }
genesis 318 }
genesis 319
genesis 320
genesis 321
genesis 322
genesis 323
genesis 324
genesis 325 //
genesis 326 // CTxDB
genesis 327 //
genesis 328
genesis 329 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
genesis 330 {
genesis 331 assert(!fClient);
genesis 332 txindex.SetNull();
genesis 333 return Read(make_pair(string("tx"), hash), txindex);
genesis 334 }
genesis 335
genesis 336 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
genesis 337 {
genesis 338 assert(!fClient);
genesis 339 return Write(make_pair(string("tx"), hash), txindex);
genesis 340 }
genesis 341
genesis 342 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
genesis 343 {
genesis 344 assert(!fClient);
genesis 345
genesis 346 // Add to tx index
genesis 347 uint256 hash = tx.GetHash();
genesis 348 CTxIndex txindex(pos, tx.vout.size());
genesis 349 return Write(make_pair(string("tx"), hash), txindex);
genesis 350 }
genesis 351
genesis 352 bool CTxDB::EraseTxIndex(const CTransaction& tx)
genesis 353 {
genesis 354 assert(!fClient);
genesis 355 uint256 hash = tx.GetHash();
genesis 356
genesis 357 return Erase(make_pair(string("tx"), hash));
genesis 358 }
genesis 359
genesis 360 bool CTxDB::ContainsTx(uint256 hash)
genesis 361 {
genesis 362 assert(!fClient);
genesis 363 return Exists(make_pair(string("tx"), hash));
genesis 364 }
genesis 365
genesis 366 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
genesis 367 {
genesis 368 assert(!fClient);
genesis 369 vtx.clear();
genesis 370
genesis 371 // Get cursor
genesis 372 Dbc* pcursor = GetCursor();
genesis 373 if (!pcursor)
genesis 374 return false;
genesis 375
genesis 376 unsigned int fFlags = DB_SET_RANGE;
genesis 377 loop
genesis 378 {
genesis 379 // Read next record
genesis 380 CDataStream ssKey;
genesis 381 if (fFlags == DB_SET_RANGE)
genesis 382 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
genesis 383 CDataStream ssValue;
genesis 384 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
genesis 385 fFlags = DB_NEXT;
genesis 386 if (ret == DB_NOTFOUND)
genesis 387 break;
genesis 388 else if (ret != 0)
genesis 389 {
genesis 390 pcursor->close();
genesis 391 return false;
genesis 392 }
genesis 393
genesis 394 // Unserialize
genesis 395 string strType;
genesis 396 uint160 hashItem;
genesis 397 CDiskTxPos pos;
genesis 398 ssKey >> strType >> hashItem >> pos;
genesis 399 int nItemHeight;
genesis 400 ssValue >> nItemHeight;
genesis 401
genesis 402 // Read transaction
genesis 403 if (strType != "owner" || hashItem != hash160)
genesis 404 break;
genesis 405 if (nItemHeight >= nMinHeight)
genesis 406 {
genesis 407 vtx.resize(vtx.size()+1);
genesis 408 if (!vtx.back().ReadFromDisk(pos))
genesis 409 {
genesis 410 pcursor->close();
genesis 411 return false;
genesis 412 }
genesis 413 }
genesis 414 }
genesis 415
genesis 416 pcursor->close();
genesis 417 return true;
genesis 418 }
genesis 419
genesis 420 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
genesis 421 {
genesis 422 assert(!fClient);
genesis 423 tx.SetNull();
genesis 424 if (!ReadTxIndex(hash, txindex))
genesis 425 return false;
genesis 426 return (tx.ReadFromDisk(txindex.pos));
genesis 427 }
genesis 428
genesis 429 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
genesis 430 {
genesis 431 CTxIndex txindex;
genesis 432 return ReadDiskTx(hash, tx, txindex);
genesis 433 }
genesis 434
genesis 435 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
genesis 436 {
genesis 437 return ReadDiskTx(outpoint.hash, tx, txindex);
genesis 438 }
genesis 439
genesis 440 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
genesis 441 {
genesis 442 CTxIndex txindex;
genesis 443 return ReadDiskTx(outpoint.hash, tx, txindex);
genesis 444 }
genesis 445
genesis 446 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
genesis 447 {
genesis 448 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
genesis 449 }
genesis 450
genesis 451 bool CTxDB::EraseBlockIndex(uint256 hash)
genesis 452 {
genesis 453 return Erase(make_pair(string("blockindex"), hash));
genesis 454 }
genesis 455
genesis 456 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
genesis 457 {
genesis 458 return Read(string("hashBestChain"), hashBestChain);
genesis 459 }
genesis 460
genesis 461 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
genesis 462 {
genesis 463 return Write(string("hashBestChain"), hashBestChain);
genesis 464 }
genesis 465
genesis 466 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
genesis 467 {
genesis 468 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
genesis 469 }
genesis 470
genesis 471 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
genesis 472 {
genesis 473 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
genesis 474 }
genesis 475
genesis 476 CBlockIndex static * InsertBlockIndex(uint256 hash)
genesis 477 {
genesis 478 if (hash == 0)
genesis 479 return NULL;
genesis 480
genesis 481 // Return existing
genesis 482 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
genesis 483 if (mi != mapBlockIndex.end())
genesis 484 return (*mi).second;
genesis 485
genesis 486 // Create new
genesis 487 CBlockIndex* pindexNew = new CBlockIndex();
genesis 488 if (!pindexNew)
genesis 489 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
genesis 490 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
genesis 491 pindexNew->phashBlock = &((*mi).first);
genesis 492
genesis 493 return pindexNew;
genesis 494 }
genesis 495
genesis 496 bool CTxDB::LoadBlockIndex()
genesis 497 {
genesis 498 // Get database cursor
genesis 499 Dbc* pcursor = GetCursor();
genesis 500 if (!pcursor)
genesis 501 return false;
genesis 502
genesis 503 // Load mapBlockIndex
genesis 504 unsigned int fFlags = DB_SET_RANGE;
genesis 505 loop
genesis 506 {
genesis 507 // Read next record
genesis 508 CDataStream ssKey;
genesis 509 if (fFlags == DB_SET_RANGE)
genesis 510 ssKey << make_pair(string("blockindex"), uint256(0));
genesis 511 CDataStream ssValue;
genesis 512 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
genesis 513 fFlags = DB_NEXT;
genesis 514 if (ret == DB_NOTFOUND)
genesis 515 break;
genesis 516 else if (ret != 0)
genesis 517 return false;
genesis 518
genesis 519 // Unserialize
genesis 520 string strType;
genesis 521 ssKey >> strType;
genesis 522 if (strType == "blockindex")
genesis 523 {
genesis 524 CDiskBlockIndex diskindex;
genesis 525 ssValue >> diskindex;
genesis 526
genesis 527 // Construct block index object
genesis 528 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
genesis 529 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
genesis 530 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
genesis 531 pindexNew->nFile = diskindex.nFile;
genesis 532 pindexNew->nBlockPos = diskindex.nBlockPos;
genesis 533 pindexNew->nHeight = diskindex.nHeight;
genesis 534 pindexNew->nVersion = diskindex.nVersion;
genesis 535 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
genesis 536 pindexNew->nTime = diskindex.nTime;
genesis 537 pindexNew->nBits = diskindex.nBits;
genesis 538 pindexNew->nNonce = diskindex.nNonce;
genesis 539
genesis 540 // Watch for genesis block
genesis 541 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
genesis 542 pindexGenesisBlock = pindexNew;
genesis 543
genesis 544 if (!pindexNew->CheckIndex())
genesis 545 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
genesis 546 }
genesis 547 else
genesis 548 {
genesis 549 break;
genesis 550 }
genesis 551 }
genesis 552 pcursor->close();
genesis 553
genesis 554 // Calculate bnChainWork
genesis 555 vector<pair<int, CBlockIndex*> > vSortedByHeight;
genesis 556 vSortedByHeight.reserve(mapBlockIndex.size());
genesis 557 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
genesis 558 {
genesis 559 CBlockIndex* pindex = item.second;
genesis 560 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
genesis 561 }
genesis 562 sort(vSortedByHeight.begin(), vSortedByHeight.end());
genesis 563 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
genesis 564 {
genesis 565 CBlockIndex* pindex = item.second;
genesis 566 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
genesis 567 }
genesis 568
genesis 569 // Load hashBestChain pointer to end of best chain
genesis 570 if (!ReadHashBestChain(hashBestChain))
genesis 571 {
genesis 572 if (pindexGenesisBlock == NULL)
genesis 573 return true;
genesis 574 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
genesis 575 }
genesis 576 if (!mapBlockIndex.count(hashBestChain))
genesis 577 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
genesis 578 pindexBest = mapBlockIndex[hashBestChain];
genesis 579 nBestHeight = pindexBest->nHeight;
genesis 580 bnBestChainWork = pindexBest->bnChainWork;
mod6_excise_hash_... 581 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().c_str(), nBestHeight);
genesis 582
genesis 583 // Load bnBestInvalidWork, OK if it doesn't exist
genesis 584 ReadBestInvalidWork(bnBestInvalidWork);
genesis 585
genesis 586 // Verify blocks in the best chain
genesis 587 CBlockIndex* pindexFork = NULL;
genesis 588 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
genesis 589 {
genesis 590 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
genesis 591 break;
genesis 592 CBlock block;
genesis 593 if (!block.ReadFromDisk(pindex))
genesis 594 return error("LoadBlockIndex() : block.ReadFromDisk failed");
genesis 595 if (!block.CheckBlock())
genesis 596 {
genesis 597 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
genesis 598 pindexFork = pindex->pprev;
genesis 599 }
genesis 600 }
genesis 601 if (pindexFork)
genesis 602 {
genesis 603 // Reorg back to the fork
genesis 604 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
genesis 605 CBlock block;
genesis 606 if (!block.ReadFromDisk(pindexFork))
genesis 607 return error("LoadBlockIndex() : block.ReadFromDisk failed");
genesis 608 CTxDB txdb;
genesis 609 block.SetBestChain(txdb, pindexFork);
genesis 610 }
genesis 611
genesis 612 return true;
genesis 613 }
genesis 614
genesis 615
genesis 616
genesis 617
genesis 618
genesis 619 //
genesis 620 // CAddrDB
genesis 621 //
genesis 622
genesis 623 bool CAddrDB::WriteAddress(const CAddress& addr)
genesis 624 {
genesis 625 return Write(make_pair(string("addr"), addr.GetKey()), addr);
genesis 626 }
genesis 627
genesis 628 bool CAddrDB::EraseAddress(const CAddress& addr)
genesis 629 {
genesis 630 return Erase(make_pair(string("addr"), addr.GetKey()));
genesis 631 }
genesis 632
genesis 633 bool CAddrDB::LoadAddresses()
genesis 634 {
genesis 635 CRITICAL_BLOCK(cs_mapAddresses)
genesis 636 {
genesis 637 // Get cursor
genesis 638 Dbc* pcursor = GetCursor();
genesis 639 if (!pcursor)
genesis 640 return false;
genesis 641
genesis 642 loop
genesis 643 {
genesis 644 // Read next record
genesis 645 CDataStream ssKey;
genesis 646 CDataStream ssValue;
genesis 647 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
genesis 648 if (ret == DB_NOTFOUND)
genesis 649 break;
genesis 650 else if (ret != 0)
genesis 651 return false;
genesis 652
genesis 653 // Unserialize
genesis 654 string strType;
genesis 655 ssKey >> strType;
genesis 656 if (strType == "addr")
genesis 657 {
genesis 658 CAddress addr;
genesis 659 ssValue >> addr;
genesis 660 mapAddresses.insert(make_pair(addr.GetKey(), addr));
genesis 661 }
genesis 662 }
genesis 663 pcursor->close();
genesis 664
genesis 665 printf("Loaded %d addresses\n", mapAddresses.size());
genesis 666 }
genesis 667
genesis 668 return true;
genesis 669 }
genesis 670
genesis 671 bool LoadAddresses()
genesis 672 {
genesis 673 return CAddrDB("cr+").LoadAddresses();
genesis 674 }
genesis 675
genesis 676
genesis 677
genesis 678
genesis 679 //
genesis 680 // CWalletDB
genesis 681 //
genesis 682
genesis 683 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
genesis 684 {
genesis 685 nWalletDBUpdated++;
genesis 686 return Write(make_pair(string("name"), strAddress), strName);
genesis 687 }
genesis 688
genesis 689 bool CWalletDB::EraseName(const string& strAddress)
genesis 690 {
genesis 691 // This should only be used for sending addresses, never for receiving addresses,
genesis 692 // receiving addresses must always have an address book entry if they're not change return.
genesis 693 nWalletDBUpdated++;
genesis 694 return Erase(make_pair(string("name"), strAddress));
genesis 695 }
genesis 696
genesis 697 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
genesis 698 {
genesis 699 account.SetNull();
genesis 700 return Read(make_pair(string("acc"), strAccount), account);
genesis 701 }
genesis 702
genesis 703 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
genesis 704 {
genesis 705 return Write(make_pair(string("acc"), strAccount), account);
genesis 706 }
genesis 707
genesis 708 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
genesis 709 {
genesis 710 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
genesis 711 }
genesis 712
genesis 713 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
genesis 714 {
genesis 715 list<CAccountingEntry> entries;
genesis 716 ListAccountCreditDebit(strAccount, entries);
genesis 717
genesis 718 int64 nCreditDebit = 0;
genesis 719 BOOST_FOREACH (const CAccountingEntry& entry, entries)
genesis 720 nCreditDebit += entry.nCreditDebit;
genesis 721
genesis 722 return nCreditDebit;
genesis 723 }
genesis 724
genesis 725 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
genesis 726 {
genesis 727 bool fAllAccounts = (strAccount == "*");
genesis 728
genesis 729 Dbc* pcursor = GetCursor();
genesis 730 if (!pcursor)
genesis 731 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
genesis 732 unsigned int fFlags = DB_SET_RANGE;
genesis 733 loop
genesis 734 {
genesis 735 // Read next record
genesis 736 CDataStream ssKey;
genesis 737 if (fFlags == DB_SET_RANGE)
genesis 738 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
genesis 739 CDataStream ssValue;
genesis 740 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
genesis 741 fFlags = DB_NEXT;
genesis 742 if (ret == DB_NOTFOUND)
genesis 743 break;
genesis 744 else if (ret != 0)
genesis 745 {
genesis 746 pcursor->close();
genesis 747 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
genesis 748 }
genesis 749
genesis 750 // Unserialize
genesis 751 string strType;
genesis 752 ssKey >> strType;
genesis 753 if (strType != "acentry")
genesis 754 break;
genesis 755 CAccountingEntry acentry;
genesis 756 ssKey >> acentry.strAccount;
genesis 757 if (!fAllAccounts && acentry.strAccount != strAccount)
genesis 758 break;
genesis 759
genesis 760 ssValue >> acentry;
genesis 761 entries.push_back(acentry);
genesis 762 }
genesis 763
genesis 764 pcursor->close();
genesis 765 }
genesis 766
genesis 767
genesis 768 int CWalletDB::LoadWallet(CWallet* pwallet)
genesis 769 {
genesis 770 pwallet->vchDefaultKey.clear();
genesis 771 int nFileVersion = 0;
genesis 772 vector<uint256> vWalletUpgrade;
genesis 773 bool fIsEncrypted = false;
genesis 774
genesis 775 // Modify defaults
genesis 776 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
genesis 777 fMinimizeToTray = false;
genesis 778 fMinimizeOnClose = false;
genesis 779
genesis 780 //// todo: shouldn't we catch exceptions and try to recover and continue?
genesis 781 CRITICAL_BLOCK(pwallet->cs_wallet)
genesis 782 {
genesis 783 // Get cursor
genesis 784 Dbc* pcursor = GetCursor();
genesis 785 if (!pcursor)
genesis 786 return DB_CORRUPT;
genesis 787
genesis 788 loop
genesis 789 {
genesis 790 // Read next record
genesis 791 CDataStream ssKey;
genesis 792 CDataStream ssValue;
genesis 793 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
genesis 794 if (ret == DB_NOTFOUND)
genesis 795 break;
genesis 796 else if (ret != 0)
genesis 797 return DB_CORRUPT;
genesis 798
genesis 799 // Unserialize
genesis 800 // Taking advantage of the fact that pair serialization
genesis 801 // is just the two items serialized one after the other
genesis 802 string strType;
genesis 803 ssKey >> strType;
genesis 804 if (strType == "name")
genesis 805 {
genesis 806 string strAddress;
genesis 807 ssKey >> strAddress;
genesis 808 ssValue >> pwallet->mapAddressBook[strAddress];
genesis 809 }
genesis 810 else if (strType == "tx")
genesis 811 {
genesis 812 uint256 hash;
genesis 813 ssKey >> hash;
genesis 814 CWalletTx& wtx = pwallet->mapWallet[hash];
genesis 815 ssValue >> wtx;
genesis 816 wtx.pwallet = pwallet;
genesis 817
genesis 818 if (wtx.GetHash() != hash)
genesis 819 printf("Error in wallet.dat, hash mismatch\n");
genesis 820
genesis 821 // Undo serialize changes in 31600
genesis 822 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
genesis 823 {
genesis 824 if (!ssValue.empty())
genesis 825 {
genesis 826 char fTmp;
genesis 827 char fUnused;
genesis 828 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
genesis 829 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
genesis 830 wtx.fTimeReceivedIsTxTime = fTmp;
genesis 831 }
genesis 832 else
genesis 833 {
genesis 834 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
genesis 835 wtx.fTimeReceivedIsTxTime = 0;
genesis 836 }
genesis 837 vWalletUpgrade.push_back(hash);
genesis 838 }
genesis 839 }
genesis 840 else if (strType == "acentry")
genesis 841 {
genesis 842 string strAccount;
genesis 843 ssKey >> strAccount;
genesis 844 uint64 nNumber;
genesis 845 ssKey >> nNumber;
genesis 846 if (nNumber > nAccountingEntryNumber)
genesis 847 nAccountingEntryNumber = nNumber;
genesis 848 }
genesis 849 else if (strType == "key" || strType == "wkey")
genesis 850 {
genesis 851 vector<unsigned char> vchPubKey;
genesis 852 ssKey >> vchPubKey;
genesis 853 CKey key;
genesis 854 if (strType == "key")
genesis 855 {
genesis 856 CPrivKey pkey;
genesis 857 ssValue >> pkey;
genesis 858 key.SetPrivKey(pkey);
genesis 859 if (key.GetPubKey() != vchPubKey || !key.IsValid())
genesis 860 return DB_CORRUPT;
genesis 861 }
genesis 862 else
genesis 863 {
genesis 864 CWalletKey wkey;
genesis 865 ssValue >> wkey;
genesis 866 key.SetPrivKey(wkey.vchPrivKey);
genesis 867 if (key.GetPubKey() != vchPubKey || !key.IsValid())
genesis 868 return DB_CORRUPT;
genesis 869 }
genesis 870 if (!pwallet->LoadKey(key))
genesis 871 return DB_CORRUPT;
genesis 872 }
genesis 873 else if (strType == "mkey")
genesis 874 {
genesis 875 unsigned int nID;
genesis 876 ssKey >> nID;
genesis 877 CMasterKey kMasterKey;
genesis 878 ssValue >> kMasterKey;
genesis 879 if(pwallet->mapMasterKeys.count(nID) != 0)
genesis 880 return DB_CORRUPT;
genesis 881 pwallet->mapMasterKeys[nID] = kMasterKey;
genesis 882 if (pwallet->nMasterKeyMaxID < nID)
genesis 883 pwallet->nMasterKeyMaxID = nID;
genesis 884 }
genesis 885 else if (strType == "ckey")
genesis 886 {
genesis 887 vector<unsigned char> vchPubKey;
genesis 888 ssKey >> vchPubKey;
genesis 889 vector<unsigned char> vchPrivKey;
genesis 890 ssValue >> vchPrivKey;
genesis 891 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
genesis 892 return DB_CORRUPT;
genesis 893 fIsEncrypted = true;
genesis 894 }
genesis 895 else if (strType == "defaultkey")
genesis 896 {
genesis 897 ssValue >> pwallet->vchDefaultKey;
genesis 898 }
genesis 899 else if (strType == "pool")
genesis 900 {
genesis 901 int64 nIndex;
genesis 902 ssKey >> nIndex;
genesis 903 pwallet->setKeyPool.insert(nIndex);
genesis 904 }
genesis 905 else if (strType == "version")
genesis 906 {
genesis 907 ssValue >> nFileVersion;
genesis 908 if (nFileVersion == 10300)
genesis 909 nFileVersion = 300;
genesis 910 }
genesis 911 else if (strType == "setting")
genesis 912 {
genesis 913 string strKey;
genesis 914 ssKey >> strKey;
genesis 915
genesis 916 // Options
genesis 917 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
genesis 918 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
genesis 919 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
genesis 920 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
genesis 921 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
genesis 922 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
genesis 923 if (strKey == "fUseProxy") ssValue >> fUseProxy;
genesis 924 if (strKey == "addrProxy") ssValue >> addrProxy;
genesis 925 }
genesis 926 else if (strType == "minversion")
genesis 927 {
genesis 928 int nMinVersion = 0;
genesis 929 ssValue >> nMinVersion;
genesis 930 if (nMinVersion > VERSION)
genesis 931 return DB_TOO_NEW;
genesis 932 }
genesis 933 }
genesis 934 pcursor->close();
genesis 935 }
genesis 936
genesis 937 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
genesis 938 WriteTx(hash, pwallet->mapWallet[hash]);
genesis 939
genesis 940 printf("nFileVersion = %d\n", nFileVersion);
genesis 941 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
genesis 942 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
genesis 943 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
genesis 944 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
genesis 945 printf("fUseProxy = %d\n", fUseProxy);
genesis 946 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
genesis 947
genesis 948 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
genesis 949 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
genesis 950 return DB_NEED_REWRITE;
genesis 951
genesis 952 if (nFileVersion < VERSION) // Update
genesis 953 {
genesis 954 // Get rid of old debug.log file in current directory
genesis 955 if (nFileVersion <= 105 && !pszSetDataDir[0])
genesis 956 unlink("debug.log");
genesis 957
genesis 958 WriteVersion(VERSION);
genesis 959 }
genesis 960
genesis 961 return DB_LOAD_OK;
genesis 962 }
genesis 963
genesis 964 void ThreadFlushWalletDB(void* parg)
genesis 965 {
genesis 966 const string& strFile = ((const string*)parg)[0];
genesis 967 static bool fOneThread;
genesis 968 if (fOneThread)
genesis 969 return;
genesis 970 fOneThread = true;
genesis 971 if (mapArgs.count("-noflushwallet"))
genesis 972 return;
genesis 973
genesis 974 unsigned int nLastSeen = nWalletDBUpdated;
genesis 975 unsigned int nLastFlushed = nWalletDBUpdated;
genesis 976 int64 nLastWalletUpdate = GetTime();
genesis 977 while (!fShutdown)
genesis 978 {
genesis 979 Sleep(500);
genesis 980
genesis 981 if (nLastSeen != nWalletDBUpdated)
genesis 982 {
genesis 983 nLastSeen = nWalletDBUpdated;
genesis 984 nLastWalletUpdate = GetTime();
genesis 985 }
genesis 986
genesis 987 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
genesis 988 {
genesis 989 TRY_CRITICAL_BLOCK(cs_db)
genesis 990 {
genesis 991 // Don't do this if any databases are in use
genesis 992 int nRefCount = 0;
genesis 993 map<string, int>::iterator mi = mapFileUseCount.begin();
genesis 994 while (mi != mapFileUseCount.end())
genesis 995 {
genesis 996 nRefCount += (*mi).second;
genesis 997 mi++;
genesis 998 }
genesis 999
genesis 1000 if (nRefCount == 0 && !fShutdown)
genesis 1001 {
genesis 1002 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
genesis 1003 if (mi != mapFileUseCount.end())
genesis 1004 {
genesis 1005 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
genesis 1006 printf("Flushing wallet.dat\n");
genesis 1007 nLastFlushed = nWalletDBUpdated;
genesis 1008 int64 nStart = GetTimeMillis();
genesis 1009
genesis 1010 // Flush wallet.dat so it's self contained
genesis 1011 CloseDb(strFile);
genesis 1012 dbenv.txn_checkpoint(0, 0, 0);
genesis 1013 dbenv.lsn_reset(strFile.c_str(), 0);
genesis 1014
genesis 1015 mapFileUseCount.erase(mi++);
genesis 1016 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 1017 }
genesis 1018 }
genesis 1019 }
genesis 1020 }
genesis 1021 }
genesis 1022 }
genesis 1023
genesis 1024 bool BackupWallet(const CWallet& wallet, const string& strDest)
genesis 1025 {
genesis 1026 if (!wallet.fFileBacked)
genesis 1027 return false;
genesis 1028 while (!fShutdown)
genesis 1029 {
genesis 1030 CRITICAL_BLOCK(cs_db)
genesis 1031 {
genesis 1032 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
genesis 1033 {
genesis 1034 // Flush log data to the dat file
genesis 1035 CloseDb(wallet.strWalletFile);
genesis 1036 dbenv.txn_checkpoint(0, 0, 0);
genesis 1037 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
genesis 1038 mapFileUseCount.erase(wallet.strWalletFile);
genesis 1039
genesis 1040 // Copy wallet.dat
genesis 1041 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
genesis 1042 filesystem::path pathDest(strDest);
genesis 1043 if (filesystem::is_directory(pathDest))
genesis 1044 pathDest = pathDest / wallet.strWalletFile;
genesis 1045 #if BOOST_VERSION >= 104000
genesis 1046 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
genesis 1047 #else
genesis 1048 filesystem::copy_file(pathSrc, pathDest);
genesis 1049 #endif
genesis 1050 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
genesis 1051
genesis 1052 return true;
genesis 1053 }
genesis 1054 }
genesis 1055 Sleep(100);
genesis 1056 }
genesis 1057 return false;
genesis 1058 }