Bitcoin v0.1.3 · 2009-01-12
util.cpp
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[0]) || !isdigit(p[1]))239 return false;240 nCents = atoi64(p);241 if (nCents < 0 || nCents > 99)242 return false;243 p += 2;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() > 17)256 return false;257 int64 nWhole = atoi64(strWhole);258 int64 nValue = nWhole * 100 + nCents;259 if (nValue / 100 != nWhole)260 return false;261 nValue *= CENT;262 nRet = nValue;263 return true;264}265266267268269270271272273274275bool FileExists(const char* psz)276{277#ifdef WIN32278 return GetFileAttributes(psz) != -1;279#else280 return access(psz, 0) != -1;281#endif282}283284int GetFilesize(FILE* file)285{286 int nSavePos = ftell(file);287 int nFilesize = -1;288 if (fseek(file, 0, SEEK_END) == 0)289 nFilesize = ftell(file);290 fseek(file, nSavePos, SEEK_SET);291 return nFilesize;292}293294295296297298299300301uint64 GetRand(uint64 nMax)302{303 if (nMax == 0)304 return 0;305306 // The range of the random source must be a multiple of the modulus307 // to give every possible output value an equal possibility308 uint64 nRange = (_UI64_MAX / nMax) * nMax;309 uint64 nRand = 0;310 do311 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));312 while (nRand >= nRange);313 return (nRand % nMax);314}315316317318319320321322323324325//326// "Never go to sea with two chronometers; take one or three."327// Our three chronometers are:328// - System clock329// - Median of other server's clocks330// - NTP servers331//332// note: NTP isn't implemented yet, so until then we just use the median333// of other nodes clocks to correct ours.334//335336int64 GetTime()337{338 return time(NULL);339}340341static int64 nTimeOffset = 0;342343int64 GetAdjustedTime()344{345 return GetTime() + nTimeOffset;346}347348void AddTimeData(unsigned int ip, int64 nTime)349{350 int64 nOffsetSample = nTime - GetTime();351352 // Ignore duplicates353 static set<unsigned int> setKnown;354 if (!setKnown.insert(ip).second)355 return;356357 // Add data358 static vector<int64> vTimeOffsets;359 if (vTimeOffsets.empty())360 vTimeOffsets.push_back(0);361 vTimeOffsets.push_back(nOffsetSample);362 printf("Added time data, samples %d, ip %08x, offset %+I64d (%+I64d minutes)\n", vTimeOffsets.size(), ip, vTimeOffsets.back(), vTimeOffsets.back()/60);363 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)364 {365 sort(vTimeOffsets.begin(), vTimeOffsets.end());366 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];367 nTimeOffset = nMedian;368 if ((nMedian > 0 ? nMedian : -nMedian) > 5 * 60)369 {370 // Only let other nodes change our clock so far before we371 // go to the NTP servers372 /// todo: Get time from NTP servers, then set a flag373 /// to make sure it doesn't get changed again374 }375 foreach(int64 n, vTimeOffsets)376 printf("%+I64d ", n);377 printf("| nTimeOffset = %+I64d (%+I64d minutes)\n", nTimeOffset, nTimeOffset/60);378 }379}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
