1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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.
10 #include <boost/algorithm/string/join.hpp>
11 #include <boost/program_options/detail/config_file.hpp>
12 #include <boost/program_options/parsers.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15 #include <boost/interprocess/sync/interprocess_mutex.hpp>
16 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
17 #include <boost/foreach.hpp>
20 using namespace boost;
22 map<string, string> mapArgs;
23 map<string, vector<string> > mapMultiArgs;
25 bool fPrintToConsole = false;
26 bool fPrintToDebugger = false;
27 char pszSetDataDir[MAX_PATH] = "";
28 bool fRequestShutdown = false;
29 bool fShutdown = false;
32 bool fCommandLine = false;
33 string strMiscWarning;
34 bool fTestNet = false;
35 bool fNoListen = false;
36 bool fLogTimestamps = false;
37 CMedianFilter<int64_t> vTimeOffsets(200,0);
41 // Workaround for "multiple definition of `_tls_used'"
42 // http://svn.boost.org/trac/boost/ticket/4258
43 extern "C" void tss_cleanup_implemented() { }
49 // Init openssl library multithreading support
50 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
51 void locking_callback(int mode, int i, const char* file, int line)
53 if (mode & CRYPTO_LOCK)
54 ppmutexOpenSSL[i]->lock();
56 ppmutexOpenSSL[i]->unlock();
65 // Init openssl library multithreading support
66 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
67 for (int i = 0; i < CRYPTO_num_locks(); i++)
68 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
69 CRYPTO_set_locking_callback(locking_callback);
72 // Seed random number generator with screen scrape and other hardware sources
76 // Seed random number generator with performance counter
81 // Shutdown openssl library multithreading support
82 CRYPTO_set_locking_callback(NULL);
83 for (int i = 0; i < CRYPTO_num_locks(); i++)
84 delete ppmutexOpenSSL[i];
85 OPENSSL_free(ppmutexOpenSSL);
99 // Seed with CPU performance counter
100 int64_t nCounter = GetPerformanceCounter();
101 RAND_add(&nCounter, sizeof(nCounter), 1.5);
102 memset(&nCounter, 0, sizeof(nCounter));
105 void RandAddSeedPerfmon()
109 // This can take up to 2 seconds, so only do it every 10 minutes
110 static int64_t nLastPerfmon;
111 if (GetTime() < nLastPerfmon + 10 * 60)
113 nLastPerfmon = GetTime();
116 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
117 // Seed with the entire set of perfmon data
118 unsigned char pdata[250000];
119 memset(pdata, 0, sizeof(pdata));
120 unsigned long nSize = sizeof(pdata);
121 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
122 RegCloseKey(HKEY_PERFORMANCE_DATA);
123 if (ret == ERROR_SUCCESS)
125 RAND_add(pdata, nSize, nSize/100.0);
126 memset(pdata, 0, nSize);
127 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
132 uint64_t GetRand(uint64_t nMax)
137 // The range of the random source must be a multiple of the modulus
138 // to give every possible output value an equal possibility
139 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
142 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
143 while (nRand >= nRange);
144 return (nRand % nMax);
147 int GetRandInt(int nMax)
149 return GetRand(nMax);
162 inline int OutputDebugStringF(const char* pszFormat, ...)
169 va_start(arg_ptr, pszFormat);
170 ret = vprintf(pszFormat, arg_ptr);
175 // print to debug.log
176 static FILE* fileout = NULL;
180 char pszFile[MAX_PATH+100];
182 strlcat(pszFile, "/debug.log", sizeof(pszFile));
183 fileout = fopen(pszFile, "a");
184 if (fileout) setbuf(fileout, NULL); // unbuffered
188 static bool fStartedNewLine = true;
190 // Debug print useful for profiling
191 if (fLogTimestamps && fStartedNewLine)
192 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
193 if (pszFormat[strlen(pszFormat) - 1] == '\n')
194 fStartedNewLine = true;
196 fStartedNewLine = false;
199 va_start(arg_ptr, pszFormat);
200 ret = vfprintf(fileout, pszFormat, arg_ptr);
206 if (fPrintToDebugger)
208 static CCriticalSection cs_OutputDebugStringF;
210 // accumulate a line at a time
211 CRITICAL_BLOCK(cs_OutputDebugStringF)
213 static char pszBuffer[50000];
218 va_start(arg_ptr, pszFormat);
219 int limit = END(pszBuffer) - pend - 2;
220 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
222 if (ret < 0 || ret >= limit)
224 pend = END(pszBuffer) - 2;
230 char* p1 = pszBuffer;
232 while (p2 = strchr(p1, '\n'))
237 OutputDebugStringA(p1);
242 memmove(pszBuffer, p1, pend - p1 + 1);
243 pend -= (p1 - pszBuffer);
252 // - prints up to limit-1 characters
253 // - output string is always null terminated even if limit reached
254 // - return value is the number of characters actually printed
255 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
260 va_start(arg_ptr, format);
261 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
263 if (ret < 0 || ret >= limit)
271 string strprintf(const std::string &format, ...)
275 int limit = sizeof(buffer);
280 va_start(arg_ptr, format);
281 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
283 if (ret >= 0 && ret < limit)
290 throw std::bad_alloc();
292 string str(p, p+ret);
298 bool error(const std::string &format, ...)
301 int limit = sizeof(buffer);
303 va_start(arg_ptr, format);
304 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
306 if (ret < 0 || ret >= limit)
311 printf("ERROR: %s\n", buffer);
316 void ParseString(const string& str, char c, vector<string>& v)
320 string::size_type i1 = 0;
321 string::size_type i2;
324 i2 = str.find(c, i1);
327 v.push_back(str.substr(i1));
330 v.push_back(str.substr(i1, i2-i1));
336 string FormatMoney(int64_t n, bool fPlus)
338 // Note: not using straight sprintf here because we do NOT want
339 // localized number formatting.
340 int64_t n_abs = (n > 0 ? n : -n);
341 int64_t quotient = n_abs/COIN;
342 int64_t remainder = n_abs%COIN;
343 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
345 // Right-trim excess 0's before the decimal point:
347 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
350 str.erase(str.size()-nTrim, nTrim);
353 str.insert((unsigned int)0, 1, '-');
354 else if (fPlus && n > 0)
355 str.insert((unsigned int)0, 1, '+');
360 bool ParseMoney(const string& str, int64_t& nRet)
362 return ParseMoney(str.c_str(), nRet);
365 bool ParseMoney(const char* pszIn, int64_t& nRet)
369 const char* p = pszIn;
377 int64_t nMult = CENT*10;
378 while (isdigit(*p) && (nMult > 0))
380 nUnits += nMult * (*p++ - '0');
389 strWhole.insert(strWhole.end(), *p);
394 if (strWhole.size() > 10) // guard against 63 bit overflow
396 if (nUnits < 0 || nUnits > COIN)
398 int64_t nWhole = atoi64(strWhole);
399 int64_t nValue = nWhole*COIN + nUnits;
406 vector<unsigned char> ParseHex(const char* psz)
408 static char phexdigit[256] =
409 { -1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
412 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
413 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
421 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
422 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
423 -1,-1,-1,-1,-1,-1,-1,-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, };
426 // convert hex dump to vector
427 vector<unsigned char> vch;
430 while (isspace(*psz))
432 char c = phexdigit[(unsigned char)*psz++];
435 unsigned char n = (c << 4);
436 c = phexdigit[(unsigned char)*psz++];
445 vector<unsigned char> ParseHex(const string& str)
447 return ParseHex(str.c_str());
450 void ParseParameters(int argc, char* argv[])
453 mapMultiArgs.clear();
454 for (int i = 1; i < argc; i++)
457 strlcpy(psz, argv[i], sizeof(psz));
458 char* pszValue = (char*)"";
459 if (strchr(psz, '='))
461 pszValue = strchr(psz, '=');
471 mapArgs[psz] = pszValue;
472 mapMultiArgs[psz].push_back(pszValue);
476 string EncodeBase64(const unsigned char* pch, size_t len)
478 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
481 strRet.reserve((len+2)/3*4);
484 const unsigned char *pchEnd = pch+len;
491 case 0: // we have no bits
492 strRet += pbase64[enc >> 2];
493 left = (enc & 3) << 4;
497 case 1: // we have two bits
498 strRet += pbase64[left | (enc >> 4)];
499 left = (enc & 15) << 2;
503 case 2: // we have four bits
504 strRet += pbase64[left | (enc >> 6)];
505 strRet += pbase64[enc & 63];
513 strRet += pbase64[left];
522 string EncodeBase64(const string& str)
524 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
527 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
529 static const int decode64_table[256] =
531 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
532 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
533 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
534 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
535 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
536 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
537 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
538 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
539 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
540 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
541 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
542 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
543 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
549 vector<unsigned char> vchRet;
550 vchRet.reserve(strlen(p)*3/4);
557 int dec = decode64_table[*p];
558 if (dec == -1) break;
562 case 0: // we have no bits and get 6
567 case 1: // we have 6 bits and keep 4
568 vchRet.push_back((left<<2) | (dec>>4));
573 case 2: // we have 4 bits and get 6, we keep 2
574 vchRet.push_back((left<<4) | (dec>>2));
579 case 3: // we have 2 bits and get 6
580 vchRet.push_back((left<<6) | dec);
589 case 0: // 4n base64 characters processed: ok
592 case 1: // 4n+1 base64 character processed: impossible
596 case 2: // 4n+2 base64 characters processed: require '=='
597 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
601 case 3: // 4n+3 base64 characters processed: require '='
602 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
610 string DecodeBase64(const string& str)
612 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
613 return string((const char*)&vchRet[0], vchRet.size());
617 bool WildcardMatch(const char* psz, const char* mask)
624 return (*psz == '\0');
626 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
641 bool WildcardMatch(const string& str, const string& mask)
643 return WildcardMatch(str.c_str(), mask.c_str());
653 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
656 char pszModule[MAX_PATH];
658 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
660 const char* pszModule = "bitcoin";
663 snprintf(pszMessage, 1000,
664 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
666 snprintf(pszMessage, 1000,
667 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
670 void LogException(std::exception* pex, const char* pszThread)
672 char pszMessage[10000];
673 FormatException(pszMessage, pex, pszThread);
674 printf("\n%s", pszMessage);
677 void PrintException(std::exception* pex, const char* pszThread)
679 char pszMessage[10000];
680 FormatException(pszMessage, pex, pszThread);
681 printf("\n\n************************\n%s\n", pszMessage);
682 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
683 strMiscWarning = pszMessage;
687 void ThreadOneMessageBox(string strMessage)
689 // Skip message boxes if one is already open
690 static bool fMessageBoxOpen;
693 fMessageBoxOpen = true;
694 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
695 fMessageBoxOpen = false;
698 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
700 char pszMessage[10000];
701 FormatException(pszMessage, pex, pszThread);
702 printf("\n\n************************\n%s\n", pszMessage);
703 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
704 strMiscWarning = pszMessage;
715 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
717 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
719 char pszPath[MAX_PATH+100] = "";
721 // SHGetSpecialFolderPath isn't always available on old Windows versions
722 HMODULE hShell32 = LoadLibraryA("shell32.dll");
725 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
726 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
727 if (pSHGetSpecialFolderPath)
728 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
729 FreeModule(hShell32);
733 if (pszPath[0] == '\0')
735 if (nFolder == CSIDL_STARTUP)
737 strcpy(pszPath, getenv("USERPROFILE"));
738 strcat(pszPath, "\\Start Menu\\Programs\\Startup");
740 else if (nFolder == CSIDL_APPDATA)
742 strcpy(pszPath, getenv("APPDATA"));
750 string GetDefaultDataDir()
752 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
753 // Mac: ~/Library/Application Support/Bitcoin
757 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
759 char* pszHome = getenv("HOME");
760 if (pszHome == NULL || strlen(pszHome) == 0)
761 pszHome = (char*)"/";
762 string strHome = pszHome;
763 if (strHome[strHome.size()-1] != '/')
767 strHome += "Library/Application Support/";
768 filesystem::create_directory(strHome.c_str());
769 return strHome + "Bitcoin";
772 return strHome + ".bitcoin";
777 void GetDataDir(char* pszDir)
779 // pszDir must be at least MAX_PATH length.
781 if (pszSetDataDir[0] != 0)
783 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
788 // This can be called during exceptions by printf, so we cache the
789 // value so we don't have to do memory allocations after that.
790 static char pszCachedDir[MAX_PATH];
791 if (pszCachedDir[0] == 0)
792 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
793 strlcpy(pszDir, pszCachedDir, MAX_PATH);
798 char* p = pszDir + strlen(pszDir);
799 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
801 strcpy(p, "testnet");
804 static bool pfMkdir[4];
805 if (!pfMkdir[nVariation])
807 pfMkdir[nVariation] = true;
808 boost::filesystem::create_directory(pszDir);
814 char pszDir[MAX_PATH];
819 string GetConfigFile()
821 namespace fs = boost::filesystem;
822 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
823 if (!pathConfig.is_complete())
824 pathConfig = fs::path(GetDataDir()) / pathConfig;
825 return pathConfig.string();
828 void ReadConfigFile(map<string, string>& mapSettingsRet,
829 map<string, vector<string> >& mapMultiSettingsRet)
831 namespace fs = boost::filesystem;
832 namespace pod = boost::program_options::detail;
834 fs::ifstream streamConfig(GetConfigFile());
835 if (!streamConfig.good())
838 set<string> setOptions;
839 setOptions.insert("*");
841 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
843 // Don't overwrite existing settings so command line settings override bitcoin.conf
844 string strKey = string("-") + it->string_key;
845 if (mapSettingsRet.count(strKey) == 0)
846 mapSettingsRet[strKey] = it->value[0];
847 mapMultiSettingsRet[strKey].push_back(it->value[0]);
853 namespace fs = boost::filesystem;
854 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
855 if (!pathConfig.is_complete())
856 pathConfig = fs::path(GetDataDir()) / pathConfig;
857 return pathConfig.string();
860 void CreatePidFile(string pidFile, pid_t pid)
862 FILE* file = fopen(pidFile.c_str(), "w");
865 fprintf(file, "%d\n", pid);
870 int GetFilesize(FILE* file)
872 int nSavePos = ftell(file);
874 if (fseek(file, 0, SEEK_END) == 0)
875 nFilesize = ftell(file);
876 fseek(file, nSavePos, SEEK_SET);
880 void ShrinkDebugFile()
882 // Scroll debug.log if it's getting too big
883 string strFile = GetDataDir() + "/debug.log";
884 FILE* file = fopen(strFile.c_str(), "r");
885 if (file && GetFilesize(file) > 10 * 1000000)
887 // Restart the file with some of the end
889 fseek(file, -sizeof(pch), SEEK_END);
890 int nBytes = fread(pch, 1, sizeof(pch), file);
893 file = fopen(strFile.c_str(), "w");
896 fwrite(pch, 1, nBytes, file);
910 // "Never go to sea with two chronometers; take one or three."
911 // Our three time sources are:
913 // - Median of other nodes's clocks
914 // - The user (asking the user to fix the system clock if the first two disagree)
916 static int64_t nMockTime = 0; // For unit testing
920 if (nMockTime) return nMockTime;
925 void SetMockTime(int64_t nMockTimeIn)
927 nMockTime = nMockTimeIn;
930 static int64_t nTimeOffset = 0;
932 int64_t GetAdjustedTime()
934 return GetTime() + nTimeOffset;
937 void AddTimeData(unsigned int ip, int64_t nTime)
939 int64_t nOffsetSample = nTime - GetTime();
942 static set<unsigned int> setKnown;
943 if (!setKnown.insert(ip).second)
947 vTimeOffsets.input(nOffsetSample);
948 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
949 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
951 int64_t nMedian = vTimeOffsets.median();
952 std::vector<int64_t> vSorted = vTimeOffsets.sorted();
953 // Only let other nodes change our time by so much
954 if (abs64(nMedian) < 70 * 60)
956 nTimeOffset = nMedian;
965 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
967 BOOST_FOREACH(int64_t nOffset, vSorted)
968 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
974 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
975 strMiscWarning = strMessage;
976 printf("*** %s\n", strMessage.c_str());
977 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
982 BOOST_FOREACH(int64_t n, vSorted)
983 printf("%+"PRI64d" ", n);
986 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
998 string FormatVersion(int nVersion)
1000 if (nVersion%100 == 0)
1001 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1003 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1006 string FormatFullVersion()
1008 string s = FormatVersion(CLIENT_VERSION);
1009 if (VERSION_IS_BETA) {
1016 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1017 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1019 std::ostringstream ss;
1021 ss << name << ":" << FormatVersion(nClientVersion);
1022 if (!comments.empty())
1023 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1030 #ifdef DEBUG_LOCKORDER
1032 // Early deadlock detection.
1033 // Problem being solved:
1034 // Thread 1 locks A, then B, then C
1035 // Thread 2 locks D, then C, then A
1036 // --> may result in deadlock between the two threads, depending on when they run.
1037 // Solution implemented here:
1038 // Keep track of pairs of locks: (A before B), (A before C), etc.
1039 // Complain if any thread trys to lock in a different order.
1042 struct CLockLocation
1044 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1046 mutexName = pszName;
1047 sourceFile = pszFile;
1051 std::string ToString() const
1053 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1057 std::string mutexName;
1058 std::string sourceFile;
1062 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1064 static boost::interprocess::interprocess_mutex dd_mutex;
1065 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1066 static boost::thread_specific_ptr<LockStack> lockstack;
1069 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1071 printf("POTENTIAL DEADLOCK DETECTED\n");
1072 printf("Previous lock order was:\n");
1073 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1075 if (i.first == mismatch.first) printf(" (1)");
1076 if (i.first == mismatch.second) printf(" (2)");
1077 printf(" %s\n", i.second.ToString().c_str());
1079 printf("Current lock order is:\n");
1080 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1082 if (i.first == mismatch.first) printf(" (1)");
1083 if (i.first == mismatch.second) printf(" (2)");
1084 printf(" %s\n", i.second.ToString().c_str());
1088 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1090 bool fOrderOK = true;
1091 if (lockstack.get() == NULL)
1092 lockstack.reset(new LockStack);
1094 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1097 (*lockstack).push_back(std::make_pair(c, locklocation));
1099 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1101 if (i.first == c) break;
1103 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1104 if (lockorders.count(p1))
1106 lockorders[p1] = (*lockstack);
1108 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1109 if (lockorders.count(p2))
1111 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1118 static void pop_lock()
1122 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1123 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1126 (*lockstack).pop_back();
1130 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1132 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1135 void CCriticalSection::Leave()
1140 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1142 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1143 bool result = mutex.try_lock();
1144 if (!result) pop_lock();
1150 void CCriticalSection::Enter(const char*, const char*, int)
1155 void CCriticalSection::Leave()
1160 bool CCriticalSection::TryEnter(const char*, const char*, int)
1162 bool result = mutex.try_lock();
1166 #endif /* DEBUG_LOCKORDER */