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