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 license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/program_options/detail/config_file.hpp>
8 #include <boost/program_options/parsers.hpp>
9 #include <boost/filesystem.hpp>
10 #include <boost/filesystem/fstream.hpp>
11 #include <boost/interprocess/sync/interprocess_mutex.hpp>
12 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
13 #include <boost/foreach.hpp>
16 using namespace boost;
18 map<string, string> mapArgs;
19 map<string, vector<string> > mapMultiArgs;
21 bool fPrintToConsole = false;
22 bool fPrintToDebugger = false;
23 char pszSetDataDir[MAX_PATH] = "";
24 bool fRequestShutdown = false;
25 bool fShutdown = false;
28 bool fCommandLine = false;
29 string strMiscWarning;
30 bool fTestNet = false;
31 bool fNoListen = false;
32 bool fLogTimestamps = false;
37 // Workaround for "multiple definition of `_tls_used'"
38 // http://svn.boost.org/trac/boost/ticket/4258
39 extern "C" void tss_cleanup_implemented() { }
45 // Init openssl library multithreading support
46 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
47 void locking_callback(int mode, int i, const char* file, int line)
49 if (mode & CRYPTO_LOCK)
50 ppmutexOpenSSL[i]->lock();
52 ppmutexOpenSSL[i]->unlock();
61 // Init openssl library multithreading support
62 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
63 for (int i = 0; i < CRYPTO_num_locks(); i++)
64 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
65 CRYPTO_set_locking_callback(locking_callback);
68 // Seed random number generator with screen scrape and other hardware sources
72 // Seed random number generator with performance counter
77 // Shutdown openssl library multithreading support
78 CRYPTO_set_locking_callback(NULL);
79 for (int i = 0; i < CRYPTO_num_locks(); i++)
80 delete ppmutexOpenSSL[i];
81 OPENSSL_free(ppmutexOpenSSL);
95 // Seed with CPU performance counter
96 int64 nCounter = GetPerformanceCounter();
97 RAND_add(&nCounter, sizeof(nCounter), 1.5);
98 memset(&nCounter, 0, sizeof(nCounter));
101 void RandAddSeedPerfmon()
105 // This can take up to 2 seconds, so only do it every 10 minutes
106 static int64 nLastPerfmon;
107 if (GetTime() < nLastPerfmon + 10 * 60)
109 nLastPerfmon = GetTime();
112 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
113 // Seed with the entire set of perfmon data
114 unsigned char pdata[250000];
115 memset(pdata, 0, sizeof(pdata));
116 unsigned long nSize = sizeof(pdata);
117 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
118 RegCloseKey(HKEY_PERFORMANCE_DATA);
119 if (ret == ERROR_SUCCESS)
121 RAND_add(pdata, nSize, nSize/100.0);
122 memset(pdata, 0, nSize);
123 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
128 uint64 GetRand(uint64 nMax)
133 // The range of the random source must be a multiple of the modulus
134 // to give every possible output value an equal possibility
135 uint64 nRange = (UINT64_MAX / nMax) * nMax;
138 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
139 while (nRand >= nRange);
140 return (nRand % nMax);
143 int GetRandInt(int nMax)
145 return GetRand(nMax);
158 inline int OutputDebugStringF(const char* pszFormat, ...)
165 va_start(arg_ptr, pszFormat);
166 ret = vprintf(pszFormat, arg_ptr);
171 // print to debug.log
172 static FILE* fileout = NULL;
176 char pszFile[MAX_PATH+100];
178 strlcat(pszFile, "/debug.log", sizeof(pszFile));
179 fileout = fopen(pszFile, "a");
180 if (fileout) setbuf(fileout, NULL); // unbuffered
184 static bool fStartedNewLine = true;
186 // Debug print useful for profiling
187 if (fLogTimestamps && fStartedNewLine)
188 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
189 if (pszFormat[strlen(pszFormat) - 1] == '\n')
190 fStartedNewLine = true;
192 fStartedNewLine = false;
195 va_start(arg_ptr, pszFormat);
196 ret = vfprintf(fileout, pszFormat, arg_ptr);
202 if (fPrintToDebugger)
204 static CCriticalSection cs_OutputDebugStringF;
206 // accumulate a line at a time
207 CRITICAL_BLOCK(cs_OutputDebugStringF)
209 static char pszBuffer[50000];
214 va_start(arg_ptr, pszFormat);
215 int limit = END(pszBuffer) - pend - 2;
216 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
218 if (ret < 0 || ret >= limit)
220 pend = END(pszBuffer) - 2;
226 char* p1 = pszBuffer;
228 while (p2 = strchr(p1, '\n'))
233 OutputDebugStringA(p1);
238 memmove(pszBuffer, p1, pend - p1 + 1);
239 pend -= (p1 - pszBuffer);
248 // - prints up to limit-1 characters
249 // - output string is always null terminated even if limit reached
250 // - return value is the number of characters actually printed
251 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
256 va_start(arg_ptr, format);
257 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
259 if (ret < 0 || ret >= limit)
267 string strprintf(const std::string &format, ...)
271 int limit = sizeof(buffer);
276 va_start(arg_ptr, format);
277 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
279 if (ret >= 0 && ret < limit)
286 throw std::bad_alloc();
288 string str(p, p+ret);
294 bool error(const std::string &format, ...)
297 int limit = sizeof(buffer);
299 va_start(arg_ptr, format);
300 int ret = _vsnprintf(buffer, limit, format.c_str(), 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);
349 str.insert((unsigned int)0, 1, '-');
350 else if (fPlus && n > 0)
351 str.insert((unsigned int)0, 1, '+');
356 bool ParseMoney(const string& str, int64& nRet)
358 return ParseMoney(str.c_str(), nRet);
361 bool ParseMoney(const char* pszIn, int64& nRet)
365 const char* p = pszIn;
373 int64 nMult = CENT*10;
374 while (isdigit(*p) && (nMult > 0))
376 nUnits += nMult * (*p++ - '0');
385 strWhole.insert(strWhole.end(), *p);
390 if (strWhole.size() > 10) // guard against 63 bit overflow
392 if (nUnits < 0 || nUnits > COIN)
394 int64 nWhole = atoi64(strWhole);
395 int64 nValue = nWhole*COIN + nUnits;
402 vector<unsigned char> ParseHex(const char* psz)
404 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
409 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
410 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,
420 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
422 // convert hex dump to vector
423 vector<unsigned char> vch;
426 while (isspace(*psz))
428 char c = phexdigit[(unsigned char)*psz++];
431 unsigned char n = (c << 4);
432 c = phexdigit[(unsigned char)*psz++];
441 vector<unsigned char> ParseHex(const string& str)
443 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);
472 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
474 if (mapArgs.count(strArg))
476 mapArgs[strArg] = strValue;
480 bool SoftSetArg(const std::string& strArg, bool fValue)
483 return SoftSetArg(strArg, std::string("1"));
485 return SoftSetArg(strArg, std::string("0"));
489 string EncodeBase64(const unsigned char* pch, size_t len)
491 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
494 strRet.reserve((len+2)/3*4);
497 const unsigned char *pchEnd = pch+len;
504 case 0: // we have no bits
505 strRet += pbase64[enc >> 2];
506 left = (enc & 3) << 4;
510 case 1: // we have two bits
511 strRet += pbase64[left | (enc >> 4)];
512 left = (enc & 15) << 2;
516 case 2: // we have four bits
517 strRet += pbase64[left | (enc >> 6)];
518 strRet += pbase64[enc & 63];
526 strRet += pbase64[left];
535 string EncodeBase64(const string& str)
537 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
540 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
542 static const int decode64_table[256] =
544 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
545 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
546 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
547 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
548 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
549 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
550 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
551 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
552 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
553 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
554 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
555 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
556 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
562 vector<unsigned char> vchRet;
563 vchRet.reserve(strlen(p)*3/4);
570 int dec = decode64_table[*p];
571 if (dec == -1) break;
575 case 0: // we have no bits and get 6
580 case 1: // we have 6 bits and keep 4
581 vchRet.push_back((left<<2) | (dec>>4));
586 case 2: // we have 4 bits and get 6, we keep 2
587 vchRet.push_back((left<<4) | (dec>>2));
592 case 3: // we have 2 bits and get 6
593 vchRet.push_back((left<<6) | dec);
602 case 0: // 4n base64 characters processed: ok
605 case 1: // 4n+1 base64 character processed: impossible
609 case 2: // 4n+2 base64 characters processed: require '=='
610 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
614 case 3: // 4n+3 base64 characters processed: require '='
615 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
623 string DecodeBase64(const string& str)
625 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
626 return string((const char*)&vchRet[0], vchRet.size());
630 bool WildcardMatch(const char* psz, const char* mask)
637 return (*psz == '\0');
639 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
654 bool WildcardMatch(const string& str, const string& mask)
656 return WildcardMatch(str.c_str(), mask.c_str());
666 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
669 char pszModule[MAX_PATH];
671 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
673 const char* pszModule = "bitcoin";
676 snprintf(pszMessage, 1000,
677 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
679 snprintf(pszMessage, 1000,
680 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
683 void LogException(std::exception* pex, const char* pszThread)
685 char pszMessage[10000];
686 FormatException(pszMessage, pex, pszThread);
687 printf("\n%s", pszMessage);
690 void PrintException(std::exception* pex, const char* pszThread)
692 char pszMessage[10000];
693 FormatException(pszMessage, pex, pszThread);
694 printf("\n\n************************\n%s\n", pszMessage);
695 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
696 strMiscWarning = pszMessage;
700 void ThreadOneMessageBox(string strMessage)
702 // Skip message boxes if one is already open
703 static bool fMessageBoxOpen;
706 fMessageBoxOpen = true;
707 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
708 fMessageBoxOpen = false;
711 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
713 char pszMessage[10000];
714 FormatException(pszMessage, pex, pszThread);
715 printf("\n\n************************\n%s\n", pszMessage);
716 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
717 strMiscWarning = pszMessage;
728 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
730 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
732 char pszPath[MAX_PATH+100] = "";
734 // SHGetSpecialFolderPath isn't always available on old Windows versions
735 HMODULE hShell32 = LoadLibraryA("shell32.dll");
738 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
739 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
740 if (pSHGetSpecialFolderPath)
741 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
742 FreeModule(hShell32);
746 if (pszPath[0] == '\0')
748 if (nFolder == CSIDL_STARTUP)
750 strcpy(pszPath, getenv("USERPROFILE"));
751 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
753 else if (nFolder == CSIDL_APPDATA)
755 strcpy(pszPath, getenv("APPDATA"));
763 string GetDefaultDataDir()
765 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
766 // Mac: ~/Library/Application Support/Bitcoin
770 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
772 char* pszHome = getenv("HOME");
773 if (pszHome == NULL || strlen(pszHome) == 0)
774 pszHome = (char*)"/";
775 string strHome = pszHome;
776 if (strHome[strHome.size()-1] != '/')
780 strHome += "Library/Application Support/";
781 filesystem::create_directory(strHome.c_str());
782 return strHome + "Bitcoin";
785 return strHome + ".bitcoin";
790 void GetDataDir(char* pszDir)
792 // pszDir must be at least MAX_PATH length.
794 if (pszSetDataDir[0] != 0)
796 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
801 // This can be called during exceptions by printf, so we cache the
802 // value so we don't have to do memory allocations after that.
803 static char pszCachedDir[MAX_PATH];
804 if (pszCachedDir[0] == 0)
805 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
806 strlcpy(pszDir, pszCachedDir, MAX_PATH);
811 char* p = pszDir + strlen(pszDir);
812 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
814 strcpy(p, "testnet");
817 static bool pfMkdir[4];
818 if (!pfMkdir[nVariation])
820 pfMkdir[nVariation] = true;
821 boost::filesystem::create_directory(pszDir);
827 char pszDir[MAX_PATH];
832 string GetConfigFile()
834 namespace fs = boost::filesystem;
835 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
836 if (!pathConfig.is_complete())
837 pathConfig = fs::path(GetDataDir()) / pathConfig;
838 return pathConfig.string();
841 void ReadConfigFile(map<string, string>& mapSettingsRet,
842 map<string, vector<string> >& mapMultiSettingsRet)
844 namespace fs = boost::filesystem;
845 namespace pod = boost::program_options::detail;
847 fs::ifstream streamConfig(GetConfigFile());
848 if (!streamConfig.good())
851 set<string> setOptions;
852 setOptions.insert("*");
854 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
856 // Don't overwrite existing settings so command line settings override bitcoin.conf
857 string strKey = string("-") + it->string_key;
858 if (mapSettingsRet.count(strKey) == 0)
859 mapSettingsRet[strKey] = it->value[0];
860 mapMultiSettingsRet[strKey].push_back(it->value[0]);
866 namespace fs = boost::filesystem;
867 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
868 if (!pathConfig.is_complete())
869 pathConfig = fs::path(GetDataDir()) / pathConfig;
870 return pathConfig.string();
873 void CreatePidFile(string pidFile, pid_t pid)
875 FILE* file = fopen(pidFile.c_str(), "w");
878 fprintf(file, "%d\n", pid);
883 int GetFilesize(FILE* file)
885 int nSavePos = ftell(file);
887 if (fseek(file, 0, SEEK_END) == 0)
888 nFilesize = ftell(file);
889 fseek(file, nSavePos, SEEK_SET);
893 void ShrinkDebugFile()
895 // Scroll debug.log if it's getting too big
896 string strFile = GetDataDir() + "/debug.log";
897 FILE* file = fopen(strFile.c_str(), "r");
898 if (file && GetFilesize(file) > 10 * 1000000)
900 // Restart the file with some of the end
902 fseek(file, -sizeof(pch), SEEK_END);
903 int nBytes = fread(pch, 1, sizeof(pch), file);
906 file = fopen(strFile.c_str(), "w");
909 fwrite(pch, 1, nBytes, file);
923 // "Never go to sea with two chronometers; take one or three."
924 // Our three time sources are:
926 // - Median of other nodes's clocks
927 // - The user (asking the user to fix the system clock if the first two disagree)
929 static int64 nMockTime = 0; // For unit testing
933 if (nMockTime) return nMockTime;
938 void SetMockTime(int64 nMockTimeIn)
940 nMockTime = nMockTimeIn;
943 static int64 nTimeOffset = 0;
945 int64 GetAdjustedTime()
947 return GetTime() + nTimeOffset;
950 void AddTimeData(unsigned int ip, int64 nTime)
952 int64 nOffsetSample = nTime - GetTime();
955 static set<unsigned int> setKnown;
956 if (!setKnown.insert(ip).second)
960 static vector<int64> vTimeOffsets;
961 if (vTimeOffsets.empty())
962 vTimeOffsets.push_back(0);
963 vTimeOffsets.push_back(nOffsetSample);
964 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
965 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
967 sort(vTimeOffsets.begin(), vTimeOffsets.end());
968 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
969 // Only let other nodes change our time by so much
970 if (abs64(nMedian) < 70 * 60)
972 nTimeOffset = nMedian;
981 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
983 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
984 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
990 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
991 strMiscWarning = strMessage;
992 printf("*** %s\n", strMessage.c_str());
993 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
997 BOOST_FOREACH(int64 n, vTimeOffsets)
998 printf("%+"PRI64d" ", n);
999 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1011 string FormatVersion(int nVersion)
1013 if (nVersion%100 == 0)
1014 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1016 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1019 string FormatFullVersion()
1021 string s = FormatVersion(VERSION) + pszSubVer;
1022 if (VERSION_IS_BETA) {
1032 #ifdef DEBUG_LOCKORDER
1034 // Early deadlock detection.
1035 // Problem being solved:
1036 // Thread 1 locks A, then B, then C
1037 // Thread 2 locks D, then C, then A
1038 // --> may result in deadlock between the two threads, depending on when they run.
1039 // Solution implemented here:
1040 // Keep track of pairs of locks: (A before B), (A before C), etc.
1041 // Complain if any thread trys to lock in a different order.
1044 struct CLockLocation
1046 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1048 mutexName = pszName;
1049 sourceFile = pszFile;
1053 std::string ToString() const
1055 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1059 std::string mutexName;
1060 std::string sourceFile;
1064 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1066 static boost::interprocess::interprocess_mutex dd_mutex;
1067 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1068 static boost::thread_specific_ptr<LockStack> lockstack;
1071 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1073 printf("POTENTIAL DEADLOCK DETECTED\n");
1074 printf("Previous lock order was:\n");
1075 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1077 if (i.first == mismatch.first) printf(" (1)");
1078 if (i.first == mismatch.second) printf(" (2)");
1079 printf(" %s\n", i.second.ToString().c_str());
1081 printf("Current lock order is:\n");
1082 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1084 if (i.first == mismatch.first) printf(" (1)");
1085 if (i.first == mismatch.second) printf(" (2)");
1086 printf(" %s\n", i.second.ToString().c_str());
1090 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1092 bool fOrderOK = true;
1093 if (lockstack.get() == NULL)
1094 lockstack.reset(new LockStack);
1096 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1099 (*lockstack).push_back(std::make_pair(c, locklocation));
1101 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1103 if (i.first == c) break;
1105 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1106 if (lockorders.count(p1))
1108 lockorders[p1] = (*lockstack);
1110 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1111 if (lockorders.count(p2))
1113 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1120 static void pop_lock()
1124 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1125 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1128 (*lockstack).pop_back();
1132 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1134 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1137 void CCriticalSection::Leave()
1142 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1144 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1145 bool result = mutex.try_lock();
1146 if (!result) pop_lock();
1152 void CCriticalSection::Enter(const char*, const char*, int)
1157 void CCriticalSection::Leave()
1162 bool CCriticalSection::TryEnter(const char*, const char*, int)
1164 bool result = mutex.try_lock();
1168 #endif /* DEBUG_LOCKORDER */