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