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;
17 bool fCommandLine = false;
18 string strMiscWarning;
19 bool fTestNet = false;
20 bool fNoListen = false;
25 // Workaround for "multiple definition of `_tls_used'"
26 // http://svn.boost.org/trac/boost/ticket/4258
27 extern "C" void tss_cleanup_implemented() { }
33 // Init openssl library multithreading support
34 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
35 void locking_callback(int mode, int i, const char* file, int line)
37 if (mode & CRYPTO_LOCK)
38 ppmutexOpenSSL[i]->lock();
40 ppmutexOpenSSL[i]->unlock();
49 // Init openssl library multithreading support
50 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
51 for (int i = 0; i < CRYPTO_num_locks(); i++)
52 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
53 CRYPTO_set_locking_callback(locking_callback);
56 // Seed random number generator with screen scrape and other hardware sources
60 // Seed random number generator with performance counter
65 // Shutdown openssl library multithreading support
66 CRYPTO_set_locking_callback(NULL);
67 for (int i = 0; i < CRYPTO_num_locks(); i++)
68 delete ppmutexOpenSSL[i];
69 OPENSSL_free(ppmutexOpenSSL);
83 // Seed with CPU performance counter
84 int64 nCounter = GetPerformanceCounter();
85 RAND_add(&nCounter, sizeof(nCounter), 1.5);
86 memset(&nCounter, 0, sizeof(nCounter));
89 void RandAddSeedPerfmon()
93 // This can take up to 2 seconds, so only do it every 10 minutes
94 static int64 nLastPerfmon;
95 if (GetTime() < nLastPerfmon + 10 * 60)
97 nLastPerfmon = GetTime();
100 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
101 // Seed with the entire set of perfmon data
102 unsigned char pdata[250000];
103 memset(pdata, 0, sizeof(pdata));
104 unsigned long nSize = sizeof(pdata);
105 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
106 RegCloseKey(HKEY_PERFORMANCE_DATA);
107 if (ret == ERROR_SUCCESS)
109 RAND_add(pdata, nSize, nSize/100.0);
110 memset(pdata, 0, nSize);
111 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
116 uint64 GetRand(uint64 nMax)
121 // The range of the random source must be a multiple of the modulus
122 // to give every possible output value an equal possibility
123 uint64 nRange = (UINT64_MAX / nMax) * nMax;
126 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
127 while (nRand >= nRange);
128 return (nRand % nMax);
131 int GetRandInt(int nMax)
133 return GetRand(nMax);
146 inline int OutputDebugStringF(const char* pszFormat, ...)
153 va_start(arg_ptr, pszFormat);
154 ret = vprintf(pszFormat, arg_ptr);
159 // print to debug.log
160 static FILE* fileout = NULL;
164 char pszFile[MAX_PATH+100];
166 strlcat(pszFile, "/debug.log", sizeof(pszFile));
167 fileout = fopen(pszFile, "a");
168 if (fileout) setbuf(fileout, NULL); // unbuffered
172 //// Debug print useful for profiling
173 //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());
175 va_start(arg_ptr, pszFormat);
176 ret = vfprintf(fileout, pszFormat, arg_ptr);
182 if (fPrintToDebugger)
184 static CCriticalSection cs_OutputDebugStringF;
186 // accumulate a line at a time
187 CRITICAL_BLOCK(cs_OutputDebugStringF)
189 static char pszBuffer[50000];
194 va_start(arg_ptr, pszFormat);
195 int limit = END(pszBuffer) - pend - 2;
196 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
198 if (ret < 0 || ret >= limit)
200 pend = END(pszBuffer) - 2;
206 char* p1 = pszBuffer;
208 while (p2 = strchr(p1, '\n'))
213 OutputDebugStringA(p1);
218 memmove(pszBuffer, p1, pend - p1 + 1);
219 pend -= (p1 - pszBuffer);
228 // - prints up to limit-1 characters
229 // - output string is always null terminated even if limit reached
230 // - return value is the number of characters actually printed
231 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
236 va_start(arg_ptr, format);
237 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
239 if (ret < 0 || ret >= limit)
248 string strprintf(const char* format, ...)
252 int limit = sizeof(buffer);
257 va_start(arg_ptr, format);
258 ret = _vsnprintf(p, limit, format, arg_ptr);
260 if (ret >= 0 && ret < limit)
267 throw std::bad_alloc();
269 string str(p, p+ret);
276 bool error(const char* format, ...)
279 int limit = sizeof(buffer);
281 va_start(arg_ptr, format);
282 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
284 if (ret < 0 || ret >= limit)
289 printf("ERROR: %s\n", buffer);
294 void ParseString(const string& str, char c, vector<string>& v)
298 string::size_type i1 = 0;
299 string::size_type i2;
302 i2 = str.find(c, i1);
305 v.push_back(str.substr(i1));
308 v.push_back(str.substr(i1, i2-i1));
314 string FormatMoney(int64 n, bool fPlus)
316 // Note: not using straight sprintf here because we do NOT want
317 // localized number formatting.
318 int64 n_abs = (n > 0 ? n : -n);
319 int64 quotient = n_abs/COIN;
320 int64 remainder = n_abs%COIN;
321 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
323 // Right-trim excess 0's before the decimal point:
325 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
328 str.erase(str.size()-nTrim, nTrim);
330 // Insert thousands-separators:
331 size_t point = str.find(".");
332 for (int i = (str.size()-point)+3; i < str.size(); i += 4)
333 if (isdigit(str[str.size() - i - 1]))
334 str.insert(str.size() - i, 1, ',');
336 str.insert((unsigned int)0, 1, '-');
337 else if (fPlus && n > 0)
338 str.insert((unsigned int)0, 1, '+');
343 bool ParseMoney(const string& str, int64& nRet)
345 return ParseMoney(str.c_str(), nRet);
348 bool ParseMoney(const char* pszIn, int64& nRet)
352 const char* p = pszIn;
357 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
362 int64 nMult = CENT*10;
363 while (isdigit(*p) && (nMult > 0))
365 nUnits += nMult * (*p++ - '0');
374 strWhole.insert(strWhole.end(), *p);
379 if (strWhole.size() > 14)
381 if (nUnits < 0 || nUnits > COIN)
383 int64 nWhole = atoi64(strWhole);
384 int64 nValue = nWhole*COIN + nUnits;
391 vector<unsigned char> ParseHex(const char* psz)
393 static char phexdigit[256] =
394 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
395 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
396 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
397 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
398 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
399 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
411 // convert hex dump to vector
412 vector<unsigned char> vch;
415 while (isspace(*psz))
417 char c = phexdigit[(unsigned char)*psz++];
420 unsigned char n = (c << 4);
421 c = phexdigit[(unsigned char)*psz++];
430 vector<unsigned char> ParseHex(const string& str)
432 return ParseHex(str.c_str());
436 void ParseParameters(int argc, char* argv[])
439 mapMultiArgs.clear();
440 for (int i = 1; i < argc; i++)
443 strlcpy(psz, argv[i], sizeof(psz));
444 char* pszValue = (char*)"";
445 if (strchr(psz, '='))
447 pszValue = strchr(psz, '=');
457 mapArgs[psz] = pszValue;
458 mapMultiArgs[psz].push_back(pszValue);
463 const char* wxGetTranslation(const char* pszEnglish)
466 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
467 static CCriticalSection cs;
471 static map<string, char*> mapCache;
472 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
473 if (mi != mapCache.end())
476 // wxWidgets translation
477 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
479 // We don't cache unknown strings because caller might be passing in a
480 // dynamic string and we would keep allocating memory for each variation.
481 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
484 // Add to cache, memory doesn't need to be freed. We only cache because
485 // we must pass back a pointer to permanently allocated memory.
486 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
487 strcpy(pszCached, strTranslated.utf8_str());
488 mapCache[pszEnglish] = pszCached;
498 bool WildcardMatch(const char* psz, const char* mask)
505 return (*psz == '\0');
507 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
522 bool WildcardMatch(const string& str, const string& mask)
524 return WildcardMatch(str.c_str(), mask.c_str());
534 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
537 char pszModule[MAX_PATH];
539 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
541 const char* pszModule = "bitcoin";
544 snprintf(pszMessage, 1000,
545 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
547 snprintf(pszMessage, 1000,
548 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
551 void LogException(std::exception* pex, const char* pszThread)
553 char pszMessage[10000];
554 FormatException(pszMessage, pex, pszThread);
555 printf("\n%s", pszMessage);
558 void PrintException(std::exception* pex, const char* pszThread)
560 char pszMessage[10000];
561 FormatException(pszMessage, pex, pszThread);
562 printf("\n\n************************\n%s\n", pszMessage);
563 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
564 strMiscWarning = pszMessage;
566 if (wxTheApp && !fDaemon)
567 MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
572 void ThreadOneMessageBox(string strMessage)
574 // Skip message boxes if one is already open
575 static bool fMessageBoxOpen;
578 fMessageBoxOpen = true;
579 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
580 fMessageBoxOpen = false;
583 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
585 char pszMessage[10000];
586 FormatException(pszMessage, pex, pszThread);
587 printf("\n\n************************\n%s\n", pszMessage);
588 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
589 strMiscWarning = pszMessage;
591 if (wxTheApp && !fDaemon)
592 boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
604 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
606 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
608 char pszPath[MAX_PATH+100] = "";
610 // SHGetSpecialFolderPath isn't always available on old Windows versions
611 HMODULE hShell32 = LoadLibraryA("shell32.dll");
614 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
615 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
616 if (pSHGetSpecialFolderPath)
617 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
618 FreeModule(hShell32);
622 if (pszPath[0] == '\0')
624 if (nFolder == CSIDL_STARTUP)
626 strcpy(pszPath, getenv("USERPROFILE"));
627 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
629 else if (nFolder == CSIDL_APPDATA)
631 strcpy(pszPath, getenv("APPDATA"));
639 string GetDefaultDataDir()
641 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
642 // Mac: ~/Library/Application Support/Bitcoin
646 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
648 char* pszHome = getenv("HOME");
649 if (pszHome == NULL || strlen(pszHome) == 0)
650 pszHome = (char*)"/";
651 string strHome = pszHome;
652 if (strHome[strHome.size()-1] != '/')
656 strHome += "Library/Application Support/";
657 filesystem::create_directory(strHome.c_str());
658 return strHome + "Bitcoin";
661 return strHome + ".bitcoin";
666 void GetDataDir(char* pszDir)
668 // pszDir must be at least MAX_PATH length.
670 if (pszSetDataDir[0] != 0)
672 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
677 // This can be called during exceptions by printf, so we cache the
678 // value so we don't have to do memory allocations after that.
679 static char pszCachedDir[MAX_PATH];
680 if (pszCachedDir[0] == 0)
681 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
682 strlcpy(pszDir, pszCachedDir, MAX_PATH);
687 char* p = pszDir + strlen(pszDir);
688 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
690 strcpy(p, "testnet");
693 static bool pfMkdir[4];
694 if (!pfMkdir[nVariation])
696 pfMkdir[nVariation] = true;
697 filesystem::create_directory(pszDir);
703 char pszDir[MAX_PATH];
708 string GetConfigFile()
710 namespace fs = boost::filesystem;
711 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
712 if (!pathConfig.is_complete())
713 pathConfig = fs::path(GetDataDir()) / pathConfig;
714 return pathConfig.string();
717 void ReadConfigFile(map<string, string>& mapSettingsRet,
718 map<string, vector<string> >& mapMultiSettingsRet)
720 namespace fs = boost::filesystem;
721 namespace pod = boost::program_options::detail;
723 fs::ifstream streamConfig(GetConfigFile());
724 if (!streamConfig.good())
727 set<string> setOptions;
728 setOptions.insert("*");
730 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
732 // Don't overwrite existing settings so command line settings override bitcoin.conf
733 string strKey = string("-") + it->string_key;
734 if (mapSettingsRet.count(strKey) == 0)
735 mapSettingsRet[strKey] = it->value[0];
736 mapMultiSettingsRet[strKey].push_back(it->value[0]);
740 int GetFilesize(FILE* file)
742 int nSavePos = ftell(file);
744 if (fseek(file, 0, SEEK_END) == 0)
745 nFilesize = ftell(file);
746 fseek(file, nSavePos, SEEK_SET);
750 void ShrinkDebugFile()
752 // Scroll debug.log if it's getting too big
753 string strFile = GetDataDir() + "/debug.log";
754 FILE* file = fopen(strFile.c_str(), "r");
755 if (file && GetFilesize(file) > 10 * 1000000)
757 // Restart the file with some of the end
759 fseek(file, -sizeof(pch), SEEK_END);
760 int nBytes = fread(pch, 1, sizeof(pch), file);
762 if (file = fopen(strFile.c_str(), "w"))
764 fwrite(pch, 1, nBytes, file);
778 // "Never go to sea with two chronometers; take one or three."
779 // Our three time sources are:
781 // - Median of other nodes's clocks
782 // - The user (asking the user to fix the system clock if the first two disagree)
789 static int64 nTimeOffset = 0;
791 int64 GetAdjustedTime()
793 return GetTime() + nTimeOffset;
796 void AddTimeData(unsigned int ip, int64 nTime)
798 int64 nOffsetSample = nTime - GetTime();
801 static set<unsigned int> setKnown;
802 if (!setKnown.insert(ip).second)
806 static vector<int64> vTimeOffsets;
807 if (vTimeOffsets.empty())
808 vTimeOffsets.push_back(0);
809 vTimeOffsets.push_back(nOffsetSample);
810 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
811 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
813 sort(vTimeOffsets.begin(), vTimeOffsets.end());
814 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
815 // Only let other nodes change our time by so much
816 if (abs64(nMedian) < 70 * 60)
818 nTimeOffset = nMedian;
827 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
829 foreach(int64 nOffset, vTimeOffsets)
830 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
836 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
837 strMiscWarning = strMessage;
838 printf("*** %s\n", strMessage.c_str());
839 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
843 foreach(int64 n, vTimeOffsets)
844 printf("%+"PRI64d" ", n);
845 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);