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.
6 #include <boost/program_options/detail/config_file.hpp>
7 #include <boost/program_options/parsers.hpp>
8 #include <boost/filesystem/fstream.hpp>
9 #include <boost/interprocess/sync/interprocess_mutex.hpp>
10 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
11 #include <boost/foreach.hpp>
14 using namespace boost;
16 map<string, string> mapArgs;
17 map<string, vector<string> > mapMultiArgs;
19 bool fPrintToConsole = false;
20 bool fPrintToDebugger = false;
21 char pszSetDataDir[MAX_PATH] = "";
22 bool fRequestShutdown = false;
23 bool fShutdown = false;
26 bool fCommandLine = false;
27 string strMiscWarning;
28 bool fTestNet = false;
29 bool fNoListen = false;
30 bool fLogTimestamps = false;
35 // Workaround for "multiple definition of `_tls_used'"
36 // http://svn.boost.org/trac/boost/ticket/4258
37 extern "C" void tss_cleanup_implemented() { }
43 // Init openssl library multithreading support
44 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
45 void locking_callback(int mode, int i, const char* file, int line)
47 if (mode & CRYPTO_LOCK)
48 ppmutexOpenSSL[i]->lock();
50 ppmutexOpenSSL[i]->unlock();
59 // Init openssl library multithreading support
60 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
61 for (int i = 0; i < CRYPTO_num_locks(); i++)
62 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
63 CRYPTO_set_locking_callback(locking_callback);
66 // Seed random number generator with screen scrape and other hardware sources
70 // Seed random number generator with performance counter
75 // Shutdown openssl library multithreading support
76 CRYPTO_set_locking_callback(NULL);
77 for (int i = 0; i < CRYPTO_num_locks(); i++)
78 delete ppmutexOpenSSL[i];
79 OPENSSL_free(ppmutexOpenSSL);
93 // Seed with CPU performance counter
94 int64 nCounter = GetPerformanceCounter();
95 RAND_add(&nCounter, sizeof(nCounter), 1.5);
96 memset(&nCounter, 0, sizeof(nCounter));
99 void RandAddSeedPerfmon()
103 // This can take up to 2 seconds, so only do it every 10 minutes
104 static int64 nLastPerfmon;
105 if (GetTime() < nLastPerfmon + 10 * 60)
107 nLastPerfmon = GetTime();
110 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
111 // Seed with the entire set of perfmon data
112 unsigned char pdata[250000];
113 memset(pdata, 0, sizeof(pdata));
114 unsigned long nSize = sizeof(pdata);
115 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
116 RegCloseKey(HKEY_PERFORMANCE_DATA);
117 if (ret == ERROR_SUCCESS)
119 RAND_add(pdata, nSize, nSize/100.0);
120 memset(pdata, 0, nSize);
121 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
126 uint64 GetRand(uint64 nMax)
131 // The range of the random source must be a multiple of the modulus
132 // to give every possible output value an equal possibility
133 uint64 nRange = (UINT64_MAX / nMax) * nMax;
136 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
137 while (nRand >= nRange);
138 return (nRand % nMax);
141 int GetRandInt(int nMax)
143 return GetRand(nMax);
156 inline int OutputDebugStringF(const char* pszFormat, ...)
163 va_start(arg_ptr, pszFormat);
164 ret = vprintf(pszFormat, arg_ptr);
169 // print to debug.log
170 static FILE* fileout = NULL;
174 char pszFile[MAX_PATH+100];
176 strlcat(pszFile, "/debug.log", sizeof(pszFile));
177 fileout = fopen(pszFile, "a");
178 if (fileout) setbuf(fileout, NULL); // unbuffered
182 static bool fStartedNewLine = true;
184 // Debug print useful for profiling
185 if (fLogTimestamps && fStartedNewLine)
186 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
187 if (pszFormat[strlen(pszFormat) - 1] == '\n')
188 fStartedNewLine = true;
190 fStartedNewLine = false;
193 va_start(arg_ptr, pszFormat);
194 ret = vfprintf(fileout, pszFormat, arg_ptr);
200 if (fPrintToDebugger)
202 static CCriticalSection cs_OutputDebugStringF;
204 // accumulate a line at a time
205 CRITICAL_BLOCK(cs_OutputDebugStringF)
207 static char pszBuffer[50000];
212 va_start(arg_ptr, pszFormat);
213 int limit = END(pszBuffer) - pend - 2;
214 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
216 if (ret < 0 || ret >= limit)
218 pend = END(pszBuffer) - 2;
224 char* p1 = pszBuffer;
226 while (p2 = strchr(p1, '\n'))
231 OutputDebugStringA(p1);
236 memmove(pszBuffer, p1, pend - p1 + 1);
237 pend -= (p1 - pszBuffer);
246 // - prints up to limit-1 characters
247 // - output string is always null terminated even if limit reached
248 // - return value is the number of characters actually printed
249 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
254 va_start(arg_ptr, format);
255 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
257 if (ret < 0 || ret >= limit)
266 string strprintf(const char* format, ...)
270 int limit = sizeof(buffer);
275 va_start(arg_ptr, format);
276 ret = _vsnprintf(p, limit, format, arg_ptr);
278 if (ret >= 0 && ret < limit)
285 throw std::bad_alloc();
287 string str(p, p+ret);
294 bool error(const char* format, ...)
297 int limit = sizeof(buffer);
299 va_start(arg_ptr, format);
300 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
302 if (ret < 0 || ret >= limit)
307 printf("ERROR: %s\n", buffer);
312 void ParseString(const string& str, char c, vector<string>& v)
316 string::size_type i1 = 0;
317 string::size_type i2;
320 i2 = str.find(c, i1);
323 v.push_back(str.substr(i1));
326 v.push_back(str.substr(i1, i2-i1));
332 string FormatMoney(int64 n, bool fPlus)
334 // Note: not using straight sprintf here because we do NOT want
335 // localized number formatting.
336 int64 n_abs = (n > 0 ? n : -n);
337 int64 quotient = n_abs/COIN;
338 int64 remainder = n_abs%COIN;
339 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
341 // Right-trim excess 0's before the decimal point:
343 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
346 str.erase(str.size()-nTrim, nTrim);
348 // Insert thousands-separators:
349 size_t point = str.find(".");
350 for (int i = (str.size()-point)+3; i < str.size(); i += 4)
351 if (isdigit(str[str.size() - i - 1]))
352 str.insert(str.size() - i, 1, ',');
354 str.insert((unsigned int)0, 1, '-');
355 else if (fPlus && n > 0)
356 str.insert((unsigned int)0, 1, '+');
361 bool ParseMoney(const string& str, int64& nRet)
363 return ParseMoney(str.c_str(), nRet);
366 bool ParseMoney(const char* pszIn, int64& nRet)
370 const char* p = pszIn;
375 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
380 int64 nMult = CENT*10;
381 while (isdigit(*p) && (nMult > 0))
383 nUnits += nMult * (*p++ - '0');
392 strWhole.insert(strWhole.end(), *p);
397 if (strWhole.size() > 14)
399 if (nUnits < 0 || nUnits > COIN)
401 int64 nWhole = atoi64(strWhole);
402 int64 nValue = nWhole*COIN + nUnits;
409 vector<unsigned char> ParseHex(const char* psz)
411 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
416 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
422 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
423 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
424 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
425 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
426 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
427 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
429 // convert hex dump to vector
430 vector<unsigned char> vch;
433 while (isspace(*psz))
435 char c = phexdigit[(unsigned char)*psz++];
438 unsigned char n = (c << 4);
439 c = phexdigit[(unsigned char)*psz++];
448 vector<unsigned char> ParseHex(const string& str)
450 return ParseHex(str.c_str());
454 void ParseParameters(int argc, char* argv[])
457 mapMultiArgs.clear();
458 for (int i = 1; i < argc; i++)
461 strlcpy(psz, argv[i], sizeof(psz));
462 char* pszValue = (char*)"";
463 if (strchr(psz, '='))
465 pszValue = strchr(psz, '=');
475 mapArgs[psz] = pszValue;
476 mapMultiArgs[psz].push_back(pszValue);
481 const char* wxGetTranslation(const char* pszEnglish)
484 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
485 static CCriticalSection cs;
489 static map<string, char*> mapCache;
490 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
491 if (mi != mapCache.end())
494 // wxWidgets translation
495 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
497 // We don't cache unknown strings because caller might be passing in a
498 // dynamic string and we would keep allocating memory for each variation.
499 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
502 // Add to cache, memory doesn't need to be freed. We only cache because
503 // we must pass back a pointer to permanently allocated memory.
504 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
505 strcpy(pszCached, strTranslated.utf8_str());
506 mapCache[pszEnglish] = pszCached;
516 bool WildcardMatch(const char* psz, const char* mask)
523 return (*psz == '\0');
525 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
540 bool WildcardMatch(const string& str, const string& mask)
542 return WildcardMatch(str.c_str(), mask.c_str());
552 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
555 char pszModule[MAX_PATH];
557 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
559 const char* pszModule = "bitcoin";
562 snprintf(pszMessage, 1000,
563 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
565 snprintf(pszMessage, 1000,
566 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
569 void LogException(std::exception* pex, const char* pszThread)
571 char pszMessage[10000];
572 FormatException(pszMessage, pex, pszThread);
573 printf("\n%s", pszMessage);
576 void PrintException(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 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
590 void ThreadOneMessageBox(string strMessage)
592 // Skip message boxes if one is already open
593 static bool fMessageBoxOpen;
596 fMessageBoxOpen = true;
597 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
598 fMessageBoxOpen = false;
601 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
603 char pszMessage[10000];
604 FormatException(pszMessage, pex, pszThread);
605 printf("\n\n************************\n%s\n", pszMessage);
606 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
607 strMiscWarning = pszMessage;
609 if (wxTheApp && !fDaemon)
610 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
622 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
624 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
626 char pszPath[MAX_PATH+100] = "";
628 // SHGetSpecialFolderPath isn't always available on old Windows versions
629 HMODULE hShell32 = LoadLibraryA("shell32.dll");
632 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
633 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
634 if (pSHGetSpecialFolderPath)
635 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
636 FreeModule(hShell32);
640 if (pszPath[0] == '\0')
642 if (nFolder == CSIDL_STARTUP)
644 strcpy(pszPath, getenv("USERPROFILE"));
645 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
647 else if (nFolder == CSIDL_APPDATA)
649 strcpy(pszPath, getenv("APPDATA"));
657 string GetDefaultDataDir()
659 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
660 // Mac: ~/Library/Application Support/Bitcoin
664 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
666 char* pszHome = getenv("HOME");
667 if (pszHome == NULL || strlen(pszHome) == 0)
668 pszHome = (char*)"/";
669 string strHome = pszHome;
670 if (strHome[strHome.size()-1] != '/')
674 strHome += "Library/Application Support/";
675 filesystem::create_directory(strHome.c_str());
676 return strHome + "Bitcoin";
679 return strHome + ".bitcoin";
684 void GetDataDir(char* pszDir)
686 // pszDir must be at least MAX_PATH length.
688 if (pszSetDataDir[0] != 0)
690 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
695 // This can be called during exceptions by printf, so we cache the
696 // value so we don't have to do memory allocations after that.
697 static char pszCachedDir[MAX_PATH];
698 if (pszCachedDir[0] == 0)
699 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
700 strlcpy(pszDir, pszCachedDir, MAX_PATH);
705 char* p = pszDir + strlen(pszDir);
706 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
708 strcpy(p, "testnet");
711 static bool pfMkdir[4];
712 if (!pfMkdir[nVariation])
714 pfMkdir[nVariation] = true;
715 boost::filesystem::create_directory(pszDir);
721 char pszDir[MAX_PATH];
726 string GetConfigFile()
728 namespace fs = boost::filesystem;
729 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
730 if (!pathConfig.is_complete())
731 pathConfig = fs::path(GetDataDir()) / pathConfig;
732 return pathConfig.string();
735 void ReadConfigFile(map<string, string>& mapSettingsRet,
736 map<string, vector<string> >& mapMultiSettingsRet)
738 namespace fs = boost::filesystem;
739 namespace pod = boost::program_options::detail;
741 fs::ifstream streamConfig(GetConfigFile());
742 if (!streamConfig.good())
745 set<string> setOptions;
746 setOptions.insert("*");
748 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
750 // Don't overwrite existing settings so command line settings override bitcoin.conf
751 string strKey = string("-") + it->string_key;
752 if (mapSettingsRet.count(strKey) == 0)
753 mapSettingsRet[strKey] = it->value[0];
754 mapMultiSettingsRet[strKey].push_back(it->value[0]);
760 namespace fs = boost::filesystem;
761 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
762 if (!pathConfig.is_complete())
763 pathConfig = fs::path(GetDataDir()) / pathConfig;
764 return pathConfig.string();
767 void CreatePidFile(string pidFile, pid_t pid)
770 if (file = fopen(pidFile.c_str(), "w"))
772 fprintf(file, "%d\n", pid);
777 int GetFilesize(FILE* file)
779 int nSavePos = ftell(file);
781 if (fseek(file, 0, SEEK_END) == 0)
782 nFilesize = ftell(file);
783 fseek(file, nSavePos, SEEK_SET);
787 void ShrinkDebugFile()
789 // Scroll debug.log if it's getting too big
790 string strFile = GetDataDir() + "/debug.log";
791 FILE* file = fopen(strFile.c_str(), "r");
792 if (file && GetFilesize(file) > 10 * 1000000)
794 // Restart the file with some of the end
796 fseek(file, -sizeof(pch), SEEK_END);
797 int nBytes = fread(pch, 1, sizeof(pch), file);
799 if (file = fopen(strFile.c_str(), "w"))
801 fwrite(pch, 1, nBytes, file);
815 // "Never go to sea with two chronometers; take one or three."
816 // Our three time sources are:
818 // - Median of other nodes's clocks
819 // - The user (asking the user to fix the system clock if the first two disagree)
826 static int64 nTimeOffset = 0;
828 int64 GetAdjustedTime()
830 return GetTime() + nTimeOffset;
833 void AddTimeData(unsigned int ip, int64 nTime)
835 int64 nOffsetSample = nTime - GetTime();
838 static set<unsigned int> setKnown;
839 if (!setKnown.insert(ip).second)
843 static vector<int64> vTimeOffsets;
844 if (vTimeOffsets.empty())
845 vTimeOffsets.push_back(0);
846 vTimeOffsets.push_back(nOffsetSample);
847 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
848 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
850 sort(vTimeOffsets.begin(), vTimeOffsets.end());
851 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
852 // Only let other nodes change our time by so much
853 if (abs64(nMedian) < 70 * 60)
855 nTimeOffset = nMedian;
864 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
866 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
867 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
873 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
874 strMiscWarning = strMessage;
875 printf("*** %s\n", strMessage.c_str());
876 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
880 BOOST_FOREACH(int64 n, vTimeOffsets)
881 printf("%+"PRI64d" ", n);
882 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
894 string FormatVersion(int nVersion)
896 if (nVersion%100 == 0)
897 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
899 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
902 string FormatFullVersion()
904 string s = FormatVersion(VERSION) + pszSubVer;
905 if (VERSION_IS_BETA) {