Bitcoin v0.1.0 · 2009-01-08
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);83 printf("RandAddSeed() got %d bytes of performance data\n", nSize);84 }85 }86}8788899091929394959697// Safer snprintf98// - prints up to limit-1 characters99// - output string is always null terminated even if limit reached100// - return value is the number of characters actually printed101int my_snprintf(char* buffer, size_t limit, const char* format, ...)102{103 if (limit == 0)104 return 0;105 va_list arg_ptr;106 va_start(arg_ptr, format);107 int ret = _vsnprintf(buffer, limit, format, arg_ptr);108 va_end(arg_ptr);109 if (ret < 0 || ret >= limit)110 {111 ret = limit - 1;112 buffer[limit-1] = 0;113 }114 return ret;115}116117118string strprintf(const char* format, ...)119{120 char buffer[50000];121 char* p = buffer;122 int limit = sizeof(buffer);123 int ret;124 loop125 {126 va_list arg_ptr;127 va_start(arg_ptr, format);128 ret = _vsnprintf(p, limit, format, arg_ptr);129 va_end(arg_ptr);130 if (ret >= 0 && ret < limit)131 break;132 if (p != buffer)133 delete p;134 limit *= 2;135 p = new char[limit];136 if (p == NULL)137 throw std::bad_alloc();138 }139#ifdef _MSC_VER140 // msvc optimisation141 if (p == buffer)142 return string(p, p+ret);143#endif144 string str(p, p+ret);145 if (p != buffer)146 delete p;147 return str;148}149150151bool error(const char* format, ...)152{153 char buffer[50000];154 int limit = sizeof(buffer);155 va_list arg_ptr;156 va_start(arg_ptr, format);157 int ret = _vsnprintf(buffer, limit, format, arg_ptr);158 va_end(arg_ptr);159 if (ret < 0 || ret >= limit)160 {161 ret = limit - 1;162 buffer[limit-1] = 0;163 }164 printf("ERROR: %s\n", buffer);165 return false;166}167168169void PrintException(std::exception* pex, const char* pszThread)170{171 char pszModule[260];172 pszModule[0] = '\0';173 GetModuleFileName(NULL, pszModule, sizeof(pszModule));174 _strlwr(pszModule);175 char pszMessage[1000];176 if (pex)177 snprintf(pszMessage, sizeof(pszMessage),178 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);179 else180 snprintf(pszMessage, sizeof(pszMessage),181 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);182 printf("\n\n************************\n%s", pszMessage);183 if (wxTheApp)184 wxMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);185 throw;186 //DebugBreak();187}188189190void ParseString(const string& str, char c, vector<string>& v)191{192 unsigned int i1 = 0;193 unsigned int i2;194 do195 {196 i2 = str.find(c, i1);197 v.push_back(str.substr(i1, i2-i1));198 i1 = i2+1;199 }200 while (i2 != str.npos);201}202203204string FormatMoney(int64 n, bool fPlus)205{206 n /= CENT;207 string str = strprintf("%I64d.%02I64d", (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);208 for (int i = 6; i < str.size(); i += 4)209 if (isdigit(str[str.size() - i - 1]))210 str.insert(str.size() - i, 1, ',');211 if (n < 0)212 str.insert((unsigned int)0, 1, '-');213 else if (fPlus && n > 0)214 str.insert((unsigned int)0, 1, '+');215 return str;216}217218bool ParseMoney(const char* pszIn, int64& nRet)219{220 string strWhole;221 int64 nCents = 0;222 const char* p = pszIn;223 while (isspace(*p))224 p++;225 for (; *p; p++)226 {227 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))228 continue;229 if (*p == '.')230 {231 p++;232 if (!isdigit(p[0]) || !isdigit(p[1]))233 return false;234 nCents = atoi64(p);235 if (nCents < 0 || nCents > 99)236 return false;237 p += 2;238 break;239 }240 if (isspace(*p))241 break;242 if (!isdigit(*p))243 return false;244 strWhole.insert(strWhole.end(), *p);245 }246 for (; *p; p++)247 if (!isspace(*p))248 return false;249 if (strWhole.size() > 17)250 return false;251 int64 nWhole = atoi64(strWhole);252 int64 nValue = nWhole * 100 + nCents;253 if (nValue / 100 != nWhole)254 return false;255 nValue *= CENT;256 nRet = nValue;257 return true;258}259260261262263264265266267268269bool FileExists(const char* psz)270{271#ifdef WIN32272 return GetFileAttributes(psz) != -1;273#else274 return access(psz, 0) != -1;275#endif276}277278int GetFilesize(FILE* file)279{280 int nSavePos = ftell(file);281 int nFilesize = -1;282 if (fseek(file, 0, SEEK_END) == 0)283 nFilesize = ftell(file);284 fseek(file, nSavePos, SEEK_SET);285 return nFilesize;286}287288289290291292293294295uint64 GetRand(uint64 nMax)296{297 if (nMax == 0)298 return 0;299300 // The range of the random source must be a multiple of the modulus301 // to give every possible output value an equal possibility302 uint64 nRange = (_UI64_MAX / nMax) * nMax;303 uint64 nRand = 0;304 do305 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));306 while (nRand >= nRange);307 return (nRand % nMax);308}309310311312313314315316317318319//320// "Never go to sea with two chronometers; take one or three."321// Our three chronometers are:322// - System clock323// - Median of other server's clocks324// - NTP servers325//326// note: NTP isn't implemented yet, so until then we just use the median327// of other nodes clocks to correct ours.328//329330int64 GetTime()331{332 return time(NULL);333}334335static int64 nTimeOffset = 0;336337int64 GetAdjustedTime()338{339 return GetTime() + nTimeOffset;340}341342void AddTimeData(unsigned int ip, int64 nTime)343{344 int64 nOffsetSample = nTime - GetTime();345346 // Ignore duplicates347 static set<unsigned int> setKnown;348 if (!setKnown.insert(ip).second)349 return;350351 // Add data352 static vector<int64> vTimeOffsets;353 if (vTimeOffsets.empty())354 vTimeOffsets.push_back(0);355 vTimeOffsets.push_back(nOffsetSample);356 printf("Added time data, samples %d, ip %08x, offset %+I64d (%+I64d minutes)\n", vTimeOffsets.size(), ip, vTimeOffsets.back(), vTimeOffsets.back()/60);357 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)358 {359 sort(vTimeOffsets.begin(), vTimeOffsets.end());360 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];361 nTimeOffset = nMedian;362 if ((nMedian > 0 ? nMedian : -nMedian) > 5 * 60)363 {364 // Only let other nodes change our clock so far before we365 // go to the NTP servers366 /// todo: Get time from NTP servers, then set a flag367 /// to make sure it doesn't get changed again368 }369 foreach(int64 n, vTimeOffsets)370 printf("%+I64d ", n);371 printf("| nTimeOffset = %+I64d (%+I64d minutes)\n", nTimeOffset, nTimeOffset/60);372 }373}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
