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.
9 map<string, string> mapArgs;
10 map<string, vector<string> > mapMultiArgs;
12 bool fPrintToConsole = false;
13 bool fPrintToDebugger = false;
14 char pszSetDataDir[MAX_PATH] = "";
15 bool fRequestShutdown = false;
16 bool fShutdown = false;
19 bool fCommandLine = false;
20 string strMiscWarning;
21 bool fTestNet = false;
22 bool fNoListen = false;
23 bool fLogTimestamps = false;
28 // Workaround for "multiple definition of `_tls_used'"
29 // http://svn.boost.org/trac/boost/ticket/4258
30 extern "C" void tss_cleanup_implemented() { }
36 // Init openssl library multithreading support
37 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
38 void locking_callback(int mode, int i, const char* file, int line)
40 if (mode & CRYPTO_LOCK)
41 ppmutexOpenSSL[i]->lock();
43 ppmutexOpenSSL[i]->unlock();
52 // Init openssl library multithreading support
53 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
54 for (int i = 0; i < CRYPTO_num_locks(); i++)
55 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
56 CRYPTO_set_locking_callback(locking_callback);
59 // Seed random number generator with screen scrape and other hardware sources
63 // Seed random number generator with performance counter
68 // Shutdown openssl library multithreading support
69 CRYPTO_set_locking_callback(NULL);
70 for (int i = 0; i < CRYPTO_num_locks(); i++)
71 delete ppmutexOpenSSL[i];
72 OPENSSL_free(ppmutexOpenSSL);
86 // Seed with CPU performance counter
87 int64 nCounter = GetPerformanceCounter();
88 RAND_add(&nCounter, sizeof(nCounter), 1.5);
89 memset(&nCounter, 0, sizeof(nCounter));
92 void RandAddSeedPerfmon()
96 // This can take up to 2 seconds, so only do it every 10 minutes
97 static int64 nLastPerfmon;
98 if (GetTime() < nLastPerfmon + 10 * 60)
100 nLastPerfmon = GetTime();
103 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
104 // Seed with the entire set of perfmon data
105 unsigned char pdata[250000];
106 memset(pdata, 0, sizeof(pdata));
107 unsigned long nSize = sizeof(pdata);
108 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
109 RegCloseKey(HKEY_PERFORMANCE_DATA);
110 if (ret == ERROR_SUCCESS)
112 RAND_add(pdata, nSize, nSize/100.0);
113 memset(pdata, 0, nSize);
114 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
119 uint64 GetRand(uint64 nMax)
124 // The range of the random source must be a multiple of the modulus
125 // to give every possible output value an equal possibility
126 uint64 nRange = (UINT64_MAX / nMax) * nMax;
129 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
130 while (nRand >= nRange);
131 return (nRand % nMax);
134 int GetRandInt(int nMax)
136 return GetRand(nMax);
149 inline int OutputDebugStringF(const char* pszFormat, ...)
156 va_start(arg_ptr, pszFormat);
157 ret = vprintf(pszFormat, arg_ptr);
162 // print to debug.log
163 static FILE* fileout = NULL;
167 char pszFile[MAX_PATH+100];
169 strlcat(pszFile, "/debug.log", sizeof(pszFile));
170 fileout = fopen(pszFile, "a");
171 if (fileout) setbuf(fileout, NULL); // unbuffered
175 static bool fStartedNewLine = true;
177 // Debug print useful for profiling
178 if (fLogTimestamps && fStartedNewLine)
179 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
180 if (pszFormat[strlen(pszFormat) - 1] == '\n')
181 fStartedNewLine = true;
183 fStartedNewLine = false;
186 va_start(arg_ptr, pszFormat);
187 ret = vfprintf(fileout, pszFormat, arg_ptr);
193 if (fPrintToDebugger)
195 static CCriticalSection cs_OutputDebugStringF;
197 // accumulate a line at a time
198 CRITICAL_BLOCK(cs_OutputDebugStringF)
200 static char pszBuffer[50000];
205 va_start(arg_ptr, pszFormat);
206 int limit = END(pszBuffer) - pend - 2;
207 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
209 if (ret < 0 || ret >= limit)
211 pend = END(pszBuffer) - 2;
217 char* p1 = pszBuffer;
219 while (p2 = strchr(p1, '\n'))
224 OutputDebugStringA(p1);
229 memmove(pszBuffer, p1, pend - p1 + 1);
230 pend -= (p1 - pszBuffer);
239 // - prints up to limit-1 characters
240 // - output string is always null terminated even if limit reached
241 // - return value is the number of characters actually printed
242 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
247 va_start(arg_ptr, format);
248 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
250 if (ret < 0 || ret >= limit)
259 string strprintf(const char* format, ...)
263 int limit = sizeof(buffer);
268 va_start(arg_ptr, format);
269 ret = _vsnprintf(p, limit, format, arg_ptr);
271 if (ret >= 0 && ret < limit)
278 throw std::bad_alloc();
280 string str(p, p+ret);
287 bool error(const char* format, ...)
290 int limit = sizeof(buffer);
292 va_start(arg_ptr, format);
293 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
295 if (ret < 0 || ret >= limit)
300 printf("ERROR: %s\n", buffer);
305 void ParseString(const string& str, char c, vector<string>& v)
309 string::size_type i1 = 0;
310 string::size_type i2;
313 i2 = str.find(c, i1);
316 v.push_back(str.substr(i1));
319 v.push_back(str.substr(i1, i2-i1));
325 string FormatMoney(int64 n, bool fPlus)
327 // Note: not using straight sprintf here because we do NOT want
328 // localized number formatting.
329 int64 n_abs = (n > 0 ? n : -n);
330 int64 quotient = n_abs/COIN;
331 int64 remainder = n_abs%COIN;
332 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
334 // Right-trim excess 0's before the decimal point:
336 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
339 str.erase(str.size()-nTrim, nTrim);
341 // Insert thousands-separators:
342 size_t point = str.find(".");
343 for (int i = (str.size()-point)+3; i < str.size(); i += 4)
344 if (isdigit(str[str.size() - i - 1]))
345 str.insert(str.size() - i, 1, ',');
347 str.insert((unsigned int)0, 1, '-');
348 else if (fPlus && n > 0)
349 str.insert((unsigned int)0, 1, '+');
354 bool ParseMoney(const string& str, int64& nRet)
356 return ParseMoney(str.c_str(), nRet);
359 bool ParseMoney(const char* pszIn, int64& nRet)
363 const char* p = pszIn;
368 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
373 int64 nMult = CENT*10;
374 while (isdigit(*p) && (nMult > 0))
376 nUnits += nMult * (*p++ - '0');
385 strWhole.insert(strWhole.end(), *p);
390 if (strWhole.size() > 14)
392 if (nUnits < 0 || nUnits > COIN)
394 int64 nWhole = atoi64(strWhole);
395 int64 nValue = nWhole*COIN + nUnits;
402 vector<unsigned char> ParseHex(const char* psz)
404 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
409 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
412 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
413 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
414 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
415 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
416 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
417 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
418 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
419 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
420 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
422 // convert hex dump to vector
423 vector<unsigned char> vch;
426 while (isspace(*psz))
428 char c = phexdigit[(unsigned char)*psz++];
431 unsigned char n = (c << 4);
432 c = phexdigit[(unsigned char)*psz++];
441 vector<unsigned char> ParseHex(const string& str)
443 return ParseHex(str.c_str());
447 void ParseParameters(int argc, char* argv[])
450 mapMultiArgs.clear();
451 for (int i = 1; i < argc; i++)
454 strlcpy(psz, argv[i], sizeof(psz));
455 char* pszValue = (char*)"";
456 if (strchr(psz, '='))
458 pszValue = strchr(psz, '=');
468 mapArgs[psz] = pszValue;
469 mapMultiArgs[psz].push_back(pszValue);
474 const char* wxGetTranslation(const char* pszEnglish)
477 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
478 static CCriticalSection cs;
482 static map<string, char*> mapCache;
483 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
484 if (mi != mapCache.end())
487 // wxWidgets translation
488 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
490 // We don't cache unknown strings because caller might be passing in a
491 // dynamic string and we would keep allocating memory for each variation.
492 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
495 // Add to cache, memory doesn't need to be freed. We only cache because
496 // we must pass back a pointer to permanently allocated memory.
497 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
498 strcpy(pszCached, strTranslated.utf8_str());
499 mapCache[pszEnglish] = pszCached;
509 bool WildcardMatch(const char* psz, const char* mask)
516 return (*psz == '\0');
518 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
533 bool WildcardMatch(const string& str, const string& mask)
535 return WildcardMatch(str.c_str(), mask.c_str());
545 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
548 char pszModule[MAX_PATH];
550 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
552 const char* pszModule = "bitcoin";
555 snprintf(pszMessage, 1000,
556 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
558 snprintf(pszMessage, 1000,
559 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
562 void LogException(std::exception* pex, const char* pszThread)
564 char pszMessage[10000];
565 FormatException(pszMessage, pex, pszThread);
566 printf("\n%s", pszMessage);
569 void PrintException(std::exception* pex, const char* pszThread)
571 char pszMessage[10000];
572 FormatException(pszMessage, pex, pszThread);
573 printf("\n\n************************\n%s\n", pszMessage);
574 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
575 strMiscWarning = pszMessage;
577 if (wxTheApp && !fDaemon)
578 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
583 void ThreadOneMessageBox(string strMessage)
585 // Skip message boxes if one is already open
586 static bool fMessageBoxOpen;
589 fMessageBoxOpen = true;
590 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
591 fMessageBoxOpen = false;
594 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
596 char pszMessage[10000];
597 FormatException(pszMessage, pex, pszThread);
598 printf("\n\n************************\n%s\n", pszMessage);
599 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
600 strMiscWarning = pszMessage;
602 if (wxTheApp && !fDaemon)
603 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
615 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
617 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
619 char pszPath[MAX_PATH+100] = "";
621 // SHGetSpecialFolderPath isn't always available on old Windows versions
622 HMODULE hShell32 = LoadLibraryA("shell32.dll");
625 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
626 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
627 if (pSHGetSpecialFolderPath)
628 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
629 FreeModule(hShell32);
633 if (pszPath[0] == '\0')
635 if (nFolder == CSIDL_STARTUP)
637 strcpy(pszPath, getenv("USERPROFILE"));
638 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
640 else if (nFolder == CSIDL_APPDATA)
642 strcpy(pszPath, getenv("APPDATA"));
650 string GetDefaultDataDir()
652 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
653 // Mac: ~/Library/Application Support/Bitcoin
657 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
659 char* pszHome = getenv("HOME");
660 if (pszHome == NULL || strlen(pszHome) == 0)
661 pszHome = (char*)"/";
662 string strHome = pszHome;
663 if (strHome[strHome.size()-1] != '/')
667 strHome += "Library/Application Support/";
668 filesystem::create_directory(strHome.c_str());
669 return strHome + "Bitcoin";
672 return strHome + ".bitcoin";
677 void GetDataDir(char* pszDir)
679 // pszDir must be at least MAX_PATH length.
681 if (pszSetDataDir[0] != 0)
683 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
688 // This can be called during exceptions by printf, so we cache the
689 // value so we don't have to do memory allocations after that.
690 static char pszCachedDir[MAX_PATH];
691 if (pszCachedDir[0] == 0)
692 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
693 strlcpy(pszDir, pszCachedDir, MAX_PATH);
698 char* p = pszDir + strlen(pszDir);
699 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
701 strcpy(p, "testnet");
704 static bool pfMkdir[4];
705 if (!pfMkdir[nVariation])
707 pfMkdir[nVariation] = true;
708 boost::filesystem::create_directory(pszDir);
714 char pszDir[MAX_PATH];
719 string GetConfigFile()
721 namespace fs = boost::filesystem;
722 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
723 if (!pathConfig.is_complete())
724 pathConfig = fs::path(GetDataDir()) / pathConfig;
725 return pathConfig.string();
728 void ReadConfigFile(map<string, string>& mapSettingsRet,
729 map<string, vector<string> >& mapMultiSettingsRet)
731 namespace fs = boost::filesystem;
732 namespace pod = boost::program_options::detail;
734 fs::ifstream streamConfig(GetConfigFile());
735 if (!streamConfig.good())
738 set<string> setOptions;
739 setOptions.insert("*");
741 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
743 // Don't overwrite existing settings so command line settings override bitcoin.conf
744 string strKey = string("-") + it->string_key;
745 if (mapSettingsRet.count(strKey) == 0)
746 mapSettingsRet[strKey] = it->value[0];
747 mapMultiSettingsRet[strKey].push_back(it->value[0]);
753 namespace fs = boost::filesystem;
754 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
755 if (!pathConfig.is_complete())
756 pathConfig = fs::path(GetDataDir()) / pathConfig;
757 return pathConfig.string();
760 void CreatePidFile(string pidFile, pid_t pid)
763 if (file = fopen(pidFile.c_str(), "w"))
765 fprintf(file, "%d\n", pid);
770 int GetFilesize(FILE* file)
772 int nSavePos = ftell(file);
774 if (fseek(file, 0, SEEK_END) == 0)
775 nFilesize = ftell(file);
776 fseek(file, nSavePos, SEEK_SET);
780 void ShrinkDebugFile()
782 // Scroll debug.log if it's getting too big
783 string strFile = GetDataDir() + "/debug.log";
784 FILE* file = fopen(strFile.c_str(), "r");
785 if (file && GetFilesize(file) > 10 * 1000000)
787 // Restart the file with some of the end
789 fseek(file, -sizeof(pch), SEEK_END);
790 int nBytes = fread(pch, 1, sizeof(pch), file);
792 if (file = fopen(strFile.c_str(), "w"))
794 fwrite(pch, 1, nBytes, file);
808 // "Never go to sea with two chronometers; take one or three."
809 // Our three time sources are:
811 // - Median of other nodes's clocks
812 // - The user (asking the user to fix the system clock if the first two disagree)
819 static int64 nTimeOffset = 0;
821 int64 GetAdjustedTime()
823 return GetTime() + nTimeOffset;
826 void AddTimeData(unsigned int ip, int64 nTime)
828 int64 nOffsetSample = nTime - GetTime();
831 static set<unsigned int> setKnown;
832 if (!setKnown.insert(ip).second)
836 static vector<int64> vTimeOffsets;
837 if (vTimeOffsets.empty())
838 vTimeOffsets.push_back(0);
839 vTimeOffsets.push_back(nOffsetSample);
840 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
841 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
843 sort(vTimeOffsets.begin(), vTimeOffsets.end());
844 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
845 // Only let other nodes change our time by so much
846 if (abs64(nMedian) < 70 * 60)
848 nTimeOffset = nMedian;
857 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
859 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
860 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
866 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
867 strMiscWarning = strMessage;
868 printf("*** %s\n", strMessage.c_str());
869 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
873 BOOST_FOREACH(int64 n, vTimeOffsets)
874 printf("%+"PRI64d" ", n);
875 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
887 string FormatVersion(int nVersion)
889 if (nVersion%100 == 0)
890 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
892 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
895 string FormatFullVersion()
897 string s = FormatVersion(VERSION) + pszSubVer;
899 s += "-" + _("beta");