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