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