Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.1.3 · 2009-01-12

db.cpp

608 lines · plain text · MIT license (license.txt)
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6789101112//13// CDB14//1516static CCriticalSection cs_db;17static bool fDbEnvInit = false;18DbEnv dbenv(0);19static map<string, int> mapFileUseCount;2021class CDBInit22{23public:24    CDBInit()25    {26    }27    ~CDBInit()28    {29        if (fDbEnvInit)30        {31            dbenv.close(0);32            fDbEnvInit = false;33        }34    }35}36instance_of_cdbinit;373839CDB::CDB(const char* pszFile, const char* pszMode, bool fTxn) : pdb(NULL)40{41    int ret;42    if (pszFile == NULL)43        return;4445    bool fCreate = strchr(pszMode, 'c');46    bool fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));47    unsigned int nFlags = DB_THREAD;48    if (fCreate)49        nFlags |= DB_CREATE;50    else if (fReadOnly)51        nFlags |= DB_RDONLY;52    if (!fReadOnly || fTxn)53        nFlags |= DB_AUTO_COMMIT;5455    CRITICAL_BLOCK(cs_db)56    {57        if (!fDbEnvInit)58        {59            string strAppDir = GetAppDir();60            string strLogDir = strAppDir + "\\database";61            _mkdir(strLogDir.c_str());62            printf("dbenv.open strAppDir=%s\n", strAppDir.c_str());6364            dbenv.set_lg_dir(strLogDir.c_str());65            dbenv.set_lg_max(10000000);66            dbenv.set_lk_max_locks(10000);67            dbenv.set_lk_max_objects(10000);68            dbenv.set_errfile(fopen("db.log", "a")); /// debug69            ///dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1); /// causes corruption70            ret = dbenv.open(strAppDir.c_str(),71                             DB_CREATE     |72                             DB_INIT_LOCK  |73                             DB_INIT_LOG   |74                             DB_INIT_MPOOL |75                             DB_INIT_TXN   |76                             DB_THREAD     |77                             DB_PRIVATE    |78                             DB_RECOVER,79                             0);80            if (ret > 0)81                throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));82            fDbEnvInit = true;83        }8485        strFile = pszFile;86        ++mapFileUseCount[strFile];87    }8889    pdb = new Db(&dbenv, 0);9091    ret = pdb->open(NULL,      // Txn pointer92                    pszFile,   // Filename93                    "main",    // Logical db name94                    DB_BTREE,  // Database type95                    nFlags,    // Flags96                    0);9798    if (ret > 0)99    {100        delete pdb;101        pdb = NULL;102        CRITICAL_BLOCK(cs_db)103            --mapFileUseCount[strFile];104        strFile = "";105        throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));106    }107108    if (fCreate && !Exists(string("version")))109        WriteVersion(VERSION);110111    RandAddSeed();112}113114void CDB::Close()115{116    if (!pdb)117        return;118    if (!vTxn.empty())119        vTxn.front()->abort();120    vTxn.clear();121    pdb->close(0);122    delete pdb;123    pdb = NULL;124    dbenv.txn_checkpoint(0, 0, 0);125126    CRITICAL_BLOCK(cs_db)127        --mapFileUseCount[strFile];128129    RandAddSeed();130}131132void DBFlush(bool fShutdown)133{134    // Flush log data to the actual data file135    //  on all files that are not in use136    printf("DBFlush(%s)\n", fShutdown ? "true" : "false");137    CRITICAL_BLOCK(cs_db)138    {139        dbenv.txn_checkpoint(0, 0, 0);140        map<string, int>::iterator mi = mapFileUseCount.begin();141        while (mi != mapFileUseCount.end())142        {143            string strFile = (*mi).first;144            int nRefCount = (*mi).second;145            if (nRefCount == 0)146            {147                dbenv.lsn_reset(strFile.c_str(), 0);148                mapFileUseCount.erase(mi++);149            }150            else151                mi++;152        }153        if (fShutdown)154        {155            char** listp;156            if (mapFileUseCount.empty())157                dbenv.log_archive(&listp, DB_ARCH_REMOVE);158            dbenv.close(0);159            fDbEnvInit = false;160        }161    }162}163164165166167168169//170// CTxDB171//172173bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)174{175    assert(!fClient);176    txindex.SetNull();177    return Read(make_pair(string("tx"), hash), txindex);178}179180bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)181{182    assert(!fClient);183    return Write(make_pair(string("tx"), hash), txindex);184}185186bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)187{188    assert(!fClient);189190    // Add to tx index191    uint256 hash = tx.GetHash();192    CTxIndex txindex(pos, tx.vout.size());193    return Write(make_pair(string("tx"), hash), txindex);194}195196bool CTxDB::EraseTxIndex(const CTransaction& tx)197{198    assert(!fClient);199    uint256 hash = tx.GetHash();200201    return Erase(make_pair(string("tx"), hash));202}203204bool CTxDB::ContainsTx(uint256 hash)205{206    assert(!fClient);207    return Exists(make_pair(string("tx"), hash));208}209210bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)211{212    assert(!fClient);213    vtx.clear();214215    // Get cursor216    Dbc* pcursor = GetCursor();217    if (!pcursor)218        return false;219220    unsigned int fFlags = DB_SET_RANGE;221    loop222    {223        // Read next record224        CDataStream ssKey;225        if (fFlags == DB_SET_RANGE)226            ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);227        CDataStream ssValue;228        int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);229        fFlags = DB_NEXT;230        if (ret == DB_NOTFOUND)231            break;232        else if (ret != 0)233            return false;234235        // Unserialize236        string strType;237        uint160 hashItem;238        CDiskTxPos pos;239        ssKey >> strType >> hashItem >> pos;240        int nItemHeight;241        ssValue >> nItemHeight;242243        // Read transaction244        if (strType != "owner" || hashItem != hash160)245            break;246        if (nItemHeight >= nMinHeight)247        {248            vtx.resize(vtx.size()+1);249            if (!vtx.back().ReadFromDisk(pos))250                return false;251        }252    }253    return true;254}255256bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)257{258    assert(!fClient);259    tx.SetNull();260    if (!ReadTxIndex(hash, txindex))261        return false;262    return (tx.ReadFromDisk(txindex.pos));263}264265bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)266{267    CTxIndex txindex;268    return ReadDiskTx(hash, tx, txindex);269}270271bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)272{273    return ReadDiskTx(outpoint.hash, tx, txindex);274}275276bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)277{278    CTxIndex txindex;279    return ReadDiskTx(outpoint.hash, tx, txindex);280}281282bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)283{284    return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);285}286287bool CTxDB::EraseBlockIndex(uint256 hash)288{289    return Erase(make_pair(string("blockindex"), hash));290}291292bool CTxDB::ReadHashBestChain(uint256& hashBestChain)293{294    return Read(string("hashBestChain"), hashBestChain);295}296297bool CTxDB::WriteHashBestChain(uint256 hashBestChain)298{299    return Write(string("hashBestChain"), hashBestChain);300}301302CBlockIndex* InsertBlockIndex(uint256 hash)303{304    if (hash == 0)305        return NULL;306307    // Return existing308    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);309    if (mi != mapBlockIndex.end())310        return (*mi).second;311312    // Create new313    CBlockIndex* pindexNew = new CBlockIndex();314    if (!pindexNew)315        throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");316    mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;317    pindexNew->phashBlock = &((*mi).first);318319    return pindexNew;320}321322bool CTxDB::LoadBlockIndex()323{324    // Get cursor325    Dbc* pcursor = GetCursor();326    if (!pcursor)327        return false;328329    unsigned int fFlags = DB_SET_RANGE;330    loop331    {332        // Read next record333        CDataStream ssKey;334        if (fFlags == DB_SET_RANGE)335            ssKey << make_pair(string("blockindex"), uint256(0));336        CDataStream ssValue;337        int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);338        fFlags = DB_NEXT;339        if (ret == DB_NOTFOUND)340            break;341        else if (ret != 0)342            return false;343344        // Unserialize345        string strType;346        ssKey >> strType;347        if (strType == "blockindex")348        {349            CDiskBlockIndex diskindex;350            ssValue >> diskindex;351352            // Construct block index object353            CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());354            pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);355            pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);356            pindexNew->nFile          = diskindex.nFile;357            pindexNew->nBlockPos      = diskindex.nBlockPos;358            pindexNew->nHeight        = diskindex.nHeight;359            pindexNew->nVersion       = diskindex.nVersion;360            pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;361            pindexNew->nTime          = diskindex.nTime;362            pindexNew->nBits          = diskindex.nBits;363            pindexNew->nNonce         = diskindex.nNonce;364365            // Watch for genesis block and best block366            if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)367                pindexGenesisBlock = pindexNew;368        }369        else370        {371            break;372        }373    }374375    if (!ReadHashBestChain(hashBestChain))376    {377        if (pindexGenesisBlock == NULL)378            return true;379        return error("CTxDB::LoadBlockIndex() : hashBestChain not found\n");380    }381382    if (!mapBlockIndex.count(hashBestChain))383        return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found\n");384    pindexBest = mapBlockIndex[hashBestChain];385    nBestHeight = pindexBest->nHeight;386    printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,14).c_str(), nBestHeight);387388    return true;389}390391392393394395//396// CAddrDB397//398399bool CAddrDB::WriteAddress(const CAddress& addr)400{401    return Write(make_pair(string("addr"), addr.GetKey()), addr);402}403404bool CAddrDB::LoadAddresses()405{406    CRITICAL_BLOCK(cs_mapAddresses)407    {408        // Load user provided addresses409        CAutoFile filein = fopen("addr.txt", "rt");410        if (filein)411        {412            try413            {414                char psz[1000];415                while (fgets(psz, sizeof(psz), filein))416                {417                    CAddress addr(psz, NODE_NETWORK);418                    if (addr.ip != 0)419                        AddAddress(*this, addr);420                }421            }422            catch (...) { }423        }424425        // Get cursor426        Dbc* pcursor = GetCursor();427        if (!pcursor)428            return false;429430        loop431        {432            // Read next record433            CDataStream ssKey;434            CDataStream ssValue;435            int ret = ReadAtCursor(pcursor, ssKey, ssValue);436            if (ret == DB_NOTFOUND)437                break;438            else if (ret != 0)439                return false;440441            // Unserialize442            string strType;443            ssKey >> strType;444            if (strType == "addr")445            {446                CAddress addr;447                ssValue >> addr;448                mapAddresses.insert(make_pair(addr.GetKey(), addr));449            }450        }451452        //// debug print453        printf("mapAddresses:\n");454        foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)455            item.second.print();456        printf("-----\n");457458        // Fix for possible GCC bug that manifests in mapAddresses.count in irc.cpp,459        // just need to call count here and it doesn't happen there, do not delete this!460        mapAddresses.count(vector<unsigned char>(18));461    }462463    return true;464}465466bool LoadAddresses()467{468    return CAddrDB("cr+").LoadAddresses();469}470471472473474//475// CReviewDB476//477478bool CReviewDB::ReadReviews(uint256 hash, vector<CReview>& vReviews)479{480    vReviews.size(); // msvc workaround, just need to do anything with vReviews481    return Read(make_pair(string("reviews"), hash), vReviews);482}483484bool CReviewDB::WriteReviews(uint256 hash, const vector<CReview>& vReviews)485{486    return Write(make_pair(string("reviews"), hash), vReviews);487}488489490491492493494495//496// CWalletDB497//498499bool CWalletDB::LoadWallet(vector<unsigned char>& vchDefaultKeyRet)500{501    vchDefaultKeyRet.clear();502503    //// todo: shouldn't we catch exceptions and try to recover and continue?504    CRITICAL_BLOCK(cs_mapKeys)505    CRITICAL_BLOCK(cs_mapWallet)506    {507        // Get cursor508        Dbc* pcursor = GetCursor();509        if (!pcursor)510            return false;511512        loop513        {514            // Read next record515            CDataStream ssKey;516            CDataStream ssValue;517            int ret = ReadAtCursor(pcursor, ssKey, ssValue);518            if (ret == DB_NOTFOUND)519                break;520            else if (ret != 0)521                return false;522523            // Unserialize524            // Taking advantage of the fact that pair serialization525            // is just the two items serialized one after the other526            string strType;527            ssKey >> strType;528            if (strType == "name")529            {530                string strAddress;531                ssKey >> strAddress;532                ssValue >> mapAddressBook[strAddress];533            }534            else if (strType == "tx")535            {536                uint256 hash;537                ssKey >> hash;538                CWalletTx& wtx = mapWallet[hash];539                ssValue >> wtx;540541                if (wtx.GetHash() != hash)542                    printf("Error in wallet.dat, hash mismatch\n");543544                //// debug print545                //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());546                //printf(" %12I64d  %s  %s  %s\n",547                //    wtx.vout[0].nValue,548                //    DateTimeStr(wtx.nTime).c_str(),549                //    wtx.hashBlock.ToString().substr(0,14).c_str(),550                //    wtx.mapValue["message"].c_str());551            }552            else if (strType == "key")553            {554                vector<unsigned char> vchPubKey;555                ssKey >> vchPubKey;556                CPrivKey vchPrivKey;557                ssValue >> vchPrivKey;558559                mapKeys[vchPubKey] = vchPrivKey;560                mapPubKeys[Hash160(vchPubKey)] = vchPubKey;561            }562            else if (strType == "defaultkey")563            {564                ssValue >> vchDefaultKeyRet;565            }566            else if (strType == "setting")  /// or settings or option or options or config?567            {568                string strKey;569                ssKey >> strKey;570                if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;571                if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;572                if (strKey == "addrIncoming")       ssValue >> addrIncoming;573            }574        }575    }576577    printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);578    printf("nTransactionFee = %I64d\n", nTransactionFee);579    printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());580581    return true;582}583584bool LoadWallet()585{586    vector<unsigned char> vchDefaultKey;587    if (!CWalletDB("cr").LoadWallet(vchDefaultKey))588        return false;589590    if (mapKeys.count(vchDefaultKey))591    {592        // Set keyUser593        keyUser.SetPubKey(vchDefaultKey);594        keyUser.SetPrivKey(mapKeys[vchDefaultKey]);595    }596    else597    {598        // Create new keyUser and set as default key599        keyUser.MakeNewKey();600        if (!AddKey(keyUser))601            return false;602        if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))603            return false;604        CWalletDB().WriteDefaultKey(keyUser.GetPubKey());605    }606607    return true;608}

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00