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;
19 bool fTestNet = false;
25 // Workaround for "multiple definition of `_tls_used'"
26 // http://svn.boost.org/trac/boost/ticket/4258
27 extern "C" void tss_cleanup_implemented() { }
33 // Init openssl library multithreading support
34 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
35 void locking_callback(int mode, int i, const char* file, int line)
37 if (mode & CRYPTO_LOCK)
38 ppmutexOpenSSL[i]->lock();
40 ppmutexOpenSSL[i]->unlock();
49 // Init openssl library multithreading support
50 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
51 for (int i = 0; i < CRYPTO_num_locks(); i++)
52 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
53 CRYPTO_set_locking_callback(locking_callback);
56 // Seed random number generator with screen scrape and other hardware sources
60 // Seed random number generator with performance counter
65 // Shutdown openssl library multithreading support
66 CRYPTO_set_locking_callback(NULL);
67 for (int i = 0; i < CRYPTO_num_locks(); i++)
68 delete ppmutexOpenSSL[i];
69 OPENSSL_free(ppmutexOpenSSL);
83 // Seed with CPU performance counter
84 int64 nCounter = GetPerformanceCounter();
85 RAND_add(&nCounter, sizeof(nCounter), 1.5);
86 memset(&nCounter, 0, sizeof(nCounter));
89 void RandAddSeedPerfmon()
93 // This can take up to 2 seconds, so only do it every 10 minutes
94 static int64 nLastPerfmon;
95 if (GetTime() < nLastPerfmon + 10 * 60)
97 nLastPerfmon = GetTime();
100 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
101 // Seed with the entire set of perfmon data
102 unsigned char pdata[250000];
103 memset(pdata, 0, sizeof(pdata));
104 unsigned long nSize = sizeof(pdata);
105 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
106 RegCloseKey(HKEY_PERFORMANCE_DATA);
107 if (ret == ERROR_SUCCESS)
109 RAND_add(pdata, nSize, nSize/100.0);
110 memset(pdata, 0, nSize);
111 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
116 uint64 GetRand(uint64 nMax)
121 // The range of the random source must be a multiple of the modulus
122 // to give every possible output value an equal possibility
123 uint64 nRange = (UINT64_MAX / nMax) * nMax;
126 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
127 while (nRand >= nRange);
128 return (nRand % nMax);
131 int GetRandInt(int nMax)
133 return GetRand(nMax);
146 inline int OutputDebugStringF(const char* pszFormat, ...)
153 va_start(arg_ptr, pszFormat);
154 ret = vprintf(pszFormat, arg_ptr);
159 // print to debug.log
160 static FILE* fileout = NULL;
161 static int64 nOpenTime = 0;
163 if (GetTime()-nOpenTime > 10 * 60)
167 char pszFile[MAX_PATH+100];
169 strlcat(pszFile, "/debug.log", sizeof(pszFile));
170 fileout = fopen(pszFile, "a");
171 nOpenTime = GetTime();
175 //// Debug print useful for profiling
176 //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());
178 va_start(arg_ptr, pszFormat);
179 ret = vfprintf(fileout, pszFormat, arg_ptr);
186 if (fPrintToDebugger)
188 // accumulate a line at a time
189 static CCriticalSection cs_OutputDebugStringF;
190 CRITICAL_BLOCK(cs_OutputDebugStringF)
192 static char pszBuffer[50000];
197 va_start(arg_ptr, pszFormat);
198 int limit = END(pszBuffer) - pend - 2;
199 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
201 if (ret < 0 || ret >= limit)
203 pend = END(pszBuffer) - 2;
209 char* p1 = pszBuffer;
211 while (p2 = strchr(p1, '\n'))
216 OutputDebugStringA(p1);
221 memmove(pszBuffer, p1, pend - p1 + 1);
222 pend -= (p1 - pszBuffer);
231 // - prints up to limit-1 characters
232 // - output string is always null terminated even if limit reached
233 // - return value is the number of characters actually printed
234 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
239 va_start(arg_ptr, format);
240 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
242 if (ret < 0 || ret >= limit)
251 string strprintf(const char* format, ...)
255 int limit = sizeof(buffer);
260 va_start(arg_ptr, format);
261 ret = _vsnprintf(p, limit, format, arg_ptr);
263 if (ret >= 0 && ret < limit)
270 throw std::bad_alloc();
272 string str(p, p+ret);
279 bool error(const char* format, ...)
282 int limit = sizeof(buffer);
284 va_start(arg_ptr, format);
285 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
287 if (ret < 0 || ret >= limit)
292 printf("ERROR: %s\n", buffer);
297 void ParseString(const string& str, char c, vector<string>& v)
301 string::size_type i1 = 0;
302 string::size_type i2;
305 i2 = str.find(c, i1);
308 v.push_back(str.substr(i1));
311 v.push_back(str.substr(i1, i2-i1));
317 string FormatMoney(int64 n, bool fPlus)
320 string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);
321 for (int i = 6; i < str.size(); i += 4)
322 if (isdigit(str[str.size() - i - 1]))
323 str.insert(str.size() - i, 1, ',');
325 str.insert((unsigned int)0, 1, '-');
326 else if (fPlus && n > 0)
327 str.insert((unsigned int)0, 1, '+');
332 bool ParseMoney(const string& str, int64& nRet)
334 return ParseMoney(str.c_str(), nRet);
337 bool ParseMoney(const char* pszIn, int64& nRet)
341 const char* p = pszIn;
346 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
353 nCents = 10 * (*p++ - '0');
355 nCents += (*p++ - '0');
363 strWhole.insert(strWhole.end(), *p);
368 if (strWhole.size() > 14)
370 if (nCents < 0 || nCents > 99)
372 int64 nWhole = atoi64(strWhole);
373 int64 nPreValue = nWhole * 100 + nCents;
374 int64 nValue = nPreValue * CENT;
375 if (nValue / CENT != nPreValue)
377 if (nValue / COIN != nWhole)
384 vector<unsigned char> ParseHex(const char* psz)
386 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
391 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
395 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
396 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
397 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
398 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
399 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
400 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
401 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
402 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
404 // convert hex dump to vector
405 vector<unsigned char> vch;
408 while (isspace(*psz))
410 char c = phexdigit[(unsigned char)*psz++];
413 unsigned char n = (c << 4);
414 c = phexdigit[(unsigned char)*psz++];
423 vector<unsigned char> ParseHex(const string& str)
425 return ParseHex(str.c_str());
429 void ParseParameters(int argc, char* argv[])
432 mapMultiArgs.clear();
433 for (int i = 1; i < argc; i++)
436 strlcpy(psz, argv[i], sizeof(psz));
437 char* pszValue = (char*)"";
438 if (strchr(psz, '='))
440 pszValue = strchr(psz, '=');
450 mapArgs[psz] = pszValue;
451 mapMultiArgs[psz].push_back(pszValue);
456 const char* wxGetTranslation(const char* pszEnglish)
459 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
460 static CCriticalSection cs;
464 static map<string, char*> mapCache;
465 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
466 if (mi != mapCache.end())
469 // wxWidgets translation
470 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
472 // We don't cache unknown strings because caller might be passing in a
473 // dynamic string and we would keep allocating memory for each variation.
474 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
477 // Add to cache, memory doesn't need to be freed. We only cache because
478 // we must pass back a pointer to permanently allocated memory.
479 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
480 strcpy(pszCached, strTranslated.utf8_str());
481 mapCache[pszEnglish] = pszCached;
491 bool WildcardMatch(const char* psz, const char* mask)
498 return (*psz == '\0');
500 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
515 bool WildcardMatch(const string& str, const string& mask)
517 return WildcardMatch(str.c_str(), mask.c_str());
527 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
530 char pszModule[MAX_PATH];
532 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
534 const char* pszModule = "bitcoin";
537 snprintf(pszMessage, 1000,
538 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
540 snprintf(pszMessage, 1000,
541 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
544 void LogException(std::exception* pex, const char* pszThread)
546 char pszMessage[10000];
547 FormatException(pszMessage, pex, pszThread);
548 printf("\n%s", pszMessage);
551 void PrintException(std::exception* pex, const char* pszThread)
553 char pszMessage[10000];
554 FormatException(pszMessage, pex, pszThread);
555 printf("\n\n************************\n%s\n", pszMessage);
556 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
557 strMiscWarning = pszMessage;
559 if (wxTheApp && !fDaemon)
560 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
565 void ThreadOneMessageBox(string strMessage)
567 // Skip message boxes if one is already open
568 static bool fMessageBoxOpen;
571 fMessageBoxOpen = true;
572 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
573 fMessageBoxOpen = false;
576 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
578 char pszMessage[10000];
579 FormatException(pszMessage, pex, pszThread);
580 printf("\n\n************************\n%s\n", pszMessage);
581 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
582 strMiscWarning = pszMessage;
584 if (wxTheApp && !fDaemon)
585 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
597 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
599 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
601 char pszPath[MAX_PATH+100] = "";
603 // SHGetSpecialFolderPath isn't always available on old Windows versions
604 HMODULE hShell32 = LoadLibraryA("shell32.dll");
607 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
608 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
609 if (pSHGetSpecialFolderPath)
610 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
611 FreeModule(hShell32);
615 if (pszPath[0] == '\0')
617 if (nFolder == CSIDL_STARTUP)
619 strcpy(pszPath, getenv("USERPROFILE"));
620 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
622 else if (nFolder == CSIDL_APPDATA)
624 strcpy(pszPath, getenv("APPDATA"));
632 string GetDefaultDataDir()
634 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
635 // Mac: ~/Library/Application Support/Bitcoin
639 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
641 char* pszHome = getenv("HOME");
642 if (pszHome == NULL || strlen(pszHome) == 0)
643 pszHome = (char*)"/";
644 string strHome = pszHome;
645 if (strHome[strHome.size()-1] != '/')
649 strHome += "Library/Application Support/";
650 filesystem::create_directory(strHome.c_str());
651 return strHome + "Bitcoin";
654 return strHome + ".bitcoin";
659 void GetDataDir(char* pszDir)
661 // pszDir must be at least MAX_PATH length.
663 if (pszSetDataDir[0] != 0)
665 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
670 // This can be called during exceptions by printf, so we cache the
671 // value so we don't have to do memory allocations after that.
672 static char pszCachedDir[MAX_PATH];
673 if (pszCachedDir[0] == 0)
674 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
675 strlcpy(pszDir, pszCachedDir, MAX_PATH);
680 char* p = pszDir + strlen(pszDir);
681 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
683 strcpy(p, "testnet");
686 static bool pfMkdir[4];
687 if (!pfMkdir[nVariation])
689 pfMkdir[nVariation] = true;
690 filesystem::create_directory(pszDir);
696 char pszDir[MAX_PATH];
701 string GetConfigFile()
703 namespace fs = boost::filesystem;
704 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
705 if (!pathConfig.is_complete())
706 pathConfig = fs::path(GetDataDir()) / pathConfig;
707 return pathConfig.string();
710 void ReadConfigFile(map<string, string>& mapSettingsRet,
711 map<string, vector<string> >& mapMultiSettingsRet)
713 namespace fs = boost::filesystem;
714 namespace pod = boost::program_options::detail;
716 fs::ifstream streamConfig(GetConfigFile());
717 if (!streamConfig.good())
720 set<string> setOptions;
721 setOptions.insert("*");
723 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
725 // Don't overwrite existing settings so command line settings override bitcoin.conf
726 string strKey = string("-") + it->string_key;
727 if (mapSettingsRet.count(strKey) == 0)
728 mapSettingsRet[strKey] = it->value[0];
729 mapMultiSettingsRet[strKey].push_back(it->value[0]);
733 int GetFilesize(FILE* file)
735 int nSavePos = ftell(file);
737 if (fseek(file, 0, SEEK_END) == 0)
738 nFilesize = ftell(file);
739 fseek(file, nSavePos, SEEK_SET);
743 void ShrinkDebugFile()
745 // Scroll debug.log if it's getting too big
746 string strFile = GetDataDir() + "/debug.log";
747 FILE* file = fopen(strFile.c_str(), "r");
748 if (file && GetFilesize(file) > 10 * 1000000)
750 // Restart the file with some of the end
752 fseek(file, -sizeof(pch), SEEK_END);
753 int nBytes = fread(pch, 1, sizeof(pch), file);
755 if (file = fopen(strFile.c_str(), "w"))
757 fwrite(pch, 1, nBytes, file);
771 // "Never go to sea with two chronometers; take one or three."
772 // Our three time sources are:
774 // - Median of other nodes's clocks
775 // - The user (asking the user to fix the system clock if the first two disagree)
782 static int64 nTimeOffset = 0;
784 int64 GetAdjustedTime()
786 return GetTime() + nTimeOffset;
789 void AddTimeData(unsigned int ip, int64 nTime)
791 int64 nOffsetSample = nTime - GetTime();
794 static set<unsigned int> setKnown;
795 if (!setKnown.insert(ip).second)
799 static vector<int64> vTimeOffsets;
800 if (vTimeOffsets.empty())
801 vTimeOffsets.push_back(0);
802 vTimeOffsets.push_back(nOffsetSample);
803 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
804 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
806 sort(vTimeOffsets.begin(), vTimeOffsets.end());
807 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
808 // Only let other nodes change our time by so much
809 if (abs64(nMedian) < 70 * 60)
811 nTimeOffset = nMedian;
816 // If nobody else has the same time as us, give a warning
818 foreach(int64 nOffset, vTimeOffsets)
819 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
822 if (!fMatch && !fDone)
825 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
826 strMiscWarning = strMessage;
827 printf("*** %s\n", strMessage.c_str());
828 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
831 foreach(int64 n, vTimeOffsets)
832 printf("%+"PRI64d" ", n);
833 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);