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.hpp>
9 #include <boost/filesystem/fstream.hpp>
10 #include <boost/interprocess/sync/interprocess_mutex.hpp>
11 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
12 #include <boost/foreach.hpp>
15 using namespace boost;
17 map<string, string> mapArgs;
18 map<string, vector<string> > mapMultiArgs;
20 bool fPrintToConsole = false;
21 bool fPrintToDebugger = false;
22 char pszSetDataDir[MAX_PATH] = "";
23 bool fRequestShutdown = false;
24 bool fShutdown = false;
27 bool fCommandLine = false;
28 string strMiscWarning;
29 bool fTestNet = false;
30 bool fNoListen = false;
31 bool fLogTimestamps = false;
36 // Workaround for "multiple definition of `_tls_used'"
37 // http://svn.boost.org/trac/boost/ticket/4258
38 extern "C" void tss_cleanup_implemented() { }
44 // Init openssl library multithreading support
45 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
46 void locking_callback(int mode, int i, const char* file, int line)
48 if (mode & CRYPTO_LOCK)
49 ppmutexOpenSSL[i]->lock();
51 ppmutexOpenSSL[i]->unlock();
60 // Init openssl library multithreading support
61 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
62 for (int i = 0; i < CRYPTO_num_locks(); i++)
63 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
64 CRYPTO_set_locking_callback(locking_callback);
67 // Seed random number generator with screen scrape and other hardware sources
71 // Seed random number generator with performance counter
76 // Shutdown openssl library multithreading support
77 CRYPTO_set_locking_callback(NULL);
78 for (int i = 0; i < CRYPTO_num_locks(); i++)
79 delete ppmutexOpenSSL[i];
80 OPENSSL_free(ppmutexOpenSSL);
94 // Seed with CPU performance counter
95 int64 nCounter = GetPerformanceCounter();
96 RAND_add(&nCounter, sizeof(nCounter), 1.5);
97 memset(&nCounter, 0, sizeof(nCounter));
100 void RandAddSeedPerfmon()
104 // This can take up to 2 seconds, so only do it every 10 minutes
105 static int64 nLastPerfmon;
106 if (GetTime() < nLastPerfmon + 10 * 60)
108 nLastPerfmon = GetTime();
111 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
112 // Seed with the entire set of perfmon data
113 unsigned char pdata[250000];
114 memset(pdata, 0, sizeof(pdata));
115 unsigned long nSize = sizeof(pdata);
116 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
117 RegCloseKey(HKEY_PERFORMANCE_DATA);
118 if (ret == ERROR_SUCCESS)
120 RAND_add(pdata, nSize, nSize/100.0);
121 memset(pdata, 0, nSize);
122 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
127 uint64 GetRand(uint64 nMax)
132 // The range of the random source must be a multiple of the modulus
133 // to give every possible output value an equal possibility
134 uint64 nRange = (UINT64_MAX / nMax) * nMax;
137 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
138 while (nRand >= nRange);
139 return (nRand % nMax);
142 int GetRandInt(int nMax)
144 return GetRand(nMax);
157 inline int OutputDebugStringF(const char* pszFormat, ...)
164 va_start(arg_ptr, pszFormat);
165 ret = vprintf(pszFormat, arg_ptr);
170 // print to debug.log
171 static FILE* fileout = NULL;
175 char pszFile[MAX_PATH+100];
177 strlcat(pszFile, "/debug.log", sizeof(pszFile));
178 fileout = fopen(pszFile, "a");
179 if (fileout) setbuf(fileout, NULL); // unbuffered
183 static bool fStartedNewLine = true;
185 // Debug print useful for profiling
186 if (fLogTimestamps && fStartedNewLine)
187 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
188 if (pszFormat[strlen(pszFormat) - 1] == '\n')
189 fStartedNewLine = true;
191 fStartedNewLine = false;
194 va_start(arg_ptr, pszFormat);
195 ret = vfprintf(fileout, pszFormat, arg_ptr);
201 if (fPrintToDebugger)
203 static CCriticalSection cs_OutputDebugStringF;
205 // accumulate a line at a time
206 CRITICAL_BLOCK(cs_OutputDebugStringF)
208 static char pszBuffer[50000];
213 va_start(arg_ptr, pszFormat);
214 int limit = END(pszBuffer) - pend - 2;
215 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
217 if (ret < 0 || ret >= limit)
219 pend = END(pszBuffer) - 2;
225 char* p1 = pszBuffer;
227 while (p2 = strchr(p1, '\n'))
232 OutputDebugStringA(p1);
237 memmove(pszBuffer, p1, pend - p1 + 1);
238 pend -= (p1 - pszBuffer);
247 // - prints up to limit-1 characters
248 // - output string is always null terminated even if limit reached
249 // - return value is the number of characters actually printed
250 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
255 va_start(arg_ptr, format);
256 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
258 if (ret < 0 || ret >= limit)
266 string strprintf(const std::string &format, ...)
270 int limit = sizeof(buffer);
275 va_start(arg_ptr, format);
276 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
278 if (ret >= 0 && ret < limit)
285 throw std::bad_alloc();
287 string str(p, p+ret);
293 bool error(const std::string &format, ...)
296 int limit = sizeof(buffer);
298 va_start(arg_ptr, format);
299 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
301 if (ret < 0 || ret >= limit)
306 printf("ERROR: %s\n", buffer);
311 void ParseString(const string& str, char c, vector<string>& v)
315 string::size_type i1 = 0;
316 string::size_type i2;
319 i2 = str.find(c, i1);
322 v.push_back(str.substr(i1));
325 v.push_back(str.substr(i1, i2-i1));
331 string FormatMoney(int64 n, bool fPlus)
333 // Note: not using straight sprintf here because we do NOT want
334 // localized number formatting.
335 int64 n_abs = (n > 0 ? n : -n);
336 int64 quotient = n_abs/COIN;
337 int64 remainder = n_abs%COIN;
338 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
340 // Right-trim excess 0's before the decimal point:
342 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
345 str.erase(str.size()-nTrim, nTrim);
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;
372 int64 nMult = CENT*10;
373 while (isdigit(*p) && (nMult > 0))
375 nUnits += nMult * (*p++ - '0');
384 strWhole.insert(strWhole.end(), *p);
389 if (strWhole.size() > 14)
391 if (nUnits < 0 || nUnits > COIN)
393 int64 nWhole = atoi64(strWhole);
394 int64 nValue = nWhole*COIN + nUnits;
401 vector<unsigned char> ParseHex(const char* psz)
403 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
408 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,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,-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, };
421 // convert hex dump to vector
422 vector<unsigned char> vch;
425 while (isspace(*psz))
427 char c = phexdigit[(unsigned char)*psz++];
430 unsigned char n = (c << 4);
431 c = phexdigit[(unsigned char)*psz++];
440 vector<unsigned char> ParseHex(const string& str)
442 return ParseHex(str.c_str());
446 void ParseParameters(int argc, char* argv[])
449 mapMultiArgs.clear();
450 for (int i = 1; i < argc; i++)
453 strlcpy(psz, argv[i], sizeof(psz));
454 char* pszValue = (char*)"";
455 if (strchr(psz, '='))
457 pszValue = strchr(psz, '=');
467 mapArgs[psz] = pszValue;
468 mapMultiArgs[psz].push_back(pszValue);
473 const char* wxGetTranslation(const char* pszEnglish)
476 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
477 static CCriticalSection cs;
481 static map<string, char*> mapCache;
482 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
483 if (mi != mapCache.end())
486 // wxWidgets translation
487 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
489 // We don't cache unknown strings because caller might be passing in a
490 // dynamic string and we would keep allocating memory for each variation.
491 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
494 // Add to cache, memory doesn't need to be freed. We only cache because
495 // we must pass back a pointer to permanently allocated memory.
496 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
497 strcpy(pszCached, strTranslated.utf8_str());
498 mapCache[pszEnglish] = pszCached;
508 bool WildcardMatch(const char* psz, const char* mask)
515 return (*psz == '\0');
517 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
532 bool WildcardMatch(const string& str, const string& mask)
534 return WildcardMatch(str.c_str(), mask.c_str());
544 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
547 char pszModule[MAX_PATH];
549 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
551 const char* pszModule = "bitcoin";
554 snprintf(pszMessage, 1000,
555 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
557 snprintf(pszMessage, 1000,
558 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
561 void LogException(std::exception* pex, const char* pszThread)
563 char pszMessage[10000];
564 FormatException(pszMessage, pex, pszThread);
565 printf("\n%s", pszMessage);
568 void PrintException(std::exception* pex, const char* pszThread)
570 char pszMessage[10000];
571 FormatException(pszMessage, pex, pszThread);
572 printf("\n\n************************\n%s\n", pszMessage);
573 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
574 strMiscWarning = pszMessage;
576 if (wxTheApp && !fDaemon)
577 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
582 void ThreadOneMessageBox(string strMessage)
584 // Skip message boxes if one is already open
585 static bool fMessageBoxOpen;
588 fMessageBoxOpen = true;
589 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
590 fMessageBoxOpen = false;
593 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
595 char pszMessage[10000];
596 FormatException(pszMessage, pex, pszThread);
597 printf("\n\n************************\n%s\n", pszMessage);
598 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
599 strMiscWarning = pszMessage;
601 if (wxTheApp && !fDaemon)
602 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
614 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
616 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
618 char pszPath[MAX_PATH+100] = "";
620 // SHGetSpecialFolderPath isn't always available on old Windows versions
621 HMODULE hShell32 = LoadLibraryA("shell32.dll");
624 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
625 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
626 if (pSHGetSpecialFolderPath)
627 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
628 FreeModule(hShell32);
632 if (pszPath[0] == '\0')
634 if (nFolder == CSIDL_STARTUP)
636 strcpy(pszPath, getenv("USERPROFILE"));
637 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
639 else if (nFolder == CSIDL_APPDATA)
641 strcpy(pszPath, getenv("APPDATA"));
649 string GetDefaultDataDir()
651 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
652 // Mac: ~/Library/Application Support/Bitcoin
656 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
658 char* pszHome = getenv("HOME");
659 if (pszHome == NULL || strlen(pszHome) == 0)
660 pszHome = (char*)"/";
661 string strHome = pszHome;
662 if (strHome[strHome.size()-1] != '/')
666 strHome += "Library/Application Support/";
667 filesystem::create_directory(strHome.c_str());
668 return strHome + "Bitcoin";
671 return strHome + ".bitcoin";
676 void GetDataDir(char* pszDir)
678 // pszDir must be at least MAX_PATH length.
680 if (pszSetDataDir[0] != 0)
682 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
687 // This can be called during exceptions by printf, so we cache the
688 // value so we don't have to do memory allocations after that.
689 static char pszCachedDir[MAX_PATH];
690 if (pszCachedDir[0] == 0)
691 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
692 strlcpy(pszDir, pszCachedDir, MAX_PATH);
697 char* p = pszDir + strlen(pszDir);
698 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
700 strcpy(p, "testnet");
703 static bool pfMkdir[4];
704 if (!pfMkdir[nVariation])
706 pfMkdir[nVariation] = true;
707 boost::filesystem::create_directory(pszDir);
713 char pszDir[MAX_PATH];
718 string GetConfigFile()
720 namespace fs = boost::filesystem;
721 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
722 if (!pathConfig.is_complete())
723 pathConfig = fs::path(GetDataDir()) / pathConfig;
724 return pathConfig.string();
727 void ReadConfigFile(map<string, string>& mapSettingsRet,
728 map<string, vector<string> >& mapMultiSettingsRet)
730 namespace fs = boost::filesystem;
731 namespace pod = boost::program_options::detail;
733 fs::ifstream streamConfig(GetConfigFile());
734 if (!streamConfig.good())
737 set<string> setOptions;
738 setOptions.insert("*");
740 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
742 // Don't overwrite existing settings so command line settings override bitcoin.conf
743 string strKey = string("-") + it->string_key;
744 if (mapSettingsRet.count(strKey) == 0)
745 mapSettingsRet[strKey] = it->value[0];
746 mapMultiSettingsRet[strKey].push_back(it->value[0]);
752 namespace fs = boost::filesystem;
753 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
754 if (!pathConfig.is_complete())
755 pathConfig = fs::path(GetDataDir()) / pathConfig;
756 return pathConfig.string();
759 void CreatePidFile(string pidFile, pid_t pid)
762 if (file = fopen(pidFile.c_str(), "w"))
764 fprintf(file, "%d\n", pid);
769 int GetFilesize(FILE* file)
771 int nSavePos = ftell(file);
773 if (fseek(file, 0, SEEK_END) == 0)
774 nFilesize = ftell(file);
775 fseek(file, nSavePos, SEEK_SET);
779 void ShrinkDebugFile()
781 // Scroll debug.log if it's getting too big
782 string strFile = GetDataDir() + "/debug.log";
783 FILE* file = fopen(strFile.c_str(), "r");
784 if (file && GetFilesize(file) > 10 * 1000000)
786 // Restart the file with some of the end
788 fseek(file, -sizeof(pch), SEEK_END);
789 int nBytes = fread(pch, 1, sizeof(pch), file);
791 if (file = fopen(strFile.c_str(), "w"))
793 fwrite(pch, 1, nBytes, file);
807 // "Never go to sea with two chronometers; take one or three."
808 // Our three time sources are:
810 // - Median of other nodes's clocks
811 // - The user (asking the user to fix the system clock if the first two disagree)
818 static int64 nTimeOffset = 0;
820 int64 GetAdjustedTime()
822 return GetTime() + nTimeOffset;
825 void AddTimeData(unsigned int ip, int64 nTime)
827 int64 nOffsetSample = nTime - GetTime();
830 static set<unsigned int> setKnown;
831 if (!setKnown.insert(ip).second)
835 static vector<int64> vTimeOffsets;
836 if (vTimeOffsets.empty())
837 vTimeOffsets.push_back(0);
838 vTimeOffsets.push_back(nOffsetSample);
839 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
840 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
842 sort(vTimeOffsets.begin(), vTimeOffsets.end());
843 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
844 // Only let other nodes change our time by so much
845 if (abs64(nMedian) < 70 * 60)
847 nTimeOffset = nMedian;
856 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
858 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
859 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
865 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
866 strMiscWarning = strMessage;
867 printf("*** %s\n", strMessage.c_str());
868 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
872 BOOST_FOREACH(int64 n, vTimeOffsets)
873 printf("%+"PRI64d" ", n);
874 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
886 string FormatVersion(int nVersion)
888 if (nVersion%100 == 0)
889 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
891 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
894 string FormatFullVersion()
896 string s = FormatVersion(VERSION) + pszSubVer;
897 if (VERSION_IS_BETA) {