1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 map<string, string> mapArgs;
9 map<string, vector<string> > mapMultiArgs;
11 bool fPrintToConsole = false;
12 bool fPrintToDebugger = false;
13 char pszSetDataDir[MAX_PATH] = "";
14 bool fRequestShutdown = false;
15 bool fShutdown = false;
17 bool fCommandLine = false;
18 string strMiscWarning;
24 // Workaround for "multiple definition of `_tls_used'"
25 // http://svn.boost.org/trac/boost/ticket/4258
26 extern "C" void tss_cleanup_implemented() { }
32 // Init openssl library multithreading support
33 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
34 void locking_callback(int mode, int i, const char* file, int line)
36 if (mode & CRYPTO_LOCK)
37 ppmutexOpenSSL[i]->lock();
39 ppmutexOpenSSL[i]->unlock();
48 // Init openssl library multithreading support
49 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
50 for (int i = 0; i < CRYPTO_num_locks(); i++)
51 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
52 CRYPTO_set_locking_callback(locking_callback);
55 // Seed random number generator with screen scrape and other hardware sources
59 // Seed random number generator with performance counter
64 // Shutdown openssl library multithreading support
65 CRYPTO_set_locking_callback(NULL);
66 for (int i = 0; i < CRYPTO_num_locks(); i++)
67 delete ppmutexOpenSSL[i];
68 OPENSSL_free(ppmutexOpenSSL);
82 // Seed with CPU performance counter
83 int64 nCounter = GetPerformanceCounter();
84 RAND_add(&nCounter, sizeof(nCounter), 1.5);
85 memset(&nCounter, 0, sizeof(nCounter));
88 void RandAddSeedPerfmon()
92 // This can take up to 2 seconds, so only do it every 10 minutes
93 static int64 nLastPerfmon;
94 if (GetTime() < nLastPerfmon + 10 * 60)
96 nLastPerfmon = GetTime();
99 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
100 // Seed with the entire set of perfmon data
101 unsigned char pdata[250000];
102 memset(pdata, 0, sizeof(pdata));
103 unsigned long nSize = sizeof(pdata);
104 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
105 RegCloseKey(HKEY_PERFORMANCE_DATA);
106 if (ret == ERROR_SUCCESS)
108 RAND_add(pdata, nSize, nSize/100.0);
109 memset(pdata, 0, nSize);
110 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
115 uint64 GetRand(uint64 nMax)
120 // The range of the random source must be a multiple of the modulus
121 // to give every possible output value an equal possibility
122 uint64 nRange = (UINT64_MAX / nMax) * nMax;
125 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
126 while (nRand >= nRange);
127 return (nRand % nMax);
130 int GetRandInt(int nMax)
132 return GetRand(nMax);
145 inline int OutputDebugStringF(const char* pszFormat, ...)
152 va_start(arg_ptr, pszFormat);
153 ret = vprintf(pszFormat, arg_ptr);
158 // print to debug.log
159 char pszFile[MAX_PATH+100];
161 strlcat(pszFile, "/debug.log", sizeof(pszFile));
162 FILE* fileout = fopen(pszFile, "a");
165 //// Debug print useful for profiling
166 //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());
168 va_start(arg_ptr, pszFormat);
169 ret = vfprintf(fileout, pszFormat, arg_ptr);
176 if (fPrintToDebugger)
178 // accumulate a line at a time
179 static CCriticalSection cs_OutputDebugStringF;
180 CRITICAL_BLOCK(cs_OutputDebugStringF)
182 static char pszBuffer[50000];
187 va_start(arg_ptr, pszFormat);
188 int limit = END(pszBuffer) - pend - 2;
189 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
191 if (ret < 0 || ret >= limit)
193 pend = END(pszBuffer) - 2;
199 char* p1 = pszBuffer;
201 while (p2 = strchr(p1, '\n'))
206 OutputDebugStringA(p1);
211 memmove(pszBuffer, p1, pend - p1 + 1);
212 pend -= (p1 - pszBuffer);
221 // - prints up to limit-1 characters
222 // - output string is always null terminated even if limit reached
223 // - return value is the number of characters actually printed
224 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
229 va_start(arg_ptr, format);
230 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
232 if (ret < 0 || ret >= limit)
241 string strprintf(const char* format, ...)
245 int limit = sizeof(buffer);
250 va_start(arg_ptr, format);
251 ret = _vsnprintf(p, limit, format, arg_ptr);
253 if (ret >= 0 && ret < limit)
260 throw std::bad_alloc();
262 string str(p, p+ret);
269 bool error(const char* format, ...)
272 int limit = sizeof(buffer);
274 va_start(arg_ptr, format);
275 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
277 if (ret < 0 || ret >= limit)
282 printf("ERROR: %s\n", buffer);
287 void ParseString(const string& str, char c, vector<string>& v)
291 string::size_type i1 = 0;
292 string::size_type i2;
295 i2 = str.find(c, i1);
298 v.push_back(str.substr(i1));
301 v.push_back(str.substr(i1, i2-i1));
307 string FormatMoney(int64 n, bool fPlus)
310 string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);
311 for (int i = 6; i < str.size(); i += 4)
312 if (isdigit(str[str.size() - i - 1]))
313 str.insert(str.size() - i, 1, ',');
315 str.insert((unsigned int)0, 1, '-');
316 else if (fPlus && n > 0)
317 str.insert((unsigned int)0, 1, '+');
322 bool ParseMoney(const string& str, int64& nRet)
324 return ParseMoney(str.c_str(), nRet);
327 bool ParseMoney(const char* pszIn, int64& nRet)
331 const char* p = pszIn;
336 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
343 nCents = 10 * (*p++ - '0');
345 nCents += (*p++ - '0');
353 strWhole.insert(strWhole.end(), *p);
358 if (strWhole.size() > 14)
360 if (nCents < 0 || nCents > 99)
362 int64 nWhole = atoi64(strWhole);
363 int64 nPreValue = nWhole * 100 + nCents;
364 int64 nValue = nPreValue * CENT;
365 if (nValue / CENT != nPreValue)
367 if (nValue / COIN != nWhole)
374 vector<unsigned char> ParseHex(const char* psz)
376 static char phexdigit[256] =
377 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
378 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
379 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
380 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
381 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
382 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
386 -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, };
394 // convert hex dump to vector
395 vector<unsigned char> vch;
398 while (isspace(*psz))
400 char c = phexdigit[(unsigned char)*psz++];
403 unsigned char n = (c << 4);
404 c = phexdigit[(unsigned char)*psz++];
413 vector<unsigned char> ParseHex(const string& str)
415 return ParseHex(str.c_str());
419 void ParseParameters(int argc, char* argv[])
422 mapMultiArgs.clear();
423 for (int i = 1; i < argc; i++)
426 strlcpy(psz, argv[i], sizeof(psz));
427 char* pszValue = (char*)"";
428 if (strchr(psz, '='))
430 pszValue = strchr(psz, '=');
440 mapArgs[psz] = pszValue;
441 mapMultiArgs[psz].push_back(pszValue);
446 const char* wxGetTranslation(const char* pszEnglish)
449 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
450 static CCriticalSection cs;
454 static map<string, char*> mapCache;
455 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
456 if (mi != mapCache.end())
459 // wxWidgets translation
460 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
462 // We don't cache unknown strings because caller might be passing in a
463 // dynamic string and we would keep allocating memory for each variation.
464 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
467 // Add to cache, memory doesn't need to be freed. We only cache because
468 // we must pass back a pointer to permanently allocated memory.
469 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
470 strcpy(pszCached, strTranslated.utf8_str());
471 mapCache[pszEnglish] = pszCached;
481 bool WildcardMatch(const char* psz, const char* mask)
488 return (*psz == '\0');
490 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
505 bool WildcardMatch(const string& str, const string& mask)
507 return WildcardMatch(str.c_str(), mask.c_str());
517 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
520 char pszModule[MAX_PATH];
522 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
524 const char* pszModule = "bitcoin";
527 snprintf(pszMessage, 1000,
528 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
530 snprintf(pszMessage, 1000,
531 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
534 void LogException(std::exception* pex, const char* pszThread)
536 char pszMessage[10000];
537 FormatException(pszMessage, pex, pszThread);
538 printf("\n%s", pszMessage);
541 void PrintException(std::exception* pex, const char* pszThread)
543 char pszMessage[10000];
544 FormatException(pszMessage, pex, pszThread);
545 printf("\n\n************************\n%s\n", pszMessage);
546 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
547 strMiscWarning = pszMessage;
549 if (wxTheApp && !fDaemon)
550 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
555 void ThreadOneMessageBox(string strMessage)
557 // Skip message boxes if one is already open
558 static bool fMessageBoxOpen;
561 fMessageBoxOpen = true;
562 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
563 fMessageBoxOpen = false;
566 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
568 char pszMessage[10000];
569 FormatException(pszMessage, pex, pszThread);
570 printf("\n\n************************\n%s\n", pszMessage);
571 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
572 strMiscWarning = pszMessage;
574 if (wxTheApp && !fDaemon)
575 boost::thread(bind(ThreadOneMessageBox, string(pszMessage)));
587 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
589 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
591 char pszPath[MAX_PATH+100] = "";
593 // SHGetSpecialFolderPath isn't always available on old Windows versions
594 HMODULE hShell32 = LoadLibraryA("shell32.dll");
597 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
598 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
599 if (pSHGetSpecialFolderPath)
600 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
601 FreeModule(hShell32);
605 if (pszPath[0] == '\0')
607 if (nFolder == CSIDL_STARTUP)
609 strcpy(pszPath, getenv("USERPROFILE"));
610 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
612 else if (nFolder == CSIDL_APPDATA)
614 strcpy(pszPath, getenv("APPDATA"));
622 string GetDefaultDataDir()
624 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
625 // Mac: ~/Library/Application Support/Bitcoin
629 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
631 char* pszHome = getenv("HOME");
632 if (pszHome == NULL || strlen(pszHome) == 0)
633 pszHome = (char*)"/";
634 string strHome = pszHome;
635 if (strHome[strHome.size()-1] != '/')
639 strHome += "Library/Application Support/";
640 filesystem::create_directory(strHome.c_str());
641 return strHome + "Bitcoin";
644 return strHome + ".bitcoin";
649 void GetDataDir(char* pszDir)
651 // pszDir must be at least MAX_PATH length.
652 if (pszSetDataDir[0] != 0)
654 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
655 static bool fMkdirDone;
659 filesystem::create_directory(pszDir);
664 // This can be called during exceptions by printf, so we cache the
665 // value so we don't have to do memory allocations after that.
666 static char pszCachedDir[MAX_PATH];
667 if (pszCachedDir[0] == 0)
669 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
670 filesystem::create_directory(pszCachedDir);
672 strlcpy(pszDir, pszCachedDir, MAX_PATH);
678 char pszDir[MAX_PATH];
683 string GetConfigFile()
685 namespace fs = boost::filesystem;
686 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
687 if (!pathConfig.is_complete())
688 pathConfig = fs::path(GetDataDir()) / pathConfig;
689 return pathConfig.string();
692 void ReadConfigFile(map<string, string>& mapSettingsRet,
693 map<string, vector<string> >& mapMultiSettingsRet)
695 namespace fs = boost::filesystem;
696 namespace pod = boost::program_options::detail;
698 fs::ifstream streamConfig(GetConfigFile());
699 if (!streamConfig.good())
702 set<string> setOptions;
703 setOptions.insert("*");
705 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
707 // Don't overwrite existing settings so command line settings override bitcoin.conf
708 string strKey = string("-") + it->string_key;
709 if (mapSettingsRet.count(strKey) == 0)
710 mapSettingsRet[strKey] = it->value[0];
711 mapMultiSettingsRet[strKey].push_back(it->value[0]);
715 int GetFilesize(FILE* file)
717 int nSavePos = ftell(file);
719 if (fseek(file, 0, SEEK_END) == 0)
720 nFilesize = ftell(file);
721 fseek(file, nSavePos, SEEK_SET);
725 void ShrinkDebugFile()
727 // Scroll debug.log if it's getting too big
728 string strFile = GetDataDir() + "/debug.log";
729 FILE* file = fopen(strFile.c_str(), "r");
730 if (file && GetFilesize(file) > 10 * 1000000)
732 // Restart the file with some of the end
734 fseek(file, -sizeof(pch), SEEK_END);
735 int nBytes = fread(pch, 1, sizeof(pch), file);
737 if (file = fopen(strFile.c_str(), "w"))
739 fwrite(pch, 1, nBytes, file);
753 // "Never go to sea with two chronometers; take one or three."
754 // Our three time sources are:
756 // - Median of other nodes's clocks
757 // - The user (asking the user to fix the system clock if the first two disagree)
764 static int64 nTimeOffset = 0;
766 int64 GetAdjustedTime()
768 return GetTime() + nTimeOffset;
771 void AddTimeData(unsigned int ip, int64 nTime)
773 int64 nOffsetSample = nTime - GetTime();
776 static set<unsigned int> setKnown;
777 if (!setKnown.insert(ip).second)
781 static vector<int64> vTimeOffsets;
782 if (vTimeOffsets.empty())
783 vTimeOffsets.push_back(0);
784 vTimeOffsets.push_back(nOffsetSample);
785 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
786 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
788 sort(vTimeOffsets.begin(), vTimeOffsets.end());
789 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
790 // Only let other nodes change our time by so much
791 if (abs64(nMedian) < 70 * 60)
793 nTimeOffset = nMedian;
798 // If nobody else has the same time as us, give a warning
800 foreach(int64 nOffset, vTimeOffsets)
801 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
804 if (!fMatch && !fDone)
807 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
808 strMiscWarning = strMessage;
809 printf("*** %s\n", strMessage.c_str());
810 boost::thread(bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
813 foreach(int64 n, vTimeOffsets)
814 printf("%+"PRI64d" ", n);
815 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);