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