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 fShutdown = false;
16 bool fCommandLine = false;
17 string strMiscWarning;
23 // Workaround for "multiple definition of `_tls_used'"
24 // http://svn.boost.org/trac/boost/ticket/4258
25 extern "C" void tss_cleanup_implemented() { }
31 // Init openssl library multithreading support
32 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
33 void locking_callback(int mode, int i, const char* file, int line)
35 if (mode & CRYPTO_LOCK)
36 ppmutexOpenSSL[i]->lock();
38 ppmutexOpenSSL[i]->unlock();
47 // Init openssl library multithreading support
48 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
49 for (int i = 0; i < CRYPTO_num_locks(); i++)
50 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
51 CRYPTO_set_locking_callback(locking_callback);
54 // Seed random number generator with screen scrape and other hardware sources
58 // Seed random number generator with performance counter
63 // Shutdown openssl library multithreading support
64 CRYPTO_set_locking_callback(NULL);
65 for (int i = 0; i < CRYPTO_num_locks(); i++)
66 delete ppmutexOpenSSL[i];
67 OPENSSL_free(ppmutexOpenSSL);
81 // Seed with CPU performance counter
82 int64 nCounter = PerformanceCounter();
83 RAND_add(&nCounter, sizeof(nCounter), 1.5);
84 memset(&nCounter, 0, sizeof(nCounter));
87 void RandAddSeedPerfmon()
91 // This can take up to 2 seconds, so only do it every 10 minutes
92 static int64 nLastPerfmon;
93 if (GetTime() < nLastPerfmon + 10 * 60)
95 nLastPerfmon = GetTime();
98 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
99 // Seed with the entire set of perfmon data
100 unsigned char pdata[250000];
101 memset(pdata, 0, sizeof(pdata));
102 unsigned long nSize = sizeof(pdata);
103 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
104 RegCloseKey(HKEY_PERFORMANCE_DATA);
105 if (ret == ERROR_SUCCESS)
107 RAND_add(pdata, nSize, nSize/100.0);
108 memset(pdata, 0, nSize);
109 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
114 uint64 GetRand(uint64 nMax)
119 // The range of the random source must be a multiple of the modulus
120 // to give every possible output value an equal possibility
121 uint64 nRange = (UINT64_MAX / nMax) * nMax;
124 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
125 while (nRand >= nRange);
126 return (nRand % nMax);
139 inline int OutputDebugStringF(const char* pszFormat, ...)
146 va_start(arg_ptr, pszFormat);
147 ret = vprintf(pszFormat, arg_ptr);
152 // print to debug.log
153 char pszFile[MAX_PATH+100];
155 strlcat(pszFile, "/debug.log", sizeof(pszFile));
156 FILE* fileout = fopen(pszFile, "a");
159 //// Debug print useful for profiling
160 //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());
162 va_start(arg_ptr, pszFormat);
163 ret = vfprintf(fileout, pszFormat, arg_ptr);
170 if (fPrintToDebugger)
172 // accumulate a line at a time
173 static CCriticalSection cs_OutputDebugStringF;
174 CRITICAL_BLOCK(cs_OutputDebugStringF)
176 static char pszBuffer[50000];
181 va_start(arg_ptr, pszFormat);
182 int limit = END(pszBuffer) - pend - 2;
183 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
185 if (ret < 0 || ret >= limit)
187 pend = END(pszBuffer) - 2;
193 char* p1 = pszBuffer;
195 while (p2 = strchr(p1, '\n'))
200 OutputDebugStringA(p1);
205 memmove(pszBuffer, p1, pend - p1 + 1);
206 pend -= (p1 - pszBuffer);
215 // - prints up to limit-1 characters
216 // - output string is always null terminated even if limit reached
217 // - return value is the number of characters actually printed
218 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
223 va_start(arg_ptr, format);
224 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
226 if (ret < 0 || ret >= limit)
235 string strprintf(const char* format, ...)
239 int limit = sizeof(buffer);
244 va_start(arg_ptr, format);
245 ret = _vsnprintf(p, limit, format, arg_ptr);
247 if (ret >= 0 && ret < limit)
254 throw std::bad_alloc();
256 string str(p, p+ret);
263 bool error(const char* format, ...)
266 int limit = sizeof(buffer);
268 va_start(arg_ptr, format);
269 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
271 if (ret < 0 || ret >= limit)
276 printf("ERROR: %s\n", buffer);
281 void ParseString(const string& str, char c, vector<string>& v)
285 string::size_type i1 = 0;
286 string::size_type i2;
289 i2 = str.find(c, i1);
292 v.push_back(str.substr(i1));
295 v.push_back(str.substr(i1, i2-i1));
301 string FormatMoney(int64 n, bool fPlus)
304 string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);
305 for (int i = 6; i < str.size(); i += 4)
306 if (isdigit(str[str.size() - i - 1]))
307 str.insert(str.size() - i, 1, ',');
309 str.insert((unsigned int)0, 1, '-');
310 else if (fPlus && n > 0)
311 str.insert((unsigned int)0, 1, '+');
316 bool ParseMoney(const string& str, int64& nRet)
318 return ParseMoney(str.c_str(), nRet);
321 bool ParseMoney(const char* pszIn, int64& nRet)
325 const char* p = pszIn;
330 if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
337 nCents = 10 * (*p++ - '0');
339 nCents += (*p++ - '0');
347 strWhole.insert(strWhole.end(), *p);
352 if (strWhole.size() > 14)
354 if (nCents < 0 || nCents > 99)
356 int64 nWhole = atoi64(strWhole);
357 int64 nPreValue = nWhole * 100 + nCents;
358 int64 nValue = nPreValue * CENT;
359 if (nValue / CENT != nPreValue)
361 if (nValue / COIN != nWhole)
368 vector<unsigned char> ParseHex(const char* psz)
370 static char phexdigit[256] =
371 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
372 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
373 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
374 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
375 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
376 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
377 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
378 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
379 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
380 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
381 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
382 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
383 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
384 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
385 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
386 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
388 // convert hex dump to vector
389 vector<unsigned char> vch;
392 while (isspace(*psz))
394 char c = phexdigit[(unsigned char)*psz++];
397 unsigned char n = (c << 4);
398 c = phexdigit[(unsigned char)*psz++];
407 vector<unsigned char> ParseHex(const std::string& str)
409 return ParseHex(str.c_str());
413 void ParseParameters(int argc, char* argv[])
416 mapMultiArgs.clear();
417 for (int i = 1; i < argc; i++)
420 strlcpy(psz, argv[i], sizeof(psz));
421 char* pszValue = (char*)"";
422 if (strchr(psz, '='))
424 pszValue = strchr(psz, '=');
434 mapArgs[psz] = pszValue;
435 mapMultiArgs[psz].push_back(pszValue);
440 const char* wxGetTranslation(const char* pszEnglish)
443 // Wrapper of wxGetTranslation returning the same const char* type as was passed in
444 static CCriticalSection cs;
448 static map<string, char*> mapCache;
449 map<string, char*>::iterator mi = mapCache.find(pszEnglish);
450 if (mi != mapCache.end())
453 // wxWidgets translation
454 wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
456 // We don't cache unknown strings because caller might be passing in a
457 // dynamic string and we would keep allocating memory for each variation.
458 if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
461 // Add to cache, memory doesn't need to be freed. We only cache because
462 // we must pass back a pointer to permanently allocated memory.
463 char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
464 strcpy(pszCached, strTranslated.utf8_str());
465 mapCache[pszEnglish] = pszCached;
483 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
486 char pszModule[MAX_PATH];
488 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
490 const char* pszModule = "bitcoin";
493 snprintf(pszMessage, 1000,
494 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
496 snprintf(pszMessage, 1000,
497 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
500 void LogException(std::exception* pex, const char* pszThread)
502 char pszMessage[1000];
503 FormatException(pszMessage, pex, pszThread);
504 printf("\n%s", pszMessage);
507 void PrintException(std::exception* pex, const char* pszThread)
509 char pszMessage[1000];
510 FormatException(pszMessage, pex, pszThread);
511 printf("\n\n************************\n%s\n", pszMessage);
512 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
514 if (wxTheApp && !fDaemon)
515 MyMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);
529 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
531 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
533 char pszPath[MAX_PATH+100] = "";
535 // SHGetSpecialFolderPath isn't always available on old Windows versions
536 HMODULE hShell32 = LoadLibraryA("shell32.dll");
539 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
540 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
541 if (pSHGetSpecialFolderPath)
542 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
543 FreeModule(hShell32);
547 if (pszPath[0] == '\0')
549 if (nFolder == CSIDL_STARTUP)
551 strcpy(pszPath, getenv("USERPROFILE"));
552 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
554 else if (nFolder == CSIDL_APPDATA)
556 strcpy(pszPath, getenv("APPDATA"));
564 string GetDefaultDataDir()
566 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
567 // Mac: ~/Library/Application Support/Bitcoin
571 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
573 char* pszHome = getenv("HOME");
574 if (pszHome == NULL || strlen(pszHome) == 0)
575 pszHome = (char*)"/";
576 string strHome = pszHome;
577 if (strHome[strHome.size()-1] != '/')
581 strHome += "Library/Application Support/";
582 filesystem::create_directory(strHome.c_str());
583 return strHome + "Bitcoin";
586 return strHome + ".bitcoin";
591 void GetDataDir(char* pszDir)
593 // pszDir must be at least MAX_PATH length.
594 if (pszSetDataDir[0] != 0)
596 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
597 static bool fMkdirDone;
601 filesystem::create_directory(pszDir);
606 // This can be called during exceptions by printf, so we cache the
607 // value so we don't have to do memory allocations after that.
608 static char pszCachedDir[MAX_PATH];
609 if (pszCachedDir[0] == 0)
611 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
612 filesystem::create_directory(pszCachedDir);
614 strlcpy(pszDir, pszCachedDir, MAX_PATH);
620 char pszDir[MAX_PATH];
625 string GetConfigFile()
627 namespace fs = boost::filesystem;
628 fs::path pathConfig(mapArgs.count("-conf") ? mapArgs["-conf"] : string("bitcoin.conf"));
629 if (!pathConfig.is_complete())
630 pathConfig = fs::path(GetDataDir()) / pathConfig;
631 return pathConfig.string();
634 void ReadConfigFile(map<string, string>& mapSettingsRet,
635 map<string, vector<string> >& mapMultiSettingsRet)
637 namespace fs = boost::filesystem;
638 namespace pod = boost::program_options::detail;
640 fs::ifstream streamConfig(GetConfigFile());
641 if (!streamConfig.good())
644 set<string> setOptions;
645 setOptions.insert("*");
647 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
649 // Don't overwrite existing settings so command line settings override bitcoin.conf
650 string strKey = string("-") + it->string_key;
651 if (mapSettingsRet.count(strKey) == 0)
652 mapSettingsRet[strKey] = it->value[0];
653 mapMultiSettingsRet[strKey].push_back(it->value[0]);
657 int GetFilesize(FILE* file)
659 int nSavePos = ftell(file);
661 if (fseek(file, 0, SEEK_END) == 0)
662 nFilesize = ftell(file);
663 fseek(file, nSavePos, SEEK_SET);
667 void ShrinkDebugFile()
669 // Scroll debug.log if it's getting too big
670 string strFile = GetDataDir() + "/debug.log";
671 FILE* file = fopen(strFile.c_str(), "r");
672 if (file && GetFilesize(file) > 10 * 1000000)
674 // Restart the file with some of the end
676 fseek(file, -sizeof(pch), SEEK_END);
677 int nBytes = fread(pch, 1, sizeof(pch), file);
679 if (file = fopen(strFile.c_str(), "w"))
681 fwrite(pch, 1, nBytes, file);
695 // "Never go to sea with two chronometers; take one or three."
696 // Our three chronometers are:
698 // - Median of other server's clocks
701 // note: NTP isn't implemented yet, so until then we just use the median
702 // of other nodes clocks to correct ours.
709 static int64 nTimeOffset = 0;
711 int64 GetAdjustedTime()
713 return GetTime() + nTimeOffset;
716 void AddTimeData(unsigned int ip, int64 nTime)
718 int64 nOffsetSample = nTime - GetTime();
721 static set<unsigned int> setKnown;
722 if (!setKnown.insert(ip).second)
726 static vector<int64> vTimeOffsets;
727 if (vTimeOffsets.empty())
728 vTimeOffsets.push_back(0);
729 vTimeOffsets.push_back(nOffsetSample);
730 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
731 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
733 sort(vTimeOffsets.begin(), vTimeOffsets.end());
734 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
735 // Only let other nodes change our time by so much
736 if (abs64(nMedian) < 70 * 60)
738 nTimeOffset = nMedian;
743 // If nobody else has the same time as us, give a warning
745 foreach(int64 nOffset, vTimeOffsets)
746 if (nOffset != 0 && abs64(nOffset) < 10 * 60)
749 if (!fMatch && !fDone)
752 string strMessage = _("Warning: Check your system date and time, you may not be able to generate or receive the most recent blocks!");
753 strMiscWarning = strMessage;
754 printf("*** %s\n", strMessage.c_str());
755 boost::thread(bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
758 foreach(int64 n, vTimeOffsets)
759 printf("%+"PRI64d" ", n);
760 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);