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.5 · 2009-02-04

util.cpp

383 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"6789bool fDebug = false;1011121314// Init openssl library multithreading support15static HANDLE* lock_cs;1617void win32_locking_callback(int mode, int type, const char* file, int line)18{19    if (mode & CRYPTO_LOCK)20        WaitForSingleObject(lock_cs[type], INFINITE);21    else22        ReleaseMutex(lock_cs[type]);23}2425// Init26class CInit27{28public:29    CInit()30    {31        // Init openssl library multithreading support32        lock_cs = (HANDLE*)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));33        for (int i = 0; i < CRYPTO_num_locks(); i++)34            lock_cs[i] = CreateMutex(NULL,FALSE,NULL);35        CRYPTO_set_locking_callback(win32_locking_callback);3637        // Seed random number generator with screen scrape and other hardware sources38        RAND_screen();3940        // Seed random number generator with perfmon data41        RandAddSeed(true);42    }43    ~CInit()44    {45        // Shutdown openssl library multithreading support46        CRYPTO_set_locking_callback(NULL);47        for (int i =0 ; i < CRYPTO_num_locks(); i++)48            CloseHandle(lock_cs[i]);49        OPENSSL_free(lock_cs);50    }51}52instance_of_cinit;5354555657void RandAddSeed(bool fPerfmon)58{59    // Seed with CPU performance counter60    LARGE_INTEGER PerformanceCount;61    QueryPerformanceCounter(&PerformanceCount);62    RAND_add(&PerformanceCount, sizeof(PerformanceCount), 1.5);63    memset(&PerformanceCount, 0, sizeof(PerformanceCount));6465    static int64 nLastPerfmon;66    if (fPerfmon || GetTime() > nLastPerfmon + 5 * 60)67    {68        nLastPerfmon = GetTime();6970        // Seed with the entire set of perfmon data71        unsigned char pdata[250000];72        memset(pdata, 0, sizeof(pdata));73        unsigned long nSize = sizeof(pdata);74        long ret = RegQueryValueEx(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);75        RegCloseKey(HKEY_PERFORMANCE_DATA);76        if (ret == ERROR_SUCCESS)77        {78            uint256 hash;79            SHA256(pdata, nSize, (unsigned char*)&hash);80            RAND_add(&hash, sizeof(hash), min(nSize/500.0, (double)sizeof(hash)));81            hash = 0;82            memset(pdata, 0, nSize);8384            time_t nTime;85            time(&nTime);86            struct tm* ptmTime = gmtime(&nTime);87            char pszTime[200];88            strftime(pszTime, sizeof(pszTime), "%x %H:%M:%S", ptmTime);89            printf("%s  RandAddSeed() got %d bytes of performance data\n", pszTime, nSize);90        }91    }92}93949596979899100101102103// Safer snprintf104//  - prints up to limit-1 characters105//  - output string is always null terminated even if limit reached106//  - return value is the number of characters actually printed107int my_snprintf(char* buffer, size_t limit, const char* format, ...)108{109    if (limit == 0)110        return 0;111    va_list arg_ptr;112    va_start(arg_ptr, format);113    int ret = _vsnprintf(buffer, limit, format, arg_ptr);114    va_end(arg_ptr);115    if (ret < 0 || ret >= limit)116    {117        ret = limit - 1;118        buffer[limit-1] = 0;119    }120    return ret;121}122123124string strprintf(const char* format, ...)125{126    char buffer[50000];127    char* p = buffer;128    int limit = sizeof(buffer);129    int ret;130    loop131    {132        va_list arg_ptr;133        va_start(arg_ptr, format);134        ret = _vsnprintf(p, limit, format, arg_ptr);135        va_end(arg_ptr);136        if (ret >= 0 && ret < limit)137            break;138        if (p != buffer)139            delete p;140        limit *= 2;141        p = new char[limit];142        if (p == NULL)143            throw std::bad_alloc();144    }145#ifdef _MSC_VER146    // msvc optimisation147    if (p == buffer)148        return string(p, p+ret);149#endif150    string str(p, p+ret);151    if (p != buffer)152        delete p;153    return str;154}155156157bool error(const char* format, ...)158{159    char buffer[50000];160    int limit = sizeof(buffer);161    va_list arg_ptr;162    va_start(arg_ptr, format);163    int ret = _vsnprintf(buffer, limit, format, arg_ptr);164    va_end(arg_ptr);165    if (ret < 0 || ret >= limit)166    {167        ret = limit - 1;168        buffer[limit-1] = 0;169    }170    printf("ERROR: %s\n", buffer);171    return false;172}173174175void PrintException(std::exception* pex, const char* pszThread)176{177    char pszModule[260];178    pszModule[0] = '\0';179    GetModuleFileName(NULL, pszModule, sizeof(pszModule));180    _strlwr(pszModule);181    char pszMessage[1000];182    if (pex)183        snprintf(pszMessage, sizeof(pszMessage),184            "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);185    else186        snprintf(pszMessage, sizeof(pszMessage),187            "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);188    printf("\n\n************************\n%s", pszMessage);189    if (wxTheApp)190        wxMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);191    throw;192    //DebugBreak();193}194195196void ParseString(const string& str, char c, vector<string>& v)197{198    unsigned int i1 = 0;199    unsigned int i2;200    do201    {202        i2 = str.find(c, i1);203        v.push_back(str.substr(i1, i2-i1));204        i1 = i2+1;205    }206    while (i2 != str.npos);207}208209210string FormatMoney(int64 n, bool fPlus)211{212    n /= CENT;213    string str = strprintf("%I64d.%02I64d", (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);214    for (int i = 6; i < str.size(); i += 4)215        if (isdigit(str[str.size() - i - 1]))216            str.insert(str.size() - i, 1, ',');217    if (n < 0)218        str.insert((unsigned int)0, 1, '-');219    else if (fPlus && n > 0)220        str.insert((unsigned int)0, 1, '+');221    return str;222}223224bool ParseMoney(const char* pszIn, int64& nRet)225{226    string strWhole;227    int64 nCents = 0;228    const char* p = pszIn;229    while (isspace(*p))230        p++;231    for (; *p; p++)232    {233        if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))234            continue;235        if (*p == '.')236        {237            p++;238            if (isdigit(*p))239            {240                nCents = 10 * (*p++ - '0');241                if (isdigit(*p))242                    nCents += (*p++ - '0');243            }244            break;245        }246        if (isspace(*p))247            break;248        if (!isdigit(*p))249            return false;250        strWhole.insert(strWhole.end(), *p);251    }252    for (; *p; p++)253        if (!isspace(*p))254            return false;255    if (strWhole.size() > 14)256        return false;257    if (nCents < 0 || nCents > 99)258        return false;259    int64 nWhole = atoi64(strWhole);260    int64 nPreValue = nWhole * 100 + nCents;261    int64 nValue = nPreValue * CENT;262    if (nValue / CENT != nPreValue)263        return false;264    if (nValue / COIN != nWhole)265        return false;266    nRet = nValue;267    return true;268}269270271272273274275276277278279bool FileExists(const char* psz)280{281#ifdef WIN32282    return GetFileAttributes(psz) != -1;283#else284    return access(psz, 0) != -1;285#endif286}287288int GetFilesize(FILE* file)289{290    int nSavePos = ftell(file);291    int nFilesize = -1;292    if (fseek(file, 0, SEEK_END) == 0)293        nFilesize = ftell(file);294    fseek(file, nSavePos, SEEK_SET);295    return nFilesize;296}297298299300301302303304305uint64 GetRand(uint64 nMax)306{307    if (nMax == 0)308        return 0;309310    // The range of the random source must be a multiple of the modulus311    // to give every possible output value an equal possibility312    uint64 nRange = (_UI64_MAX / nMax) * nMax;313    uint64 nRand = 0;314    do315        RAND_bytes((unsigned char*)&nRand, sizeof(nRand));316    while (nRand >= nRange);317    return (nRand % nMax);318}319320321322323324325326327328329//330// "Never go to sea with two chronometers; take one or three."331// Our three chronometers are:332//  - System clock333//  - Median of other server's clocks334//  - NTP servers335//336// note: NTP isn't implemented yet, so until then we just use the median337//  of other nodes clocks to correct ours.338//339340int64 GetTime()341{342    return time(NULL);343}344345static int64 nTimeOffset = 0;346347int64 GetAdjustedTime()348{349    return GetTime() + nTimeOffset;350}351352void AddTimeData(unsigned int ip, int64 nTime)353{354    int64 nOffsetSample = nTime - GetTime();355356    // Ignore duplicates357    static set<unsigned int> setKnown;358    if (!setKnown.insert(ip).second)359        return;360361    // Add data362    static vector<int64> vTimeOffsets;363    if (vTimeOffsets.empty())364        vTimeOffsets.push_back(0);365    vTimeOffsets.push_back(nOffsetSample);366    printf("Added time data, samples %d, ip %08x, offset %+I64d (%+I64d minutes)\n", vTimeOffsets.size(), ip, vTimeOffsets.back(), vTimeOffsets.back()/60);367    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)368    {369        sort(vTimeOffsets.begin(), vTimeOffsets.end());370        int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];371        nTimeOffset = nMedian;372        if ((nMedian > 0 ? nMedian : -nMedian) > 5 * 60)373        {374            // Only let other nodes change our clock so far before we375            // go to the NTP servers376            /// todo: Get time from NTP servers, then set a flag377            ///    to make sure it doesn't get changed again378        }379        foreach(int64 n, vTimeOffsets)380            printf("%+I64d  ", n);381        printf("|  nTimeOffset = %+I64d  (%+I64d minutes)\n", nTimeOffset, nTimeOffset/60);382    }383}

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