Bitcoin v0.3.10 · 2010-08-15
util.cpp
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"678map<string, string> mapArgs;9map<string, vector<string> > mapMultiArgs;10bool fDebug = false;11bool fPrintToConsole = false;12bool fPrintToDebugger = false;13char pszSetDataDir[MAX_PATH] = "";14bool fShutdown = false;15bool fDaemon = false;16bool fCommandLine = false;171819202122// Workaround for "multiple definition of `_tls_used'"23// http://svn.boost.org/trac/boost/ticket/425824extern "C" void tss_cleanup_implemented() { }252627282930// Init openssl library multithreading support31static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;32void locking_callback(int mode, int i, const char* file, int line)33{34 if (mode & CRYPTO_LOCK)35 ppmutexOpenSSL[i]->lock();36 else37 ppmutexOpenSSL[i]->unlock();38}3940// Init41class CInit42{43public:44 CInit()45 {46 // Init openssl library multithreading support47 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));48 for (int i = 0; i < CRYPTO_num_locks(); i++)49 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();50 CRYPTO_set_locking_callback(locking_callback);5152#ifdef __WXMSW__53 // Seed random number generator with screen scrape and other hardware sources54 RAND_screen();55#endif5657 // Seed random number generator with performance counter58 RandAddSeed();59 }60 ~CInit()61 {62 // Shutdown openssl library multithreading support63 CRYPTO_set_locking_callback(NULL);64 for (int i = 0; i < CRYPTO_num_locks(); i++)65 delete ppmutexOpenSSL[i];66 OPENSSL_free(ppmutexOpenSSL);67 }68}69instance_of_cinit;707172737475767778void RandAddSeed()79{80 // Seed with CPU performance counter81 int64 nCounter = PerformanceCounter();82 RAND_add(&nCounter, sizeof(nCounter), 1.5);83 memset(&nCounter, 0, sizeof(nCounter));84}8586void RandAddSeedPerfmon()87{88 RandAddSeed();8990 // This can take up to 2 seconds, so only do it every 10 minutes91 static int64 nLastPerfmon;92 if (GetTime() < nLastPerfmon + 10 * 60)93 return;94 nLastPerfmon = GetTime();9596#ifdef __WXMSW__97 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom98 // Seed with the entire set of perfmon data99 unsigned char pdata[250000];100 memset(pdata, 0, sizeof(pdata));101 unsigned long nSize = sizeof(pdata);102 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);103 RegCloseKey(HKEY_PERFORMANCE_DATA);104 if (ret == ERROR_SUCCESS)105 {106 uint256 hash;107 SHA256(pdata, nSize, (unsigned char*)&hash);108 RAND_add(&hash, sizeof(hash), min(nSize/500.0, (double)sizeof(hash)));109 hash = 0;110 memset(pdata, 0, nSize);111112 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);113 }114#endif115}116117uint64 GetRand(uint64 nMax)118{119 if (nMax == 0)120 return 0;121122 // The range of the random source must be a multiple of the modulus123 // to give every possible output value an equal possibility124 uint64 nRange = (UINT64_MAX / nMax) * nMax;125 uint64 nRand = 0;126 do127 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));128 while (nRand >= nRange);129 return (nRand % nMax);130}131132133134135136137138139140141142inline int OutputDebugStringF(const char* pszFormat, ...)143{144 int ret = 0;145 if (fPrintToConsole)146 {147 // print to console148 va_list arg_ptr;149 va_start(arg_ptr, pszFormat);150 ret = vprintf(pszFormat, arg_ptr);151 va_end(arg_ptr);152 }153 else154 {155 // print to debug.log156 char pszFile[MAX_PATH+100];157 GetDataDir(pszFile);158 strlcat(pszFile, "/debug.log", sizeof(pszFile));159 FILE* fileout = fopen(pszFile, "a");160 if (fileout)161 {162 //// Debug print useful for profiling163 //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());164 va_list arg_ptr;165 va_start(arg_ptr, pszFormat);166 ret = vfprintf(fileout, pszFormat, arg_ptr);167 va_end(arg_ptr);168 fclose(fileout);169 }170 }171172#ifdef __WXMSW__173 if (fPrintToDebugger)174 {175 // accumulate a line at a time176 static CCriticalSection cs_OutputDebugStringF;177 CRITICAL_BLOCK(cs_OutputDebugStringF)178 {179 static char pszBuffer[50000];180 static char* pend;181 if (pend == NULL)182 pend = pszBuffer;183 va_list arg_ptr;184 va_start(arg_ptr, pszFormat);185 int limit = END(pszBuffer) - pend - 2;186 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);187 va_end(arg_ptr);188 if (ret < 0 || ret >= limit)189 {190 pend = END(pszBuffer) - 2;191 *pend++ = '\n';192 }193 else194 pend += ret;195 *pend = '\0';196 char* p1 = pszBuffer;197 char* p2;198 while (p2 = strchr(p1, '\n'))199 {200 p2++;201 char c = *p2;202 *p2 = '\0';203 OutputDebugStringA(p1);204 *p2 = c;205 p1 = p2;206 }207 if (p1 != pszBuffer)208 memmove(pszBuffer, p1, pend - p1 + 1);209 pend -= (p1 - pszBuffer);210 }211 }212#endif213 return ret;214}215216217// Safer snprintf218// - prints up to limit-1 characters219// - output string is always null terminated even if limit reached220// - return value is the number of characters actually printed221int my_snprintf(char* buffer, size_t limit, const char* format, ...)222{223 if (limit == 0)224 return 0;225 va_list arg_ptr;226 va_start(arg_ptr, format);227 int ret = _vsnprintf(buffer, limit, format, arg_ptr);228 va_end(arg_ptr);229 if (ret < 0 || ret >= limit)230 {231 ret = limit - 1;232 buffer[limit-1] = 0;233 }234 return ret;235}236237238string strprintf(const char* format, ...)239{240 char buffer[50000];241 char* p = buffer;242 int limit = sizeof(buffer);243 int ret;244 loop245 {246 va_list arg_ptr;247 va_start(arg_ptr, format);248 ret = _vsnprintf(p, limit, format, arg_ptr);249 va_end(arg_ptr);250 if (ret >= 0 && ret < limit)251 break;252 if (p != buffer)253 delete p;254 limit *= 2;255 p = new char[limit];256 if (p == NULL)257 throw std::bad_alloc();258 }259 string str(p, p+ret);260 if (p != buffer)261 delete p;262 return str;263}264265266bool error(const char* format, ...)267{268 char buffer[50000];269 int limit = sizeof(buffer);270 va_list arg_ptr;271 va_start(arg_ptr, format);272 int ret = _vsnprintf(buffer, limit, format, arg_ptr);273 va_end(arg_ptr);274 if (ret < 0 || ret >= limit)275 {276 ret = limit - 1;277 buffer[limit-1] = 0;278 }279 printf("ERROR: %s\n", buffer);280 return false;281}282283284void ParseString(const string& str, char c, vector<string>& v)285{286 if (str.empty())287 return;288 string::size_type i1 = 0;289 string::size_type i2;290 loop291 {292 i2 = str.find(c, i1);293 if (i2 == str.npos)294 {295 v.push_back(str.substr(i1));296 return;297 }298 v.push_back(str.substr(i1, i2-i1));299 i1 = i2+1;300 }301}302303304string FormatMoney(int64 n, bool fPlus)305{306 n /= CENT;307 string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);308 for (int i = 6; i < str.size(); i += 4)309 if (isdigit(str[str.size() - i - 1]))310 str.insert(str.size() - i, 1, ',');311 if (n < 0)312 str.insert((unsigned int)0, 1, '-');313 else if (fPlus && n > 0)314 str.insert((unsigned int)0, 1, '+');315 return str;316}317318319bool ParseMoney(const string& str, int64& nRet)320{321 return ParseMoney(str.c_str(), nRet);322}323324bool ParseMoney(const char* pszIn, int64& nRet)325{326 string strWhole;327 int64 nCents = 0;328 const char* p = pszIn;329 while (isspace(*p))330 p++;331 for (; *p; p++)332 {333 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))334 continue;335 if (*p == '.')336 {337 p++;338 if (isdigit(*p))339 {340 nCents = 10 * (*p++ - '0');341 if (isdigit(*p))342 nCents += (*p++ - '0');343 }344 break;345 }346 if (isspace(*p))347 break;348 if (!isdigit(*p))349 return false;350 strWhole.insert(strWhole.end(), *p);351 }352 for (; *p; p++)353 if (!isspace(*p))354 return false;355 if (strWhole.size() > 14)356 return false;357 if (nCents < 0 || nCents > 99)358 return false;359 int64 nWhole = atoi64(strWhole);360 int64 nPreValue = nWhole * 100 + nCents;361 int64 nValue = nPreValue * CENT;362 if (nValue / CENT != nPreValue)363 return false;364 if (nValue / COIN != nWhole)365 return false;366 nRet = nValue;367 return true;368}369370371vector<unsigned char> ParseHex(const char* psz)372{373 vector<unsigned char> vch;374 while (isspace(*psz))375 psz++;376 vch.reserve((strlen(psz)+1)/3);377378 static char phexdigit[256] =379 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,380 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,381 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,382 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,383 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,384 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,385 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1386 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,387 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,388 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,389 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,390 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,391 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,392 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,393 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,394 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };395396 while (*psz)397 {398 char c = phexdigit[(unsigned char)*psz++];399 if (c == -1)400 break;401 unsigned char n = (c << 4);402 if (*psz)403 {404 char c = phexdigit[(unsigned char)*psz++];405 if (c == -1)406 break;407 n |= c;408 vch.push_back(n);409 }410 while (isspace(*psz))411 psz++;412 }413414 return vch;415}416417vector<unsigned char> ParseHex(const std::string& str)418{419 return ParseHex(str.c_str());420}421422423void ParseParameters(int argc, char* argv[])424{425 mapArgs.clear();426 mapMultiArgs.clear();427 for (int i = 1; i < argc; i++)428 {429 char psz[10000];430 strlcpy(psz, argv[i], sizeof(psz));431 char* pszValue = (char*)"";432 if (strchr(psz, '='))433 {434 pszValue = strchr(psz, '=');435 *pszValue++ = '\0';436 }437 #ifdef __WXMSW__438 _strlwr(psz);439 if (psz[0] == '/')440 psz[0] = '-';441 #endif442 if (psz[0] != '-')443 break;444 mapArgs[psz] = pszValue;445 mapMultiArgs[psz].push_back(pszValue);446 }447}448449450const char* wxGetTranslation(const char* pszEnglish)451{452#ifdef GUI453 // Wrapper of wxGetTranslation returning the same const char* type as was passed in454 static CCriticalSection cs;455 CRITICAL_BLOCK(cs)456 {457 // Look in cache458 static map<string, char*> mapCache;459 map<string, char*>::iterator mi = mapCache.find(pszEnglish);460 if (mi != mapCache.end())461 return (*mi).second;462463 // wxWidgets translation464 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));465466 // We don't cache unknown strings because caller might be passing in a467 // dynamic string and we would keep allocating memory for each variation.468 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)469 return pszEnglish;470471 // Add to cache, memory doesn't need to be freed. We only cache because472 // we must pass back a pointer to permanently allocated memory.473 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];474 strcpy(pszCached, strTranslated.utf8_str());475 mapCache[pszEnglish] = pszCached;476 return pszCached;477 }478 return NULL;479#else480 return pszEnglish;481#endif482}483484485486487488489490491492493void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)494{495#ifdef __WXMSW__496 char pszModule[MAX_PATH];497 pszModule[0] = '\0';498 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));499#else500 const char* pszModule = "bitcoin";501#endif502 if (pex)503 snprintf(pszMessage, 1000,504 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);505 else506 snprintf(pszMessage, 1000,507 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);508}509510void LogException(std::exception* pex, const char* pszThread)511{512 char pszMessage[1000];513 FormatException(pszMessage, pex, pszThread);514 printf("\n%s", pszMessage);515}516517void PrintException(std::exception* pex, const char* pszThread)518{519 char pszMessage[1000];520 FormatException(pszMessage, pex, pszThread);521 printf("\n\n************************\n%s\n", pszMessage);522 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);523#ifdef GUI524 if (wxTheApp && !fDaemon)525 MyMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);526#endif527 throw;528 //DebugBreak();529}530531532533534535536537538#ifdef __WXMSW__539typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);540541string MyGetSpecialFolderPath(int nFolder, bool fCreate)542{543 char pszPath[MAX_PATH+100] = "";544545 // SHGetSpecialFolderPath isn't always available on old Windows versions546 HMODULE hShell32 = LoadLibraryA("shell32.dll");547 if (hShell32)548 {549 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =550 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");551 if (pSHGetSpecialFolderPath)552 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);553 FreeModule(hShell32);554 }555556 // Backup option557 if (pszPath[0] == '\0')558 {559 if (nFolder == CSIDL_STARTUP)560 {561 strcpy(pszPath, getenv("USERPROFILE"));562 strcat(pszPath, "\\Start Menu\\Programs\\Startup");563 }564 else if (nFolder == CSIDL_APPDATA)565 {566 strcpy(pszPath, getenv("APPDATA"));567 }568 }569570 return pszPath;571}572#endif573574string GetDefaultDataDir()575{576 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin577 // Mac: ~/Library/Application Support/Bitcoin578 // Unix: ~/.bitcoin579#ifdef __WXMSW__580 // Windows581 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";582#else583 char* pszHome = getenv("HOME");584 if (pszHome == NULL || strlen(pszHome) == 0)585 pszHome = (char*)"/";586 string strHome = pszHome;587 if (strHome[strHome.size()-1] != '/')588 strHome += '/';589#ifdef __WXMAC_OSX__590 // Mac591 strHome += "Library/Application Support/";592 filesystem::create_directory(strHome.c_str());593 return strHome + "Bitcoin";594#else595 // Unix596 return strHome + ".bitcoin";597#endif598#endif599}600601void GetDataDir(char* pszDir)602{603 // pszDir must be at least MAX_PATH length.604 if (pszSetDataDir[0] != 0)605 {606 strlcpy(pszDir, pszSetDataDir, MAX_PATH);607 static bool fMkdirDone;608 if (!fMkdirDone)609 {610 fMkdirDone = true;611 filesystem::create_directory(pszDir);612 }613 }614 else615 {616 // This can be called during exceptions by printf, so we cache the617 // value so we don't have to do memory allocations after that.618 static char pszCachedDir[MAX_PATH];619 if (pszCachedDir[0] == 0)620 {621 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));622 filesystem::create_directory(pszCachedDir);623 }624 strlcpy(pszDir, pszCachedDir, MAX_PATH);625 }626}627628string GetDataDir()629{630 char pszDir[MAX_PATH];631 GetDataDir(pszDir);632 return pszDir;633}634635string GetConfigFile()636{637 namespace fs = boost::filesystem;638 fs::path pathConfig(mapArgs.count("-conf") ? mapArgs["-conf"] : string("bitcoin.conf"));639 if (!pathConfig.is_complete())640 pathConfig = fs::path(GetDataDir()) / pathConfig;641 return pathConfig.string();642}643644void ReadConfigFile(map<string, string>& mapSettingsRet,645 map<string, vector<string> >& mapMultiSettingsRet)646{647 namespace fs = boost::filesystem;648 namespace pod = boost::program_options::detail;649650 fs::ifstream streamConfig(GetConfigFile());651 if (!streamConfig.good())652 return;653654 set<string> setOptions;655 setOptions.insert("*");656 657 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)658 {659 // Don't overwrite existing settings so command line settings override bitcoin.conf660 string strKey = string("-") + it->string_key;661 if (mapSettingsRet.count(strKey) == 0)662 mapSettingsRet[strKey] = it->value[0];663 mapMultiSettingsRet[strKey].push_back(it->value[0]);664 }665}666667int GetFilesize(FILE* file)668{669 int nSavePos = ftell(file);670 int nFilesize = -1;671 if (fseek(file, 0, SEEK_END) == 0)672 nFilesize = ftell(file);673 fseek(file, nSavePos, SEEK_SET);674 return nFilesize;675}676677void ShrinkDebugFile()678{679 // Scroll debug.log if it's getting too big680 string strFile = GetDataDir() + "/debug.log";681 FILE* file = fopen(strFile.c_str(), "r");682 if (file && GetFilesize(file) > 10 * 1000000)683 {684 // Restart the file with some of the end685 char pch[200000];686 fseek(file, -sizeof(pch), SEEK_END);687 int nBytes = fread(pch, 1, sizeof(pch), file);688 fclose(file);689 if (file = fopen(strFile.c_str(), "w"))690 {691 fwrite(pch, 1, nBytes, file);692 fclose(file);693 }694 }695}696697698699700701702703704//705// "Never go to sea with two chronometers; take one or three."706// Our three chronometers are:707// - System clock708// - Median of other server's clocks709// - NTP servers710//711// note: NTP isn't implemented yet, so until then we just use the median712// of other nodes clocks to correct ours.713//714int64 GetTime()715{716 return time(NULL);717}718719static int64 nTimeOffset = 0;720721int64 GetAdjustedTime()722{723 return GetTime() + nTimeOffset;724}725726void AddTimeData(unsigned int ip, int64 nTime)727{728 int64 nOffsetSample = nTime - GetTime();729730 // Ignore duplicates731 static set<unsigned int> setKnown;732 if (!setKnown.insert(ip).second)733 return;734735 // Add data736 static vector<int64> vTimeOffsets;737 if (vTimeOffsets.empty())738 vTimeOffsets.push_back(0);739 vTimeOffsets.push_back(nOffsetSample);740 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);741 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)742 {743 sort(vTimeOffsets.begin(), vTimeOffsets.end());744 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];745 nTimeOffset = nMedian;746 if ((nMedian > 0 ? nMedian : -nMedian) > 70 * 60)747 {748 // Only let other nodes change our clock so far before we749 // go to the NTP servers750 /// todo: Get time from NTP servers, then set a flag751 /// to make sure it doesn't get changed again752 nTimeOffset = 0;753 }754 foreach(int64 n, vTimeOffsets)755 printf("%+"PRI64d" ", n);756 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);757 }758}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
