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.3.19 · 2010-12-13

db.cpp

1,019 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 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"67void ThreadFlushWalletDB(void* parg);8910unsigned int nWalletDBUpdated;11uint64 nAccountingEntryNumber = 0;12131415//16// CDB17//1819static CCriticalSection cs_db;20static bool fDbEnvInit = false;21DbEnv dbenv(0);22static map<string, int> mapFileUseCount;23static map<string, Db*> mapDb;2425class CDBInit26{27public:28    CDBInit()29    {30    }31    ~CDBInit()32    {33        if (fDbEnvInit)34        {35            dbenv.close(0);36            fDbEnvInit = false;37        }38    }39}40instance_of_cdbinit;414243CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)44{45    int ret;46    if (pszFile == NULL)47        return;4849    fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));50    bool fCreate = strchr(pszMode, 'c');51    unsigned int nFlags = DB_THREAD;52    if (fCreate)53        nFlags |= DB_CREATE;5455    CRITICAL_BLOCK(cs_db)56    {57        if (!fDbEnvInit)58        {59            if (fShutdown)60                return;61            string strDataDir = GetDataDir();62            string strLogDir = strDataDir + "/database";63            filesystem::create_directory(strLogDir.c_str());64            string strErrorFile = strDataDir + "/db.log";65            printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());6667            dbenv.set_lg_dir(strLogDir.c_str());68            dbenv.set_lg_max(10000000);69            dbenv.set_lk_max_locks(10000);70            dbenv.set_lk_max_objects(10000);71            dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug72            dbenv.set_flags(DB_AUTO_COMMIT, 1);73            ret = dbenv.open(strDataDir.c_str(),74                             DB_CREATE     |75                             DB_INIT_LOCK  |76                             DB_INIT_LOG   |77                             DB_INIT_MPOOL |78                             DB_INIT_TXN   |79                             DB_THREAD     |80                             DB_RECOVER,81                             S_IRUSR | S_IWUSR);82            if (ret > 0)83                throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));84            fDbEnvInit = true;85        }8687        strFile = pszFile;88        ++mapFileUseCount[strFile];89        pdb = mapDb[strFile];90        if (pdb == NULL)91        {92            pdb = new Db(&dbenv, 0);9394            ret = pdb->open(NULL,      // Txn pointer95                            pszFile,   // Filename96                            "main",    // Logical db name97                            DB_BTREE,  // Database type98                            nFlags,    // Flags99                            0);100101            if (ret > 0)102            {103                delete pdb;104                pdb = NULL;105                CRITICAL_BLOCK(cs_db)106                    --mapFileUseCount[strFile];107                strFile = "";108                throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));109            }110111            if (fCreate && !Exists(string("version")))112            {113                bool fTmp = fReadOnly;114                fReadOnly = false;115                WriteVersion(VERSION);116                fReadOnly = fTmp;117            }118119            mapDb[strFile] = pdb;120        }121    }122}123124void CDB::Close()125{126    if (!pdb)127        return;128    if (!vTxn.empty())129        vTxn.front()->abort();130    vTxn.clear();131    pdb = NULL;132133    // Flush database activity from memory pool to disk log134    unsigned int nMinutes = 0;135    if (fReadOnly)136        nMinutes = 1;137    if (strFile == "addr.dat")138        nMinutes = 2;139    if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)140        nMinutes = 1;141    dbenv.txn_checkpoint(0, nMinutes, 0);142143    CRITICAL_BLOCK(cs_db)144        --mapFileUseCount[strFile];145}146147void CloseDb(const string& strFile)148{149    CRITICAL_BLOCK(cs_db)150    {151        if (mapDb[strFile] != NULL)152        {153            // Close the database handle154            Db* pdb = mapDb[strFile];155            pdb->close(0);156            delete pdb;157            mapDb[strFile] = NULL;158        }159    }160}161162void DBFlush(bool fShutdown)163{164    // Flush log data to the actual data file165    //  on all files that are not in use166    printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");167    if (!fDbEnvInit)168        return;169    CRITICAL_BLOCK(cs_db)170    {171        map<string, int>::iterator mi = mapFileUseCount.begin();172        while (mi != mapFileUseCount.end())173        {174            string strFile = (*mi).first;175            int nRefCount = (*mi).second;176            printf("%s refcount=%d\n", strFile.c_str(), nRefCount);177            if (nRefCount == 0)178            {179                // Move log data to the dat file180                CloseDb(strFile);181                dbenv.txn_checkpoint(0, 0, 0);182                printf("%s flush\n", strFile.c_str());183                dbenv.lsn_reset(strFile.c_str(), 0);184                mapFileUseCount.erase(mi++);185            }186            else187                mi++;188        }189        if (fShutdown)190        {191            char** listp;192            if (mapFileUseCount.empty())193                dbenv.log_archive(&listp, DB_ARCH_REMOVE);194            dbenv.close(0);195            fDbEnvInit = false;196        }197    }198}199200201202203204205//206// CTxDB207//208209bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)210{211    assert(!fClient);212    txindex.SetNull();213    return Read(make_pair(string("tx"), hash), txindex);214}215216bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)217{218    assert(!fClient);219    return Write(make_pair(string("tx"), hash), txindex);220}221222bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)223{224    assert(!fClient);225226    // Add to tx index227    uint256 hash = tx.GetHash();228    CTxIndex txindex(pos, tx.vout.size());229    return Write(make_pair(string("tx"), hash), txindex);230}231232bool CTxDB::EraseTxIndex(const CTransaction& tx)233{234    assert(!fClient);235    uint256 hash = tx.GetHash();236237    return Erase(make_pair(string("tx"), hash));238}239240bool CTxDB::ContainsTx(uint256 hash)241{242    assert(!fClient);243    return Exists(make_pair(string("tx"), hash));244}245246bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)247{248    assert(!fClient);249    vtx.clear();250251    // Get cursor252    Dbc* pcursor = GetCursor();253    if (!pcursor)254        return false;255256    unsigned int fFlags = DB_SET_RANGE;257    loop258    {259        // Read next record260        CDataStream ssKey;261        if (fFlags == DB_SET_RANGE)262            ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);263        CDataStream ssValue;264        int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);265        fFlags = DB_NEXT;266        if (ret == DB_NOTFOUND)267            break;268        else if (ret != 0)269        {270            pcursor->close();271            return false;272        }273274        // Unserialize275        string strType;276        uint160 hashItem;277        CDiskTxPos pos;278        ssKey >> strType >> hashItem >> pos;279        int nItemHeight;280        ssValue >> nItemHeight;281282        // Read transaction283        if (strType != "owner" || hashItem != hash160)284            break;285        if (nItemHeight >= nMinHeight)286        {287            vtx.resize(vtx.size()+1);288            if (!vtx.back().ReadFromDisk(pos))289            {290                pcursor->close();291                return false;292            }293        }294    }295296    pcursor->close();297    return true;298}299300bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)301{302    assert(!fClient);303    tx.SetNull();304    if (!ReadTxIndex(hash, txindex))305        return false;306    return (tx.ReadFromDisk(txindex.pos));307}308309bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)310{311    CTxIndex txindex;312    return ReadDiskTx(hash, tx, txindex);313}314315bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)316{317    return ReadDiskTx(outpoint.hash, tx, txindex);318}319320bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)321{322    CTxIndex txindex;323    return ReadDiskTx(outpoint.hash, tx, txindex);324}325326bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)327{328    return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);329}330331bool CTxDB::EraseBlockIndex(uint256 hash)332{333    return Erase(make_pair(string("blockindex"), hash));334}335336bool CTxDB::ReadHashBestChain(uint256& hashBestChain)337{338    return Read(string("hashBestChain"), hashBestChain);339}340341bool CTxDB::WriteHashBestChain(uint256 hashBestChain)342{343    return Write(string("hashBestChain"), hashBestChain);344}345346bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)347{348    return Read(string("bnBestInvalidWork"), bnBestInvalidWork);349}350351bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)352{353    return Write(string("bnBestInvalidWork"), bnBestInvalidWork);354}355356CBlockIndex* InsertBlockIndex(uint256 hash)357{358    if (hash == 0)359        return NULL;360361    // Return existing362    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);363    if (mi != mapBlockIndex.end())364        return (*mi).second;365366    // Create new367    CBlockIndex* pindexNew = new CBlockIndex();368    if (!pindexNew)369        throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");370    mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;371    pindexNew->phashBlock = &((*mi).first);372373    return pindexNew;374}375376bool CTxDB::LoadBlockIndex()377{378    // Get database cursor379    Dbc* pcursor = GetCursor();380    if (!pcursor)381        return false;382383    // Load mapBlockIndex384    unsigned int fFlags = DB_SET_RANGE;385    loop386    {387        // Read next record388        CDataStream ssKey;389        if (fFlags == DB_SET_RANGE)390            ssKey << make_pair(string("blockindex"), uint256(0));391        CDataStream ssValue;392        int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);393        fFlags = DB_NEXT;394        if (ret == DB_NOTFOUND)395            break;396        else if (ret != 0)397            return false;398399        // Unserialize400        string strType;401        ssKey >> strType;402        if (strType == "blockindex")403        {404            CDiskBlockIndex diskindex;405            ssValue >> diskindex;406407            // Construct block index object408            CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());409            pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);410            pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);411            pindexNew->nFile          = diskindex.nFile;412            pindexNew->nBlockPos      = diskindex.nBlockPos;413            pindexNew->nHeight        = diskindex.nHeight;414            pindexNew->nVersion       = diskindex.nVersion;415            pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;416            pindexNew->nTime          = diskindex.nTime;417            pindexNew->nBits          = diskindex.nBits;418            pindexNew->nNonce         = diskindex.nNonce;419420            // Watch for genesis block421            if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)422                pindexGenesisBlock = pindexNew;423424            if (!pindexNew->CheckIndex())425                return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);426        }427        else428        {429            break;430        }431    }432    pcursor->close();433434    // Calculate bnChainWork435    vector<pair<int, CBlockIndex*> > vSortedByHeight;436    vSortedByHeight.reserve(mapBlockIndex.size());437    foreach(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)438    {439        CBlockIndex* pindex = item.second;440        vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));441    }442    sort(vSortedByHeight.begin(), vSortedByHeight.end());443    foreach(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)444    {445        CBlockIndex* pindex = item.second;446        pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();447    }448449    // Load hashBestChain pointer to end of best chain450    if (!ReadHashBestChain(hashBestChain))451    {452        if (pindexGenesisBlock == NULL)453            return true;454        return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");455    }456    if (!mapBlockIndex.count(hashBestChain))457        return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");458    pindexBest = mapBlockIndex[hashBestChain];459    nBestHeight = pindexBest->nHeight;460    bnBestChainWork = pindexBest->bnChainWork;461    printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);462463    // Load bnBestInvalidWork, OK if it doesn't exist464    ReadBestInvalidWork(bnBestInvalidWork);465466    // Verify blocks in the best chain467    CBlockIndex* pindexFork = NULL;468    for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)469    {470        if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))471            break;472        CBlock block;473        if (!block.ReadFromDisk(pindex))474            return error("LoadBlockIndex() : block.ReadFromDisk failed");475        if (!block.CheckBlock())476        {477            printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());478            pindexFork = pindex->pprev;479        }480    }481    if (pindexFork)482    {483        // Reorg back to the fork484        printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);485        CBlock block;486        if (!block.ReadFromDisk(pindexFork))487            return error("LoadBlockIndex() : block.ReadFromDisk failed");488        CTxDB txdb;489        block.SetBestChain(txdb, pindexFork);490    }491492    return true;493}494495496497498499//500// CAddrDB501//502503bool CAddrDB::WriteAddress(const CAddress& addr)504{505    return Write(make_pair(string("addr"), addr.GetKey()), addr);506}507508bool CAddrDB::EraseAddress(const CAddress& addr)509{510    return Erase(make_pair(string("addr"), addr.GetKey()));511}512513bool CAddrDB::LoadAddresses()514{515    CRITICAL_BLOCK(cs_mapAddresses)516    {517        // Load user provided addresses518        CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");519        if (filein)520        {521            try522            {523                char psz[1000];524                while (fgets(psz, sizeof(psz), filein))525                {526                    CAddress addr(psz, NODE_NETWORK);527                    addr.nTime = 0; // so it won't relay unless successfully connected528                    if (addr.IsValid())529                        AddAddress(addr);530                }531            }532            catch (...) { }533        }534535        // Get cursor536        Dbc* pcursor = GetCursor();537        if (!pcursor)538            return false;539540        loop541        {542            // Read next record543            CDataStream ssKey;544            CDataStream ssValue;545            int ret = ReadAtCursor(pcursor, ssKey, ssValue);546            if (ret == DB_NOTFOUND)547                break;548            else if (ret != 0)549                return false;550551            // Unserialize552            string strType;553            ssKey >> strType;554            if (strType == "addr")555            {556                CAddress addr;557                ssValue >> addr;558                mapAddresses.insert(make_pair(addr.GetKey(), addr));559            }560        }561        pcursor->close();562563        printf("Loaded %d addresses\n", mapAddresses.size());564    }565566    return true;567}568569bool LoadAddresses()570{571    return CAddrDB("cr+").LoadAddresses();572}573574575576577//578// CWalletDB579//580581static set<int64> setKeyPool;582static CCriticalSection cs_setKeyPool;583584bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)585{586    account.SetNull();587    return Read(make_pair(string("acc"), strAccount), account);588}589590bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)591{592    return Write(make_pair(string("acc"), strAccount), account);593}594595bool CWalletDB::WriteAccountingEntry(const string& strAccount, const CAccountingEntry& acentry)596{597    return Write(make_tuple(string("acentry"), strAccount, ++nAccountingEntryNumber), acentry);598}599600int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)601{602    list<CAccountingEntry> entries;603    ListAccountCreditDebit(strAccount, entries);604605    int64 nCreditDebit = 0;606    foreach (const CAccountingEntry& entry, entries)607        nCreditDebit += entry.nCreditDebit;608609    return nCreditDebit;610}611612void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)613{614    int64 nCreditDebit = 0;615616    Dbc* pcursor = GetCursor();617    if (!pcursor)618        throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");619    unsigned int fFlags = DB_SET_RANGE;620    loop621    {622        // Read next record623        CDataStream ssKey;624        if (fFlags == DB_SET_RANGE)625            ssKey << make_tuple(string("acentry"), strAccount, uint64(0));626        CDataStream ssValue;627        int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);628        fFlags = DB_NEXT;629        if (ret == DB_NOTFOUND)630            break;631        else if (ret != 0)632        {633            pcursor->close();634            throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");635        }636637        // Unserialize638        string strType;639        ssKey >> strType;640        if (strType != "acentry")641            break;642        string strAccountName;643        ssKey >> strAccountName;644        if (strAccountName != strAccount)645            break;646647        CAccountingEntry acentry;648        ssValue >> acentry;649        entries.push_back(acentry);650    }651652    pcursor->close();653}654655bool CWalletDB::LoadWallet()656{657    vchDefaultKey.clear();658    int nFileVersion = 0;659    vector<uint256> vWalletUpgrade;660661    // Modify defaults662#ifndef __WXMSW__663    // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program664    fMinimizeToTray = false;665    fMinimizeOnClose = false;666#endif667668    //// todo: shouldn't we catch exceptions and try to recover and continue?669    CRITICAL_BLOCK(cs_mapKeys)670    CRITICAL_BLOCK(cs_mapWallet)671    {672        // Get cursor673        Dbc* pcursor = GetCursor();674        if (!pcursor)675            return false;676677        loop678        {679            // Read next record680            CDataStream ssKey;681            CDataStream ssValue;682            int ret = ReadAtCursor(pcursor, ssKey, ssValue);683            if (ret == DB_NOTFOUND)684                break;685            else if (ret != 0)686                return false;687688            // Unserialize689            // Taking advantage of the fact that pair serialization690            // is just the two items serialized one after the other691            string strType;692            ssKey >> strType;693            if (strType == "name")694            {695                string strAddress;696                ssKey >> strAddress;697                ssValue >> mapAddressBook[strAddress];698            }699            else if (strType == "tx")700            {701                uint256 hash;702                ssKey >> hash;703                CWalletTx& wtx = mapWallet[hash];704                ssValue >> wtx;705706                if (wtx.GetHash() != hash)707                    printf("Error in wallet.dat, hash mismatch\n");708709                // Undo serialize changes in 31600710                if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)711                {712                    if (!ssValue.empty())713                    {714                        char fTmp;715                        char fUnused;716                        ssValue >> fTmp >> fUnused >> wtx.strFromAccount;717                        printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());718                        wtx.fTimeReceivedIsTxTime = fTmp;719                    }720                    else721                    {722                        printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());723                        wtx.fTimeReceivedIsTxTime = 0;724                    }725                    vWalletUpgrade.push_back(hash);726                }727728                //// debug print729                //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());730                //printf(" %12I64d  %s  %s  %s\n",731                //    wtx.vout[0].nValue,732                //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),733                //    wtx.hashBlock.ToString().substr(0,20).c_str(),734                //    wtx.mapValue["message"].c_str());735            }736            else if (strType == "acentry")737            {738                string strAccount;739                ssKey >> strAccount;740                uint64 nNumber;741                ssKey >> nNumber;742                if (nNumber > nAccountingEntryNumber)743                    nAccountingEntryNumber = nNumber;744            }745            else if (strType == "key" || strType == "wkey")746            {747                vector<unsigned char> vchPubKey;748                ssKey >> vchPubKey;749                CWalletKey wkey;750                if (strType == "key")751                    ssValue >> wkey.vchPrivKey;752                else753                    ssValue >> wkey;754755                mapKeys[vchPubKey] = wkey.vchPrivKey;756                mapPubKeys[Hash160(vchPubKey)] = vchPubKey;757            }758            else if (strType == "defaultkey")759            {760                ssValue >> vchDefaultKey;761            }762            else if (strType == "pool")763            {764                int64 nIndex;765                ssKey >> nIndex;766                setKeyPool.insert(nIndex);767            }768            else if (strType == "version")769            {770                ssValue >> nFileVersion;771                if (nFileVersion == 10300)772                    nFileVersion = 300;773            }774            else if (strType == "setting")775            {776                string strKey;777                ssKey >> strKey;778779                // Menu state780                if (strKey == "fGenerateBitcoins")  ssValue >> fGenerateBitcoins;781782                // Options783                if (strKey == "nTransactionFee")    ssValue >> nTransactionFee;784                if (strKey == "addrIncoming")       ssValue >> addrIncoming;785                if (strKey == "fLimitProcessors")   ssValue >> fLimitProcessors;786                if (strKey == "nLimitProcessors")   ssValue >> nLimitProcessors;787                if (strKey == "fMinimizeToTray")    ssValue >> fMinimizeToTray;788                if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;789                if (strKey == "fUseProxy")          ssValue >> fUseProxy;790                if (strKey == "addrProxy")          ssValue >> addrProxy;791792            }793        }794        pcursor->close();795    }796797    foreach(uint256 hash, vWalletUpgrade)798        WriteTx(hash, mapWallet[hash]);799800    printf("nFileVersion = %d\n", nFileVersion);801    printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);802    printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);803    printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());804    printf("fMinimizeToTray = %d\n", fMinimizeToTray);805    printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);806    printf("fUseProxy = %d\n", fUseProxy);807    printf("addrProxy = %s\n", addrProxy.ToString().c_str());808809810    // Upgrade811    if (nFileVersion < VERSION)812    {813        // Get rid of old debug.log file in current directory814        if (nFileVersion <= 105 && !pszSetDataDir[0])815            unlink("debug.log");816817        WriteVersion(VERSION);818    }819820821    return true;822}823824bool LoadWallet(bool& fFirstRunRet)825{826    fFirstRunRet = false;827    if (!CWalletDB("cr+").LoadWallet())828        return false;829    fFirstRunRet = vchDefaultKey.empty();830831    if (mapKeys.count(vchDefaultKey))832    {833        // Set keyUser834        keyUser.SetPubKey(vchDefaultKey);835        keyUser.SetPrivKey(mapKeys[vchDefaultKey]);836    }837    else838    {839        // Create new keyUser and set as default key840        RandAddSeedPerfmon();841        keyUser.MakeNewKey();842        if (!AddKey(keyUser))843            return false;844        if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))845            return false;846        CWalletDB().WriteDefaultKey(keyUser.GetPubKey());847    }848849    CreateThread(ThreadFlushWalletDB, NULL);850    return true;851}852853void ThreadFlushWalletDB(void* parg)854{855    static bool fOneThread;856    if (fOneThread)857        return;858    fOneThread = true;859    if (mapArgs.count("-noflushwallet"))860        return;861862    unsigned int nLastSeen = nWalletDBUpdated;863    unsigned int nLastFlushed = nWalletDBUpdated;864    int64 nLastWalletUpdate = GetTime();865    while (!fShutdown)866    {867        Sleep(500);868869        if (nLastSeen != nWalletDBUpdated)870        {871            nLastSeen = nWalletDBUpdated;872            nLastWalletUpdate = GetTime();873        }874875        if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)876        {877            TRY_CRITICAL_BLOCK(cs_db)878            {879                // Don't do this if any databases are in use880                int nRefCount = 0;881                map<string, int>::iterator mi = mapFileUseCount.begin();882                while (mi != mapFileUseCount.end())883                {884                    nRefCount += (*mi).second;885                    mi++;886                }887888                if (nRefCount == 0 && !fShutdown)889                {890                    string strFile = "wallet.dat";891                    map<string, int>::iterator mi = mapFileUseCount.find(strFile);892                    if (mi != mapFileUseCount.end())893                    {894                        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());895                        printf("Flushing wallet.dat\n");896                        nLastFlushed = nWalletDBUpdated;897                        int64 nStart = GetTimeMillis();898899                        // Flush wallet.dat so it's self contained900                        CloseDb(strFile);901                        dbenv.txn_checkpoint(0, 0, 0);902                        dbenv.lsn_reset(strFile.c_str(), 0);903904                        mapFileUseCount.erase(mi++);905                        printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);906                    }907                }908            }909        }910    }911}912913void BackupWallet(const string& strDest)914{915    while (!fShutdown)916    {917        CRITICAL_BLOCK(cs_db)918        {919            const string strFile = "wallet.dat";920            if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)921            {922                // Flush log data to the dat file923                CloseDb(strFile);924                dbenv.txn_checkpoint(0, 0, 0);925                dbenv.lsn_reset(strFile.c_str(), 0);926                mapFileUseCount.erase(strFile);927928                // Copy wallet.dat929                filesystem::path pathSrc(GetDataDir() + "/" + strFile);930                filesystem::path pathDest(strDest);931                if (filesystem::is_directory(pathDest))932                    pathDest = pathDest / strFile;933#if BOOST_VERSION >= 104000934                filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);935#else936                filesystem::copy_file(pathSrc, pathDest);937#endif938                printf("copied wallet.dat to %s\n", pathDest.string().c_str());939940                return;941            }942        }943        Sleep(100);944    }945}946947948void CWalletDB::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)949{950    nIndex = -1;951    keypool.vchPubKey.clear();952    CRITICAL_BLOCK(cs_main)953    CRITICAL_BLOCK(cs_mapWallet)954    CRITICAL_BLOCK(cs_setKeyPool)955    {956        // Top up key pool957        int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);958        while (setKeyPool.size() < nTargetSize+1)959        {960            int64 nEnd = 1;961            if (!setKeyPool.empty())962                nEnd = *(--setKeyPool.end()) + 1;963            if (!Write(make_pair(string("pool"), nEnd), CKeyPool(GenerateNewKey())))964                throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");965            setKeyPool.insert(nEnd);966            printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());967        }968969        // Get the oldest key970        assert(!setKeyPool.empty());971        nIndex = *(setKeyPool.begin());972        setKeyPool.erase(setKeyPool.begin());973        if (!Read(make_pair(string("pool"), nIndex), keypool))974            throw runtime_error("ReserveKeyFromKeyPool() : read failed");975        if (!mapKeys.count(keypool.vchPubKey))976            throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");977        assert(!keypool.vchPubKey.empty());978        printf("keypool reserve %"PRI64d"\n", nIndex);979    }980}981982void CWalletDB::KeepKey(int64 nIndex)983{984    // Remove from key pool985    CRITICAL_BLOCK(cs_main)986    CRITICAL_BLOCK(cs_mapWallet)987    {988        Erase(make_pair(string("pool"), nIndex));989    }990    printf("keypool keep %"PRI64d"\n", nIndex);991}992993void CWalletDB::ReturnKey(int64 nIndex)994{995    // Return to key pool996    CRITICAL_BLOCK(cs_setKeyPool)997        setKeyPool.insert(nIndex);998    printf("keypool return %"PRI64d"\n", nIndex);999}10001001vector<unsigned char> GetKeyFromKeyPool()1002{1003    CWalletDB walletdb;1004    int64 nIndex = 0;1005    CKeyPool keypool;1006    walletdb.ReserveKeyFromKeyPool(nIndex, keypool);1007    walletdb.KeepKey(nIndex);1008    return keypool.vchPubKey;1009}10101011int64 GetOldestKeyPoolTime()1012{1013    CWalletDB walletdb;1014    int64 nIndex = 0;1015    CKeyPool keypool;1016    walletdb.ReserveKeyFromKeyPool(nIndex, keypool);1017    walletdb.ReturnKey(nIndex);1018    return keypool.nTime;1019}

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