1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 // Work around clang compilation problem in Boost 1.46:
9 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
10 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
11 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
13 namespace program_options {
14 std::string to_internal(const std::string&);
18 #include <boost/program_options/detail/config_file.hpp>
19 #include <boost/program_options/parsers.hpp>
20 #include <boost/filesystem.hpp>
21 #include <boost/filesystem/fstream.hpp>
22 #include <boost/interprocess/sync/interprocess_mutex.hpp>
23 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
24 #include <boost/foreach.hpp>
25 #include <boost/thread.hpp>
28 using namespace boost;
30 map<string, string> mapArgs;
31 map<string, vector<string> > mapMultiArgs;
33 bool fPrintToConsole = false;
34 bool fPrintToDebugger = false;
35 char pszSetDataDir[MAX_PATH] = "";
36 bool fRequestShutdown = false;
37 bool fShutdown = false;
40 bool fCommandLine = false;
41 string strMiscWarning;
42 bool fTestNet = false;
43 bool fNoListen = false;
44 bool fLogTimestamps = false;
49 // Workaround for "multiple definition of `_tls_used'"
50 // http://svn.boost.org/trac/boost/ticket/4258
51 extern "C" void tss_cleanup_implemented() { }
57 // Init openssl library multithreading support
58 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
59 void locking_callback(int mode, int i, const char* file, int line)
61 if (mode & CRYPTO_LOCK)
62 ppmutexOpenSSL[i]->lock();
64 ppmutexOpenSSL[i]->unlock();
73 // Init openssl library multithreading support
74 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
75 for (int i = 0; i < CRYPTO_num_locks(); i++)
76 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
77 CRYPTO_set_locking_callback(locking_callback);
80 // Seed random number generator with screen scrape and other hardware sources
84 // Seed random number generator with performance counter
89 // Shutdown openssl library multithreading support
90 CRYPTO_set_locking_callback(NULL);
91 for (int i = 0; i < CRYPTO_num_locks(); i++)
92 delete ppmutexOpenSSL[i];
93 OPENSSL_free(ppmutexOpenSSL);
107 // Seed with CPU performance counter
108 int64 nCounter = GetPerformanceCounter();
109 RAND_add(&nCounter, sizeof(nCounter), 1.5);
110 memset(&nCounter, 0, sizeof(nCounter));
113 void RandAddSeedPerfmon()
117 // This can take up to 2 seconds, so only do it every 10 minutes
118 static int64 nLastPerfmon;
119 if (GetTime() < nLastPerfmon + 10 * 60)
121 nLastPerfmon = GetTime();
124 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
125 // Seed with the entire set of perfmon data
126 unsigned char pdata[250000];
127 memset(pdata, 0, sizeof(pdata));
128 unsigned long nSize = sizeof(pdata);
129 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
130 RegCloseKey(HKEY_PERFORMANCE_DATA);
131 if (ret == ERROR_SUCCESS)
133 RAND_add(pdata, nSize, nSize/100.0);
134 memset(pdata, 0, nSize);
135 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
140 uint64 GetRand(uint64 nMax)
145 // The range of the random source must be a multiple of the modulus
146 // to give every possible output value an equal possibility
147 uint64 nRange = (UINT64_MAX / nMax) * nMax;
150 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
151 while (nRand >= nRange);
152 return (nRand % nMax);
155 int GetRandInt(int nMax)
157 return GetRand(nMax);
170 inline int OutputDebugStringF(const char* pszFormat, ...)
177 va_start(arg_ptr, pszFormat);
178 ret = vprintf(pszFormat, arg_ptr);
183 // print to debug.log
184 static FILE* fileout = NULL;
188 char pszFile[MAX_PATH+100];
190 strlcat(pszFile, "/debug.log", sizeof(pszFile));
191 fileout = fopen(pszFile, "a");
192 if (fileout) setbuf(fileout, NULL); // unbuffered
196 static bool fStartedNewLine = true;
197 static boost::mutex mutexDebugLog;
198 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
200 // Debug print useful for profiling
201 if (fLogTimestamps && fStartedNewLine)
202 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
203 if (pszFormat[strlen(pszFormat) - 1] == '\n')
204 fStartedNewLine = true;
206 fStartedNewLine = false;
209 va_start(arg_ptr, pszFormat);
210 ret = vfprintf(fileout, pszFormat, arg_ptr);
216 if (fPrintToDebugger)
218 static CCriticalSection cs_OutputDebugStringF;
220 // accumulate a line at a time
221 CRITICAL_BLOCK(cs_OutputDebugStringF)
223 static char pszBuffer[50000];
228 va_start(arg_ptr, pszFormat);
229 int limit = END(pszBuffer) - pend - 2;
230 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
232 if (ret < 0 || ret >= limit)
234 pend = END(pszBuffer) - 2;
240 char* p1 = pszBuffer;
242 while ((p2 = strchr(p1, '\n')))
247 OutputDebugStringA(p1);
252 memmove(pszBuffer, p1, pend - p1 + 1);
253 pend -= (p1 - pszBuffer);
262 // - prints up to limit-1 characters
263 // - output string is always null terminated even if limit reached
264 // - return value is the number of characters actually printed
265 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
270 va_start(arg_ptr, format);
271 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
273 if (ret < 0 || ret >= limit)
281 string strprintf(const std::string &format, ...)
285 int limit = sizeof(buffer);
290 va_start(arg_ptr, format);
291 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
293 if (ret >= 0 && ret < limit)
300 throw std::bad_alloc();
302 string str(p, p+ret);
308 bool error(const std::string &format, ...)
311 int limit = sizeof(buffer);
313 va_start(arg_ptr, format);
314 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
316 if (ret < 0 || ret >= limit)
321 printf("ERROR: %s\n", buffer);
326 void ParseString(const string& str, char c, vector<string>& v)
330 string::size_type i1 = 0;
331 string::size_type i2;
334 i2 = str.find(c, i1);
337 v.push_back(str.substr(i1));
340 v.push_back(str.substr(i1, i2-i1));
346 string FormatMoney(int64 n, bool fPlus)
348 // Note: not using straight sprintf here because we do NOT want
349 // localized number formatting.
350 int64 n_abs = (n > 0 ? n : -n);
351 int64 quotient = n_abs/COIN;
352 int64 remainder = n_abs%COIN;
353 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
355 // Right-trim excess 0's before the decimal point:
357 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
360 str.erase(str.size()-nTrim, nTrim);
363 str.insert((unsigned int)0, 1, '-');
364 else if (fPlus && n > 0)
365 str.insert((unsigned int)0, 1, '+');
370 bool ParseMoney(const string& str, int64& nRet)
372 return ParseMoney(str.c_str(), nRet);
375 bool ParseMoney(const char* pszIn, int64& nRet)
379 const char* p = pszIn;
387 int64 nMult = CENT*10;
388 while (isdigit(*p) && (nMult > 0))
390 nUnits += nMult * (*p++ - '0');
399 strWhole.insert(strWhole.end(), *p);
404 if (strWhole.size() > 10) // guard against 63 bit overflow
406 if (nUnits < 0 || nUnits > COIN)
408 int64 nWhole = atoi64(strWhole);
409 int64 nValue = nWhole*COIN + nUnits;
416 vector<unsigned char> ParseHex(const char* psz)
418 static signed char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
423 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
428 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
429 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
430 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
431 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
432 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
433 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
434 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
436 // convert hex dump to vector
437 vector<unsigned char> vch;
440 while (isspace(*psz))
442 signed char c = phexdigit[(unsigned char)*psz++];
443 if (c == (signed char)-1)
445 unsigned char n = (c << 4);
446 c = phexdigit[(unsigned char)*psz++];
447 if (c == (signed char)-1)
455 vector<unsigned char> ParseHex(const string& str)
457 return ParseHex(str.c_str());
460 void ParseParameters(int argc, char* argv[])
463 mapMultiArgs.clear();
464 for (int i = 1; i < argc; i++)
467 strlcpy(psz, argv[i], sizeof(psz));
468 char* pszValue = (char*)"";
469 if (strchr(psz, '='))
471 pszValue = strchr(psz, '=');
481 mapArgs[psz] = pszValue;
482 mapMultiArgs[psz].push_back(pszValue);
486 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
488 if (mapArgs.count(strArg))
490 mapArgs[strArg] = strValue;
494 bool SoftSetArg(const std::string& strArg, bool fValue)
497 return SoftSetArg(strArg, std::string("1"));
499 return SoftSetArg(strArg, std::string("0"));
503 string EncodeBase64(const unsigned char* pch, size_t len)
505 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
508 strRet.reserve((len+2)/3*4);
511 const unsigned char *pchEnd = pch+len;
518 case 0: // we have no bits
519 strRet += pbase64[enc >> 2];
520 left = (enc & 3) << 4;
524 case 1: // we have two bits
525 strRet += pbase64[left | (enc >> 4)];
526 left = (enc & 15) << 2;
530 case 2: // we have four bits
531 strRet += pbase64[left | (enc >> 6)];
532 strRet += pbase64[enc & 63];
540 strRet += pbase64[left];
549 string EncodeBase64(const string& str)
551 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
554 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
556 static const int decode64_table[256] =
558 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
559 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
560 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
561 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
562 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
563 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
564 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
565 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
566 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
567 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
568 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
569 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
570 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
576 vector<unsigned char> vchRet;
577 vchRet.reserve(strlen(p)*3/4);
584 int dec = decode64_table[(unsigned char)*p];
585 if (dec == -1) break;
589 case 0: // we have no bits and get 6
594 case 1: // we have 6 bits and keep 4
595 vchRet.push_back((left<<2) | (dec>>4));
600 case 2: // we have 4 bits and get 6, we keep 2
601 vchRet.push_back((left<<4) | (dec>>2));
606 case 3: // we have 2 bits and get 6
607 vchRet.push_back((left<<6) | dec);
616 case 0: // 4n base64 characters processed: ok
619 case 1: // 4n+1 base64 character processed: impossible
623 case 2: // 4n+2 base64 characters processed: require '=='
624 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
628 case 3: // 4n+3 base64 characters processed: require '='
629 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
637 string DecodeBase64(const string& str)
639 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
640 return string((const char*)&vchRet[0], vchRet.size());
644 bool WildcardMatch(const char* psz, const char* mask)
651 return (*psz == '\0');
653 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
668 bool WildcardMatch(const string& str, const string& mask)
670 return WildcardMatch(str.c_str(), mask.c_str());
680 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
683 char pszModule[MAX_PATH];
685 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
687 const char* pszModule = "bitcoin";
690 snprintf(pszMessage, 1000,
691 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
693 snprintf(pszMessage, 1000,
694 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
697 void LogException(std::exception* pex, const char* pszThread)
699 char pszMessage[10000];
700 FormatException(pszMessage, pex, pszThread);
701 printf("\n%s", pszMessage);
704 void PrintException(std::exception* pex, const char* pszThread)
706 char pszMessage[10000];
707 FormatException(pszMessage, pex, pszThread);
708 printf("\n\n************************\n%s\n", pszMessage);
709 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
710 strMiscWarning = pszMessage;
714 void ThreadOneMessageBox(string strMessage)
716 // Skip message boxes if one is already open
717 static bool fMessageBoxOpen;
720 fMessageBoxOpen = true;
721 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
722 fMessageBoxOpen = false;
725 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
727 char pszMessage[10000];
728 FormatException(pszMessage, pex, pszThread);
729 printf("\n\n************************\n%s\n", pszMessage);
730 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
731 strMiscWarning = pszMessage;
742 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
744 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
746 char pszPath[MAX_PATH+100] = "";
748 // SHGetSpecialFolderPath isn't always available on old Windows versions
749 HMODULE hShell32 = LoadLibraryA("shell32.dll");
752 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
753 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
754 bool fSuccess = false;
755 if (pSHGetSpecialFolderPath)
757 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
758 FreeModule(hShell32);
767 if (nFolder == CSIDL_STARTUP)
769 pszEnv = getenv("USERPROFILE");
772 strPath += "\\Start Menu\\Programs\\Startup";
774 else if (nFolder == CSIDL_APPDATA)
776 pszEnv = getenv("APPDATA");
786 string GetDefaultDataDir()
788 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
789 // Mac: ~/Library/Application Support/Bitcoin
793 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
795 char* pszHome = getenv("HOME");
796 if (pszHome == NULL || strlen(pszHome) == 0)
797 pszHome = (char*)"/";
798 string strHome = pszHome;
799 if (strHome[strHome.size()-1] != '/')
803 strHome += "Library/Application Support/";
804 filesystem::create_directory(strHome.c_str());
805 return strHome + "Bitcoin";
808 return strHome + ".bitcoin";
813 void GetDataDir(char* pszDir)
815 // pszDir must be at least MAX_PATH length.
817 if (pszSetDataDir[0] != 0)
819 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
824 // This can be called during exceptions by printf, so we cache the
825 // value so we don't have to do memory allocations after that.
826 static char pszCachedDir[MAX_PATH];
827 if (pszCachedDir[0] == 0)
828 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
829 strlcpy(pszDir, pszCachedDir, MAX_PATH);
834 char* p = pszDir + strlen(pszDir);
835 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
837 strcpy(p, "testnet");
840 static bool pfMkdir[4];
841 if (!pfMkdir[nVariation])
843 pfMkdir[nVariation] = true;
844 boost::filesystem::create_directory(pszDir);
850 char pszDir[MAX_PATH];
855 string GetConfigFile()
857 namespace fs = boost::filesystem;
858 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
859 if (!pathConfig.is_complete())
860 pathConfig = fs::path(GetDataDir()) / pathConfig;
861 return pathConfig.string();
864 void ReadConfigFile(map<string, string>& mapSettingsRet,
865 map<string, vector<string> >& mapMultiSettingsRet)
867 namespace fs = boost::filesystem;
868 namespace pod = boost::program_options::detail;
870 fs::ifstream streamConfig(GetConfigFile());
871 if (!streamConfig.good())
874 set<string> setOptions;
875 setOptions.insert("*");
877 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
879 // Don't overwrite existing settings so command line settings override bitcoin.conf
880 string strKey = string("-") + it->string_key;
881 if (mapSettingsRet.count(strKey) == 0)
882 mapSettingsRet[strKey] = it->value[0];
883 mapMultiSettingsRet[strKey].push_back(it->value[0]);
889 namespace fs = boost::filesystem;
890 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
891 if (!pathConfig.is_complete())
892 pathConfig = fs::path(GetDataDir()) / pathConfig;
893 return pathConfig.string();
896 void CreatePidFile(string pidFile, pid_t pid)
898 FILE* file = fopen(pidFile.c_str(), "w");
901 fprintf(file, "%d\n", pid);
906 int GetFilesize(FILE* file)
908 int nSavePos = ftell(file);
910 if (fseek(file, 0, SEEK_END) == 0)
911 nFilesize = ftell(file);
912 fseek(file, nSavePos, SEEK_SET);
916 void ShrinkDebugFile()
918 // Scroll debug.log if it's getting too big
919 string strFile = GetDataDir() + "/debug.log";
920 FILE* file = fopen(strFile.c_str(), "r");
921 if (file && GetFilesize(file) > 10 * 1000000)
923 // Restart the file with some of the end
925 fseek(file, -sizeof(pch), SEEK_END);
926 int nBytes = fread(pch, 1, sizeof(pch), file);
929 file = fopen(strFile.c_str(), "w");
932 fwrite(pch, 1, nBytes, file);
946 // "Never go to sea with two chronometers; take one or three."
947 // Our three time sources are:
949 // - Median of other nodes's clocks
950 // - The user (asking the user to fix the system clock if the first two disagree)
952 static int64 nMockTime = 0; // For unit testing
956 if (nMockTime) return nMockTime;
961 void SetMockTime(int64 nMockTimeIn)
963 nMockTime = nMockTimeIn;
966 static int64 nTimeOffset = 0;
968 int64 GetAdjustedTime()
970 return GetTime() + nTimeOffset;
973 void AddTimeData(unsigned int ip, int64 nTime)
975 int64 nOffsetSample = nTime - GetTime();
978 static set<unsigned int> setKnown;
979 if (!setKnown.insert(ip).second)
983 static vector<int64> vTimeOffsets;
984 if (vTimeOffsets.empty())
985 vTimeOffsets.push_back(0);
986 vTimeOffsets.push_back(nOffsetSample);
987 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
988 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
990 sort(vTimeOffsets.begin(), vTimeOffsets.end());
991 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
992 // Only let other nodes change our time by so much
993 if (abs64(nMedian) < 70 * 60)
995 nTimeOffset = nMedian;
1004 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1005 bool fMatch = false;
1006 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
1007 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1013 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1014 strMiscWarning = strMessage;
1015 printf("*** %s\n", strMessage.c_str());
1016 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
1020 BOOST_FOREACH(int64 n, vTimeOffsets)
1021 printf("%+"PRI64d" ", n);
1022 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1034 string FormatVersion(int nVersion)
1036 if (nVersion%100 == 0)
1037 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1039 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1042 string FormatFullVersion()
1044 string s = FormatVersion(VERSION) + pszSubVer;
1045 if (VERSION_IS_BETA) {
1055 #ifdef DEBUG_LOCKORDER
1057 // Early deadlock detection.
1058 // Problem being solved:
1059 // Thread 1 locks A, then B, then C
1060 // Thread 2 locks D, then C, then A
1061 // --> may result in deadlock between the two threads, depending on when they run.
1062 // Solution implemented here:
1063 // Keep track of pairs of locks: (A before B), (A before C), etc.
1064 // Complain if any thread trys to lock in a different order.
1067 struct CLockLocation
1069 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1071 mutexName = pszName;
1072 sourceFile = pszFile;
1076 std::string ToString() const
1078 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1082 std::string mutexName;
1083 std::string sourceFile;
1087 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1089 static boost::interprocess::interprocess_mutex dd_mutex;
1090 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1091 static boost::thread_specific_ptr<LockStack> lockstack;
1094 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1096 printf("POTENTIAL DEADLOCK DETECTED\n");
1097 printf("Previous lock order was:\n");
1098 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1100 if (i.first == mismatch.first) printf(" (1)");
1101 if (i.first == mismatch.second) printf(" (2)");
1102 printf(" %s\n", i.second.ToString().c_str());
1104 printf("Current lock order is:\n");
1105 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1107 if (i.first == mismatch.first) printf(" (1)");
1108 if (i.first == mismatch.second) printf(" (2)");
1109 printf(" %s\n", i.second.ToString().c_str());
1113 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1115 bool fOrderOK = true;
1116 if (lockstack.get() == NULL)
1117 lockstack.reset(new LockStack);
1119 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1122 (*lockstack).push_back(std::make_pair(c, locklocation));
1124 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1126 if (i.first == c) break;
1128 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1129 if (lockorders.count(p1))
1131 lockorders[p1] = (*lockstack);
1133 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1134 if (lockorders.count(p2))
1136 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1143 static void pop_lock()
1147 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1148 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1151 (*lockstack).pop_back();
1155 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1157 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1160 void CCriticalSection::Leave()
1165 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1167 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1168 bool result = mutex.try_lock();
1169 if (!result) pop_lock();
1175 void CCriticalSection::Enter(const char*, const char*, int)
1180 void CCriticalSection::Leave()
1185 bool CCriticalSection::TryEnter(const char*, const char*, int)
1187 bool result = mutex.try_lock();
1191 #endif /* DEBUG_LOCKORDER */