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.2.0 · 2009-12-16

util.cpp

539 lines · plain text · GitHub · 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"678map<string, string> mapArgs;9map<string, vector<string> > mapMultiArgs;10bool fDebug = false;11bool fPrintToDebugger = false;12bool fPrintToConsole = false;13char pszSetDataDir[MAX_PATH] = "";14bool fShutdown = false;151617181920// Init openssl library multithreading support21static wxMutex** ppmutexOpenSSL;22void locking_callback(int mode, int i, const char* file, int line)23{24    if (mode & CRYPTO_LOCK)25        ppmutexOpenSSL[i]->Lock();26    else27        ppmutexOpenSSL[i]->Unlock();28}2930// Init31class CInit32{33public:34    CInit()35    {36        // Init openssl library multithreading support37        ppmutexOpenSSL = (wxMutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(wxMutex*));38        for (int i = 0; i < CRYPTO_num_locks(); i++)39            ppmutexOpenSSL[i] = new wxMutex();40        CRYPTO_set_locking_callback(locking_callback);4142#ifdef __WXMSW__43        // Seed random number generator with screen scrape and other hardware sources44        RAND_screen();45#endif4647        // Seed random number generator with performance counter48        RandAddSeed();49    }50    ~CInit()51    {52        // Shutdown openssl library multithreading support53        CRYPTO_set_locking_callback(NULL);54        for (int i = 0; i < CRYPTO_num_locks(); i++)55            delete ppmutexOpenSSL[i];56        OPENSSL_free(ppmutexOpenSSL);57    }58}59instance_of_cinit;606162636465666768void RandAddSeed()69{70    // Seed with CPU performance counter71    int64 nCounter = PerformanceCounter();72    RAND_add(&nCounter, sizeof(nCounter), 1.5);73    memset(&nCounter, 0, sizeof(nCounter));74}7576void RandAddSeedPerfmon()77{78    // This can take up to 2 seconds, so only do it every 10 minutes79    static int64 nLastPerfmon;80    if (GetTime() < nLastPerfmon + 10 * 60)81        return;82    nLastPerfmon = GetTime();8384#ifdef __WXMSW__85    // Don't need this on Linux, OpenSSL automatically uses /dev/urandom86    // Seed with the entire set of perfmon data87    unsigned char pdata[250000];88    memset(pdata, 0, sizeof(pdata));89    unsigned long nSize = sizeof(pdata);90    long ret = RegQueryValueEx(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);91    RegCloseKey(HKEY_PERFORMANCE_DATA);92    if (ret == ERROR_SUCCESS)93    {94        uint256 hash;95        SHA256(pdata, nSize, (unsigned char*)&hash);96        RAND_add(&hash, sizeof(hash), min(nSize/500.0, (double)sizeof(hash)));97        hash = 0;98        memset(pdata, 0, nSize);99100        printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str(), nSize);101    }102#else103    printf("%s RandAddSeed()\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());104#endif105}106107uint64 GetRand(uint64 nMax)108{109    if (nMax == 0)110        return 0;111112    // The range of the random source must be a multiple of the modulus113    // to give every possible output value an equal possibility114    uint64 nRange = (UINT64_MAX / nMax) * nMax;115    uint64 nRand = 0;116    do117        RAND_bytes((unsigned char*)&nRand, sizeof(nRand));118    while (nRand >= nRange);119    return (nRand % nMax);120}121122123124125126127128129130131132133134// Safer snprintf135//  - prints up to limit-1 characters136//  - output string is always null terminated even if limit reached137//  - return value is the number of characters actually printed138int my_snprintf(char* buffer, size_t limit, const char* format, ...)139{140    if (limit == 0)141        return 0;142    va_list arg_ptr;143    va_start(arg_ptr, format);144    int ret = _vsnprintf(buffer, limit, format, arg_ptr);145    va_end(arg_ptr);146    if (ret < 0 || ret >= limit)147    {148        ret = limit - 1;149        buffer[limit-1] = 0;150    }151    return ret;152}153154155string strprintf(const char* format, ...)156{157    char buffer[50000];158    char* p = buffer;159    int limit = sizeof(buffer);160    int ret;161    loop162    {163        va_list arg_ptr;164        va_start(arg_ptr, format);165        ret = _vsnprintf(p, limit, format, arg_ptr);166        va_end(arg_ptr);167        if (ret >= 0 && ret < limit)168            break;169        if (p != buffer)170            delete p;171        limit *= 2;172        p = new char[limit];173        if (p == NULL)174            throw std::bad_alloc();175    }176#ifdef _MSC_VER177    // msvc optimisation178    if (p == buffer)179        return string(p, p+ret);180#endif181    string str(p, p+ret);182    if (p != buffer)183        delete p;184    return str;185}186187188bool error(const char* format, ...)189{190    char buffer[50000];191    int limit = sizeof(buffer);192    va_list arg_ptr;193    va_start(arg_ptr, format);194    int ret = _vsnprintf(buffer, limit, format, arg_ptr);195    va_end(arg_ptr);196    if (ret < 0 || ret >= limit)197    {198        ret = limit - 1;199        buffer[limit-1] = 0;200    }201    printf("ERROR: %s\n", buffer);202    return false;203}204205206void ParseString(const string& str, char c, vector<string>& v)207{208    unsigned int i1 = 0;209    unsigned int i2;210    do211    {212        i2 = str.find(c, i1);213        v.push_back(str.substr(i1, i2-i1));214        i1 = i2+1;215    }216    while (i2 != str.npos);217}218219220string FormatMoney(int64 n, bool fPlus)221{222    n /= CENT;223    string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);224    for (int i = 6; i < str.size(); i += 4)225        if (isdigit(str[str.size() - i - 1]))226            str.insert(str.size() - i, 1, ',');227    if (n < 0)228        str.insert((unsigned int)0, 1, '-');229    else if (fPlus && n > 0)230        str.insert((unsigned int)0, 1, '+');231    return str;232}233234bool ParseMoney(const char* pszIn, int64& nRet)235{236    string strWhole;237    int64 nCents = 0;238    const char* p = pszIn;239    while (isspace(*p))240        p++;241    for (; *p; p++)242    {243        if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))244            continue;245        if (*p == '.')246        {247            p++;248            if (isdigit(*p))249            {250                nCents = 10 * (*p++ - '0');251                if (isdigit(*p))252                    nCents += (*p++ - '0');253            }254            break;255        }256        if (isspace(*p))257            break;258        if (!isdigit(*p))259            return false;260        strWhole.insert(strWhole.end(), *p);261    }262    for (; *p; p++)263        if (!isspace(*p))264            return false;265    if (strWhole.size() > 14)266        return false;267    if (nCents < 0 || nCents > 99)268        return false;269    int64 nWhole = atoi64(strWhole);270    int64 nPreValue = nWhole * 100 + nCents;271    int64 nValue = nPreValue * CENT;272    if (nValue / CENT != nPreValue)273        return false;274    if (nValue / COIN != nWhole)275        return false;276    nRet = nValue;277    return true;278}279280281vector<unsigned char> ParseHex(const char* psz)282{283    vector<unsigned char> vch;284    while (isspace(*psz))285        psz++;286    vch.reserve((strlen(psz)+1)/3);287288    static char phexdigit[256] =289    { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,290      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,291      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,292      0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,293      -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,294      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,295      -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1296      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,297      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,298      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,299      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,300      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,301      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,302      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,303      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,304      -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };305306    while (*psz)307    {308        char c = phexdigit[(unsigned char)*psz++];309        if (c == -1)310            break;311        unsigned char n = (c << 4);312        if (*psz)313        {314            char c = phexdigit[(unsigned char)*psz++];315            if (c == -1)316                break;317            n |= c;318            vch.push_back(n);319        }320        while (isspace(*psz))321            psz++;322    }323324    return vch;325}326327vector<unsigned char> ParseHex(const std::string& str)328{329    return ParseHex(str.c_str());330}331332333void ParseParameters(int argc, char* argv[])334{335    mapArgs.clear();336    mapMultiArgs.clear();337    for (int i = 0; i < argc; i++)338    {339        char psz[10000];340        strlcpy(psz, argv[i], sizeof(psz));341        char* pszValue = (char*)"";342        if (strchr(psz, '='))343        {344            pszValue = strchr(psz, '=');345            *pszValue++ = '\0';346        }347        #ifdef __WXMSW__348        _strlwr(psz);349        if (psz[0] == '/')350            psz[0] = '-';351        #endif352        mapArgs[psz] = pszValue;353        mapMultiArgs[psz].push_back(pszValue);354    }355}356357358359360361362363void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)364{365#ifdef __WXMSW__366    char pszModule[MAX_PATH];367    pszModule[0] = '\0';368    GetModuleFileName(NULL, pszModule, sizeof(pszModule));369#else370    // might not be thread safe, uses wxString371    //const char* pszModule = wxStandardPaths::Get().GetExecutablePath().mb_str();372    const char* pszModule = "bitcoin";373#endif374    if (pex)375        snprintf(pszMessage, 1000,376            "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);377    else378        snprintf(pszMessage, 1000,379            "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);380}381382void LogException(std::exception* pex, const char* pszThread)383{384    char pszMessage[1000];385    FormatException(pszMessage, pex, pszThread);386    printf("\n%s", pszMessage);387}388389void PrintException(std::exception* pex, const char* pszThread)390{391    char pszMessage[1000];392    FormatException(pszMessage, pex, pszThread);393    printf("\n\n************************\n%s\n", pszMessage);394    if (wxTheApp)395        wxMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);396    throw;397    //DebugBreak();398}399400401402403404405406407void GetDataDir(char* pszDir)408{409    // pszDir must be at least MAX_PATH length.410    if (pszSetDataDir[0] != 0)411    {412        strlcpy(pszDir, pszSetDataDir, MAX_PATH);413        static bool fMkdirDone;414        if (!fMkdirDone)415        {416            fMkdirDone = true;417            _mkdir(pszDir);418        }419    }420    else421    {422        // This can be called during exceptions by printf, so we cache the423        // value so we don't have to do memory allocations after that.424        // wxStandardPaths::GetUserDataDir425        //  Return the directory for the user-dependent application data files:426        //  Unix: ~/.appname427        //  Windows: C:\Documents and Settings\username\Application Data\appname428        //  Mac: ~/Library/Application Support/appname429        static char pszCachedDir[MAX_PATH];430        if (pszCachedDir[0] == 0)431        {432            strlcpy(pszCachedDir, wxStandardPaths::Get().GetUserDataDir().c_str(), sizeof(pszCachedDir));433            _mkdir(pszCachedDir);434        }435        strlcpy(pszDir, pszCachedDir, MAX_PATH);436    }437}438439string GetDataDir()440{441    char pszDir[MAX_PATH];442    GetDataDir(pszDir);443    return pszDir;444}445446int GetFilesize(FILE* file)447{448    int nSavePos = ftell(file);449    int nFilesize = -1;450    if (fseek(file, 0, SEEK_END) == 0)451        nFilesize = ftell(file);452    fseek(file, nSavePos, SEEK_SET);453    return nFilesize;454}455456void ShrinkDebugFile()457{458    // Scroll debug.log if it's getting too big459    string strFile = GetDataDir() + "/debug.log";460    FILE* file = fopen(strFile.c_str(), "r");461    if (file && GetFilesize(file) > 10 * 1000000)462    {463        // Restart the file with some of the end464        char pch[200000];465        fseek(file, -sizeof(pch), SEEK_END);466        int nBytes = fread(pch, 1, sizeof(pch), file);467        fclose(file);468        if (file = fopen(strFile.c_str(), "w"))469        {470            fwrite(pch, 1, nBytes, file);471            fclose(file);472        }473    }474}475476477478479480481482483484485486//487// "Never go to sea with two chronometers; take one or three."488// Our three chronometers are:489//  - System clock490//  - Median of other server's clocks491//  - NTP servers492//493// note: NTP isn't implemented yet, so until then we just use the median494//  of other nodes clocks to correct ours.495//496int64 GetTime()497{498    return time(NULL);499}500501static int64 nTimeOffset = 0;502503int64 GetAdjustedTime()504{505    return GetTime() + nTimeOffset;506}507508void AddTimeData(unsigned int ip, int64 nTime)509{510    int64 nOffsetSample = nTime - GetTime();511512    // Ignore duplicates513    static set<unsigned int> setKnown;514    if (!setKnown.insert(ip).second)515        return;516517    // Add data518    static vector<int64> vTimeOffsets;519    if (vTimeOffsets.empty())520        vTimeOffsets.push_back(0);521    vTimeOffsets.push_back(nOffsetSample);522    printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);523    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)524    {525        sort(vTimeOffsets.begin(), vTimeOffsets.end());526        int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];527        nTimeOffset = nMedian;528        if ((nMedian > 0 ? nMedian : -nMedian) > 5 * 60)529        {530            // Only let other nodes change our clock so far before we531            // go to the NTP servers532            /// todo: Get time from NTP servers, then set a flag533            ///    to make sure it doesn't get changed again534        }535        foreach(int64 n, vTimeOffsets)536            printf("%+"PRI64d"  ", n);537        printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);538    }539}

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