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.
10 map<string, string> mapArgs;
11 map<string, vector<string> > mapMultiArgs;
13 bool fPrintToConsole = false;
14 bool fPrintToDebugger = false;
15 char pszSetDataDir[MAX_PATH] = "";
16 bool fRequestShutdown = false;
17 bool fShutdown = false;
20 bool fCommandLine = false;
21 string strMiscWarning;
22 bool fTestNet = false;
23 bool fNoListen = false;
24 bool fLogTimestamps = false;
29 // Workaround for "multiple definition of `_tls_used'"
30 // http://svn.boost.org/trac/boost/ticket/4258
31 extern "C" void tss_cleanup_implemented() { }
37 // Init openssl library multithreading support
38 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
39 void locking_callback(int mode, int i, const char* file, int line)
41 if (mode & CRYPTO_LOCK)
42 ppmutexOpenSSL[i]->lock();
44 ppmutexOpenSSL[i]->unlock();
53 // Init openssl library multithreading support
54 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
55 for (int i = 0; i < CRYPTO_num_locks(); i++)
56 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
57 CRYPTO_set_locking_callback(locking_callback);
60 // Seed random number generator with screen scrape and other hardware sources
64 // Seed random number generator with performance counter
69 // Shutdown openssl library multithreading support
70 CRYPTO_set_locking_callback(NULL);
71 for (int i = 0; i < CRYPTO_num_locks(); i++)
72 delete ppmutexOpenSSL[i];
73 OPENSSL_free(ppmutexOpenSSL);
87 // Seed with CPU performance counter
88 int64 nCounter = GetPerformanceCounter();
89 RAND_add(&nCounter, sizeof(nCounter), 1.5);
90 memset(&nCounter, 0, sizeof(nCounter));
93 void RandAddSeedPerfmon()
97 // This can take up to 2 seconds, so only do it every 10 minutes
98 static int64 nLastPerfmon;
99 if (GetTime() < nLastPerfmon + 10 * 60)
101 nLastPerfmon = GetTime();
104 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
105 // Seed with the entire set of perfmon data
106 unsigned char pdata[250000];
107 memset(pdata, 0, sizeof(pdata));
108 unsigned long nSize = sizeof(pdata);
109 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
110 RegCloseKey(HKEY_PERFORMANCE_DATA);
111 if (ret == ERROR_SUCCESS)
113 RAND_add(pdata, nSize, nSize/100.0);
114 memset(pdata, 0, nSize);
115 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
120 uint64 GetRand(uint64 nMax)
125 // The range of the random source must be a multiple of the modulus
126 // to give every possible output value an equal possibility
127 uint64 nRange = (UINT64_MAX / nMax) * nMax;
130 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
131 while (nRand >= nRange);
132 return (nRand % nMax);
135 int GetRandInt(int nMax)
137 return GetRand(nMax);
150 inline int OutputDebugStringF(const char* pszFormat, ...)
157 va_start(arg_ptr, pszFormat);
158 ret = vprintf(pszFormat, arg_ptr);
163 // print to debug.log
164 static FILE* fileout = NULL;
168 char pszFile[MAX_PATH+100];
170 strlcat(pszFile, "/debug.log", sizeof(pszFile));
171 fileout = fopen(pszFile, "a");
172 if (fileout) setbuf(fileout, NULL); // unbuffered
176 static bool fStartedNewLine = true;
178 // Debug print useful for profiling
179 if (fLogTimestamps && fStartedNewLine)
180 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
181 if (pszFormat[strlen(pszFormat) - 1] == '\n')
182 fStartedNewLine = true;
184 fStartedNewLine = false;
187 va_start(arg_ptr, pszFormat);
188 ret = vfprintf(fileout, pszFormat, arg_ptr);
194 if (fPrintToDebugger)
196 static CCriticalSection cs_OutputDebugStringF;
198 // accumulate a line at a time
199 CRITICAL_BLOCK(cs_OutputDebugStringF)
201 static char pszBuffer[50000];
206 va_start(arg_ptr, pszFormat);
207 int limit = END(pszBuffer) - pend - 2;
208 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
210 if (ret < 0 || ret >= limit)
212 pend = END(pszBuffer) - 2;
218 char* p1 = pszBuffer;
220 while (p2 = strchr(p1, '\n'))
225 OutputDebugStringA(p1);
230 memmove(pszBuffer, p1, pend - p1 + 1);
231 pend -= (p1 - pszBuffer);
240 // - prints up to limit-1 characters
241 // - output string is always null terminated even if limit reached
242 // - return value is the number of characters actually printed
243 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
248 va_start(arg_ptr, format);
249 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
251 if (ret < 0 || ret >= limit)
260 string strprintf(const char* format, ...)
264 int limit = sizeof(buffer);
269 va_start(arg_ptr, format);
270 ret = _vsnprintf(p, limit, format, arg_ptr);
272 if (ret >= 0 && ret < limit)
279 throw std::bad_alloc();
281 string str(p, p+ret);
288 bool error(const char* format, ...)
291 int limit = sizeof(buffer);
293 va_start(arg_ptr, format);
294 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
296 if (ret < 0 || ret >= limit)
301 printf("ERROR: %s\n", buffer);
306 void ParseString(const string& str, char c, vector<string>& v)
310 string::size_type i1 = 0;
311 string::size_type i2;
314 i2 = str.find(c, i1);
317 v.push_back(str.substr(i1));
320 v.push_back(str.substr(i1, i2-i1));
326 string FormatMoney(int64 n, bool fPlus)
328 // Note: not using straight sprintf here because we do NOT want
329 // localized number formatting.
330 int64 n_abs = (n > 0 ? n : -n);
331 int64 quotient = n_abs/COIN;
332 int64 remainder = n_abs%COIN;
333 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
335 // Right-trim excess 0's before the decimal point:
337 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
340 str.erase(str.size()-nTrim, nTrim);
342 // Insert thousands-separators:
343 size_t point = str.find(".");
344 for (int i = (str.size()-point)+3; i < str.size(); i += 4)
345 if (isdigit(str[str.size() - i - 1]))
346 str.insert(str.size() - i, 1, ',');
348 str.insert((unsigned int)0, 1, '-');
349 else if (fPlus && n > 0)
350 str.insert((unsigned int)0, 1, '+');
355 bool ParseMoney(const string& str, int64& nRet)
357 return ParseMoney(str.c_str(), nRet);
360 bool ParseMoney(const char* pszIn, int64& nRet)
364 const char* p = pszIn;
369 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
374 int64 nMult = CENT*10;
375 while (isdigit(*p) && (nMult > 0))
377 nUnits += nMult * (*p++ - '0');
386 strWhole.insert(strWhole.end(), *p);
391 if (strWhole.size() > 14)
393 if (nUnits < 0 || nUnits > COIN)
395 int64 nWhole = atoi64(strWhole);
396 int64 nValue = nWhole*COIN + nUnits;
403 vector<unsigned char> ParseHex(const char* psz)
405 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
410 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,
412 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,
421 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
423 // convert hex dump to vector
424 vector<unsigned char> vch;
427 while (isspace(*psz))
429 char c = phexdigit[(unsigned char)*psz++];
432 unsigned char n = (c << 4);
433 c = phexdigit[(unsigned char)*psz++];
442 vector<unsigned char> ParseHex(const string& str)
444 return ParseHex(str.c_str());
448 void ParseParameters(int argc, char* argv[])
451 mapMultiArgs.clear();
452 for (int i = 1; i < argc; i++)
455 strlcpy(psz, argv[i], sizeof(psz));
456 char* pszValue = (char*)"";
457 if (strchr(psz, '='))
459 pszValue = strchr(psz, '=');
469 mapArgs[psz] = pszValue;
470 mapMultiArgs[psz].push_back(pszValue);
475 const char* wxGetTranslation(const char* pszEnglish)
478 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
479 static CCriticalSection cs;
483 static map<string, char*> mapCache;
484 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
485 if (mi != mapCache.end())
488 // wxWidgets translation
489 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
491 // We don't cache unknown strings because caller might be passing in a
492 // dynamic string and we would keep allocating memory for each variation.
493 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
496 // Add to cache, memory doesn't need to be freed. We only cache because
497 // we must pass back a pointer to permanently allocated memory.
498 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
499 strcpy(pszCached, strTranslated.utf8_str());
500 mapCache[pszEnglish] = pszCached;
510 bool WildcardMatch(const char* psz, const char* mask)
517 return (*psz == '\0');
519 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
534 bool WildcardMatch(const string& str, const string& mask)
536 return WildcardMatch(str.c_str(), mask.c_str());
546 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
549 char pszModule[MAX_PATH];
551 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
553 const char* pszModule = "bitcoin";
556 snprintf(pszMessage, 1000,
557 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
559 snprintf(pszMessage, 1000,
560 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
563 void LogException(std::exception* pex, const char* pszThread)
565 char pszMessage[10000];
566 FormatException(pszMessage, pex, pszThread);
567 printf("\n%s", pszMessage);
570 void PrintException(std::exception* pex, const char* pszThread)
572 char pszMessage[10000];
573 FormatException(pszMessage, pex, pszThread);
574 printf("\n\n************************\n%s\n", pszMessage);
575 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
576 strMiscWarning = pszMessage;
578 if (wxTheApp && !fDaemon)
579 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
584 void ThreadOneMessageBox(string strMessage)
586 // Skip message boxes if one is already open
587 static bool fMessageBoxOpen;
590 fMessageBoxOpen = true;
591 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
592 fMessageBoxOpen = false;
595 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
597 char pszMessage[10000];
598 FormatException(pszMessage, pex, pszThread);
599 printf("\n\n************************\n%s\n", pszMessage);
600 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
601 strMiscWarning = pszMessage;
603 if (wxTheApp && !fDaemon)
604 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
616 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
618 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
620 char pszPath[MAX_PATH+100] = "";
622 // SHGetSpecialFolderPath isn't always available on old Windows versions
623 HMODULE hShell32 = LoadLibraryA("shell32.dll");
626 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
627 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
628 if (pSHGetSpecialFolderPath)
629 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
630 FreeModule(hShell32);
634 if (pszPath[0] == '\0')
636 if (nFolder == CSIDL_STARTUP)
638 strcpy(pszPath, getenv("USERPROFILE"));
639 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
641 else if (nFolder == CSIDL_APPDATA)
643 strcpy(pszPath, getenv("APPDATA"));
651 string GetDefaultDataDir()
653 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
654 // Mac: ~/Library/Application Support/Bitcoin
658 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
660 char* pszHome = getenv("HOME");
661 if (pszHome == NULL || strlen(pszHome) == 0)
662 pszHome = (char*)"/";
663 string strHome = pszHome;
664 if (strHome[strHome.size()-1] != '/')
668 strHome += "Library/Application Support/";
669 filesystem::create_directory(strHome.c_str());
670 return strHome + "Bitcoin";
673 return strHome + ".bitcoin";
678 void GetDataDir(char* pszDir)
680 // pszDir must be at least MAX_PATH length.
682 if (pszSetDataDir[0] != 0)
684 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
689 // This can be called during exceptions by printf, so we cache the
690 // value so we don't have to do memory allocations after that.
691 static char pszCachedDir[MAX_PATH];
692 if (pszCachedDir[0] == 0)
693 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
694 strlcpy(pszDir, pszCachedDir, MAX_PATH);
699 char* p = pszDir + strlen(pszDir);
700 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
702 strcpy(p, "testnet");
705 static bool pfMkdir[4];
706 if (!pfMkdir[nVariation])
708 pfMkdir[nVariation] = true;
709 boost::filesystem::create_directory(pszDir);
715 char pszDir[MAX_PATH];
720 string GetConfigFile()
722 namespace fs = boost::filesystem;
723 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
724 if (!pathConfig.is_complete())
725 pathConfig = fs::path(GetDataDir()) / pathConfig;
726 return pathConfig.string();
729 void ReadConfigFile(map<string, string>& mapSettingsRet,
730 map<string, vector<string> >& mapMultiSettingsRet)
732 namespace fs = boost::filesystem;
733 namespace pod = boost::program_options::detail;
735 fs::ifstream streamConfig(GetConfigFile());
736 if (!streamConfig.good())
739 set<string> setOptions;
740 setOptions.insert("*");
742 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
744 // Don't overwrite existing settings so command line settings override bitcoin.conf
745 string strKey = string("-") + it->string_key;
746 if (mapSettingsRet.count(strKey) == 0)
747 mapSettingsRet[strKey] = it->value[0];
748 mapMultiSettingsRet[strKey].push_back(it->value[0]);
754 namespace fs = boost::filesystem;
755 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
756 if (!pathConfig.is_complete())
757 pathConfig = fs::path(GetDataDir()) / pathConfig;
758 return pathConfig.string();
761 void CreatePidFile(string pidFile, pid_t pid)
764 if (file = fopen(pidFile.c_str(), "w"))
766 fprintf(file, "%d\n", pid);
771 int GetFilesize(FILE* file)
773 int nSavePos = ftell(file);
775 if (fseek(file, 0, SEEK_END) == 0)
776 nFilesize = ftell(file);
777 fseek(file, nSavePos, SEEK_SET);
781 void ShrinkDebugFile()
783 // Scroll debug.log if it's getting too big
784 string strFile = GetDataDir() + "/debug.log";
785 FILE* file = fopen(strFile.c_str(), "r");
786 if (file && GetFilesize(file) > 10 * 1000000)
788 // Restart the file with some of the end
790 fseek(file, -sizeof(pch), SEEK_END);
791 int nBytes = fread(pch, 1, sizeof(pch), file);
793 if (file = fopen(strFile.c_str(), "w"))
795 fwrite(pch, 1, nBytes, file);
809 // "Never go to sea with two chronometers; take one or three."
810 // Our three time sources are:
812 // - Median of other nodes's clocks
813 // - The user (asking the user to fix the system clock if the first two disagree)
820 static int64 nTimeOffset = 0;
822 int64 GetAdjustedTime()
824 return GetTime() + nTimeOffset;
827 void AddTimeData(unsigned int ip, int64 nTime)
829 int64 nOffsetSample = nTime - GetTime();
832 static set<unsigned int> setKnown;
833 if (!setKnown.insert(ip).second)
837 static vector<int64> vTimeOffsets;
838 if (vTimeOffsets.empty())
839 vTimeOffsets.push_back(0);
840 vTimeOffsets.push_back(nOffsetSample);
841 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
842 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
844 sort(vTimeOffsets.begin(), vTimeOffsets.end());
845 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
846 // Only let other nodes change our time by so much
847 if (abs64(nMedian) < 70 * 60)
849 nTimeOffset = nMedian;
858 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
860 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
861 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
867 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
868 strMiscWarning = strMessage;
869 printf("*** %s\n", strMessage.c_str());
870 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
874 BOOST_FOREACH(int64 n, vTimeOffsets)
875 printf("%+"PRI64d" ", n);
876 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
888 string FormatVersion(int nVersion)
890 if (nVersion%100 == 0)
891 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
893 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
896 string FormatFullVersion()
898 string s = FormatVersion(VERSION) + pszSubVer;