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;
18 bool fCommandLine = false;
19 string strMiscWarning;
20 bool fTestNet = false;
21 bool fNoListen = false;
26 // Workaround for "multiple definition of `_tls_used'"
27 // http://svn.boost.org/trac/boost/ticket/4258
28 extern "C" void tss_cleanup_implemented() { }
34 // Init openssl library multithreading support
35 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
36 void locking_callback(int mode, int i, const char* file, int line)
38 if (mode & CRYPTO_LOCK)
39 ppmutexOpenSSL[i]->lock();
41 ppmutexOpenSSL[i]->unlock();
50 // Init openssl library multithreading support
51 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
52 for (int i = 0; i < CRYPTO_num_locks(); i++)
53 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
54 CRYPTO_set_locking_callback(locking_callback);
57 // Seed random number generator with screen scrape and other hardware sources
61 // Seed random number generator with performance counter
66 // Shutdown openssl library multithreading support
67 CRYPTO_set_locking_callback(NULL);
68 for (int i = 0; i < CRYPTO_num_locks(); i++)
69 delete ppmutexOpenSSL[i];
70 OPENSSL_free(ppmutexOpenSSL);
84 // Seed with CPU performance counter
85 int64 nCounter = GetPerformanceCounter();
86 RAND_add(&nCounter, sizeof(nCounter), 1.5);
87 memset(&nCounter, 0, sizeof(nCounter));
90 void RandAddSeedPerfmon()
94 // This can take up to 2 seconds, so only do it every 10 minutes
95 static int64 nLastPerfmon;
96 if (GetTime() < nLastPerfmon + 10 * 60)
98 nLastPerfmon = GetTime();
101 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
102 // Seed with the entire set of perfmon data
103 unsigned char pdata[250000];
104 memset(pdata, 0, sizeof(pdata));
105 unsigned long nSize = sizeof(pdata);
106 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
107 RegCloseKey(HKEY_PERFORMANCE_DATA);
108 if (ret == ERROR_SUCCESS)
110 RAND_add(pdata, nSize, nSize/100.0);
111 memset(pdata, 0, nSize);
112 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
117 uint64 GetRand(uint64 nMax)
122 // The range of the random source must be a multiple of the modulus
123 // to give every possible output value an equal possibility
124 uint64 nRange = (UINT64_MAX / nMax) * nMax;
127 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
128 while (nRand >= nRange);
129 return (nRand % nMax);
132 int GetRandInt(int nMax)
134 return GetRand(nMax);
147 inline int OutputDebugStringF(const char* pszFormat, ...)
154 va_start(arg_ptr, pszFormat);
155 ret = vprintf(pszFormat, arg_ptr);
160 // print to debug.log
161 static FILE* fileout = NULL;
165 char pszFile[MAX_PATH+100];
167 strlcat(pszFile, "/debug.log", sizeof(pszFile));
168 fileout = fopen(pszFile, "a");
169 if (fileout) setbuf(fileout, NULL); // unbuffered
173 // Debug print useful for profiling
174 if (GetBoolArg("-logtimestamps"))
175 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
177 va_start(arg_ptr, pszFormat);
178 ret = vfprintf(fileout, pszFormat, arg_ptr);
184 if (fPrintToDebugger)
186 static CCriticalSection cs_OutputDebugStringF;
188 // accumulate a line at a time
189 CRITICAL_BLOCK(cs_OutputDebugStringF)
191 static char pszBuffer[50000];
196 va_start(arg_ptr, pszFormat);
197 int limit = END(pszBuffer) - pend - 2;
198 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
200 if (ret < 0 || ret >= limit)
202 pend = END(pszBuffer) - 2;
208 char* p1 = pszBuffer;
210 while (p2 = strchr(p1, '\n'))
215 OutputDebugStringA(p1);
220 memmove(pszBuffer, p1, pend - p1 + 1);
221 pend -= (p1 - pszBuffer);
230 // - prints up to limit-1 characters
231 // - output string is always null terminated even if limit reached
232 // - return value is the number of characters actually printed
233 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
238 va_start(arg_ptr, format);
239 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
241 if (ret < 0 || ret >= limit)
250 string strprintf(const char* format, ...)
254 int limit = sizeof(buffer);
259 va_start(arg_ptr, format);
260 ret = _vsnprintf(p, limit, format, arg_ptr);
262 if (ret >= 0 && ret < limit)
269 throw std::bad_alloc();
271 string str(p, p+ret);
278 bool error(const char* format, ...)
281 int limit = sizeof(buffer);
283 va_start(arg_ptr, format);
284 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
286 if (ret < 0 || ret >= limit)
291 printf("ERROR: %s\n", buffer);
296 void ParseString(const string& str, char c, vector<string>& v)
300 string::size_type i1 = 0;
301 string::size_type i2;
304 i2 = str.find(c, i1);
307 v.push_back(str.substr(i1));
310 v.push_back(str.substr(i1, i2-i1));
316 string FormatMoney(int64 n, bool fPlus)
318 // Note: not using straight sprintf here because we do NOT want
319 // localized number formatting.
320 int64 n_abs = (n > 0 ? n : -n);
321 int64 quotient = n_abs/COIN;
322 int64 remainder = n_abs%COIN;
323 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
325 // Right-trim excess 0's before the decimal point:
327 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
330 str.erase(str.size()-nTrim, nTrim);
332 // Insert thousands-separators:
333 size_t point = str.find(".");
334 for (int i = (str.size()-point)+3; i < str.size(); i += 4)
335 if (isdigit(str[str.size() - i - 1]))
336 str.insert(str.size() - i, 1, ',');
338 str.insert((unsigned int)0, 1, '-');
339 else if (fPlus && n > 0)
340 str.insert((unsigned int)0, 1, '+');
345 bool ParseMoney(const string& str, int64& nRet)
347 return ParseMoney(str.c_str(), nRet);
350 bool ParseMoney(const char* pszIn, int64& nRet)
354 const char* p = pszIn;
359 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
364 int64 nMult = CENT*10;
365 while (isdigit(*p) && (nMult > 0))
367 nUnits += nMult * (*p++ - '0');
376 strWhole.insert(strWhole.end(), *p);
381 if (strWhole.size() > 14)
383 if (nUnits < 0 || nUnits > COIN)
385 int64 nWhole = atoi64(strWhole);
386 int64 nValue = nWhole*COIN + nUnits;
393 vector<unsigned char> ParseHex(const char* psz)
395 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
400 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
403 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
404 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
405 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
406 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
407 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
408 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
409 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
410 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
413 // convert hex dump to vector
414 vector<unsigned char> vch;
417 while (isspace(*psz))
419 char c = phexdigit[(unsigned char)*psz++];
422 unsigned char n = (c << 4);
423 c = phexdigit[(unsigned char)*psz++];
432 vector<unsigned char> ParseHex(const string& str)
434 return ParseHex(str.c_str());
438 void ParseParameters(int argc, char* argv[])
441 mapMultiArgs.clear();
442 for (int i = 1; i < argc; i++)
445 strlcpy(psz, argv[i], sizeof(psz));
446 char* pszValue = (char*)"";
447 if (strchr(psz, '='))
449 pszValue = strchr(psz, '=');
459 mapArgs[psz] = pszValue;
460 mapMultiArgs[psz].push_back(pszValue);
465 const char* wxGetTranslation(const char* pszEnglish)
468 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
469 static CCriticalSection cs;
473 static map<string, char*> mapCache;
474 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
475 if (mi != mapCache.end())
478 // wxWidgets translation
479 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
481 // We don't cache unknown strings because caller might be passing in a
482 // dynamic string and we would keep allocating memory for each variation.
483 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
486 // Add to cache, memory doesn't need to be freed. We only cache because
487 // we must pass back a pointer to permanently allocated memory.
488 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
489 strcpy(pszCached, strTranslated.utf8_str());
490 mapCache[pszEnglish] = pszCached;
500 bool WildcardMatch(const char* psz, const char* mask)
507 return (*psz == '\0');
509 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
524 bool WildcardMatch(const string& str, const string& mask)
526 return WildcardMatch(str.c_str(), mask.c_str());
536 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
539 char pszModule[MAX_PATH];
541 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
543 const char* pszModule = "bitcoin";
546 snprintf(pszMessage, 1000,
547 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
549 snprintf(pszMessage, 1000,
550 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
553 void LogException(std::exception* pex, const char* pszThread)
555 char pszMessage[10000];
556 FormatException(pszMessage, pex, pszThread);
557 printf("\n%s", pszMessage);
560 void PrintException(std::exception* pex, const char* pszThread)
562 char pszMessage[10000];
563 FormatException(pszMessage, pex, pszThread);
564 printf("\n\n************************\n%s\n", pszMessage);
565 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
566 strMiscWarning = pszMessage;
568 if (wxTheApp && !fDaemon)
569 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
574 void ThreadOneMessageBox(string strMessage)
576 // Skip message boxes if one is already open
577 static bool fMessageBoxOpen;
580 fMessageBoxOpen = true;
581 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
582 fMessageBoxOpen = false;
585 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
587 char pszMessage[10000];
588 FormatException(pszMessage, pex, pszThread);
589 printf("\n\n************************\n%s\n", pszMessage);
590 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
591 strMiscWarning = pszMessage;
593 if (wxTheApp && !fDaemon)
594 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
606 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
608 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
610 char pszPath[MAX_PATH+100] = "";
612 // SHGetSpecialFolderPath isn't always available on old Windows versions
613 HMODULE hShell32 = LoadLibraryA("shell32.dll");
616 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
617 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
618 if (pSHGetSpecialFolderPath)
619 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
620 FreeModule(hShell32);
624 if (pszPath[0] == '\0')
626 if (nFolder == CSIDL_STARTUP)
628 strcpy(pszPath, getenv("USERPROFILE"));
629 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
631 else if (nFolder == CSIDL_APPDATA)
633 strcpy(pszPath, getenv("APPDATA"));
641 string GetDefaultDataDir()
643 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
644 // Mac: ~/Library/Application Support/Bitcoin
648 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
650 char* pszHome = getenv("HOME");
651 if (pszHome == NULL || strlen(pszHome) == 0)
652 pszHome = (char*)"/";
653 string strHome = pszHome;
654 if (strHome[strHome.size()-1] != '/')
658 strHome += "Library/Application Support/";
659 filesystem::create_directory(strHome.c_str());
660 return strHome + "Bitcoin";
663 return strHome + ".bitcoin";
668 void GetDataDir(char* pszDir)
670 // pszDir must be at least MAX_PATH length.
672 if (pszSetDataDir[0] != 0)
674 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
679 // This can be called during exceptions by printf, so we cache the
680 // value so we don't have to do memory allocations after that.
681 static char pszCachedDir[MAX_PATH];
682 if (pszCachedDir[0] == 0)
683 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
684 strlcpy(pszDir, pszCachedDir, MAX_PATH);
689 char* p = pszDir + strlen(pszDir);
690 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
692 strcpy(p, "testnet");
695 static bool pfMkdir[4];
696 if (!pfMkdir[nVariation])
698 pfMkdir[nVariation] = true;
699 filesystem::create_directory(pszDir);
705 char pszDir[MAX_PATH];
710 string GetConfigFile()
712 namespace fs = boost::filesystem;
713 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
714 if (!pathConfig.is_complete())
715 pathConfig = fs::path(GetDataDir()) / pathConfig;
716 return pathConfig.string();
719 void ReadConfigFile(map<string, string>& mapSettingsRet,
720 map<string, vector<string> >& mapMultiSettingsRet)
722 namespace fs = boost::filesystem;
723 namespace pod = boost::program_options::detail;
725 fs::ifstream streamConfig(GetConfigFile());
726 if (!streamConfig.good())
729 set<string> setOptions;
730 setOptions.insert("*");
732 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
734 // Don't overwrite existing settings so command line settings override bitcoin.conf
735 string strKey = string("-") + it->string_key;
736 if (mapSettingsRet.count(strKey) == 0)
737 mapSettingsRet[strKey] = it->value[0];
738 mapMultiSettingsRet[strKey].push_back(it->value[0]);
742 int GetFilesize(FILE* file)
744 int nSavePos = ftell(file);
746 if (fseek(file, 0, SEEK_END) == 0)
747 nFilesize = ftell(file);
748 fseek(file, nSavePos, SEEK_SET);
752 void ShrinkDebugFile()
754 // Scroll debug.log if it's getting too big
755 string strFile = GetDataDir() + "/debug.log";
756 FILE* file = fopen(strFile.c_str(), "r");
757 if (file && GetFilesize(file) > 10 * 1000000)
759 // Restart the file with some of the end
761 fseek(file, -sizeof(pch), SEEK_END);
762 int nBytes = fread(pch, 1, sizeof(pch), file);
764 if (file = fopen(strFile.c_str(), "w"))
766 fwrite(pch, 1, nBytes, file);
780 // "Never go to sea with two chronometers; take one or three."
781 // Our three time sources are:
783 // - Median of other nodes's clocks
784 // - The user (asking the user to fix the system clock if the first two disagree)
791 static int64 nTimeOffset = 0;
793 int64 GetAdjustedTime()
795 return GetTime() + nTimeOffset;
798 void AddTimeData(unsigned int ip, int64 nTime)
800 int64 nOffsetSample = nTime - GetTime();
803 static set<unsigned int> setKnown;
804 if (!setKnown.insert(ip).second)
808 static vector<int64> vTimeOffsets;
809 if (vTimeOffsets.empty())
810 vTimeOffsets.push_back(0);
811 vTimeOffsets.push_back(nOffsetSample);
812 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
813 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
815 sort(vTimeOffsets.begin(), vTimeOffsets.end());
816 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
817 // Only let other nodes change our time by so much
818 if (abs64(nMedian) < 70 * 60)
820 nTimeOffset = nMedian;
829 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
831 foreach(int64 nOffset, vTimeOffsets)
832 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
838 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
839 strMiscWarning = strMessage;
840 printf("*** %s\n", strMessage.c_str());
841 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
845 foreach(int64 n, vTimeOffsets)
846 printf("%+"PRI64d" ", n);
847 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);