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.
8 #include <boost/algorithm/string/join.hpp>
9 #include <boost/program_options/detail/config_file.hpp>
10 #include <boost/program_options/parsers.hpp>
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/interprocess/sync/interprocess_mutex.hpp>
14 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
15 #include <boost/foreach.hpp>
18 using namespace boost;
20 map<string, string> mapArgs;
21 map<string, vector<string> > mapMultiArgs;
23 bool fPrintToConsole = false;
24 bool fPrintToDebugger = false;
25 bool fRequestShutdown = false;
26 bool fShutdown = false;
29 bool fCommandLine = false;
30 string strMiscWarning;
31 bool fTestNet = false;
32 bool fNoListen = false;
33 bool fLogTimestamps = false;
34 CMedianFilter<int64> vTimeOffsets(200,0);
36 // Init openssl library multithreading support
37 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
38 void locking_callback(int mode, int i, const char* file, int line)
40 if (mode & CRYPTO_LOCK)
41 ppmutexOpenSSL[i]->lock();
43 ppmutexOpenSSL[i]->unlock();
52 // Init openssl library multithreading support
53 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
54 for (int i = 0; i < CRYPTO_num_locks(); i++)
55 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
56 CRYPTO_set_locking_callback(locking_callback);
59 // Seed random number generator with screen scrape and other hardware sources
63 // Seed random number generator with performance counter
68 // Shutdown openssl library multithreading support
69 CRYPTO_set_locking_callback(NULL);
70 for (int i = 0; i < CRYPTO_num_locks(); i++)
71 delete ppmutexOpenSSL[i];
72 OPENSSL_free(ppmutexOpenSSL);
86 // Seed with CPU performance counter
87 int64 nCounter = GetPerformanceCounter();
88 RAND_add(&nCounter, sizeof(nCounter), 1.5);
89 memset(&nCounter, 0, sizeof(nCounter));
92 void RandAddSeedPerfmon()
96 // This can take up to 2 seconds, so only do it every 10 minutes
97 static int64 nLastPerfmon;
98 if (GetTime() < nLastPerfmon + 10 * 60)
100 nLastPerfmon = GetTime();
103 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
104 // Seed with the entire set of perfmon data
105 unsigned char pdata[250000];
106 memset(pdata, 0, sizeof(pdata));
107 unsigned long nSize = sizeof(pdata);
108 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
109 RegCloseKey(HKEY_PERFORMANCE_DATA);
110 if (ret == ERROR_SUCCESS)
112 RAND_add(pdata, nSize, nSize/100.0);
113 memset(pdata, 0, nSize);
114 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
119 uint64 GetRand(uint64 nMax)
124 // The range of the random source must be a multiple of the modulus
125 // to give every possible output value an equal possibility
126 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
129 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
130 while (nRand >= nRange);
131 return (nRand % nMax);
134 int GetRandInt(int nMax)
136 return GetRand(nMax);
149 inline int OutputDebugStringF(const char* pszFormat, ...)
156 va_start(arg_ptr, pszFormat);
157 ret = vprintf(pszFormat, arg_ptr);
162 // print to debug.log
163 static FILE* fileout = NULL;
167 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
168 fileout = fopen(pathDebug.string().c_str(), "a");
169 if (fileout) setbuf(fileout, NULL); // unbuffered
173 static bool fStartedNewLine = true;
175 // Debug print useful for profiling
176 if (fLogTimestamps && fStartedNewLine)
177 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
178 if (pszFormat[strlen(pszFormat) - 1] == '\n')
179 fStartedNewLine = true;
181 fStartedNewLine = false;
184 va_start(arg_ptr, pszFormat);
185 ret = vfprintf(fileout, pszFormat, arg_ptr);
191 if (fPrintToDebugger)
193 static CCriticalSection cs_OutputDebugStringF;
195 // accumulate a line at a time
197 LOCK(cs_OutputDebugStringF);
198 static char pszBuffer[50000];
203 va_start(arg_ptr, pszFormat);
204 int limit = END(pszBuffer) - pend - 2;
205 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
207 if (ret < 0 || ret >= limit)
209 pend = END(pszBuffer) - 2;
215 char* p1 = pszBuffer;
217 while (p2 = strchr(p1, '\n'))
222 OutputDebugStringA(p1);
227 memmove(pszBuffer, p1, pend - p1 + 1);
228 pend -= (p1 - pszBuffer);
237 // - prints up to limit-1 characters
238 // - output string is always null terminated even if limit reached
239 // - return value is the number of characters actually printed
240 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
245 va_start(arg_ptr, format);
246 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
248 if (ret < 0 || ret >= limit)
256 string real_strprintf(const std::string &format, int dummy, ...)
260 int limit = sizeof(buffer);
265 va_start(arg_ptr, dummy);
266 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
268 if (ret >= 0 && ret < limit)
275 throw std::bad_alloc();
277 string str(p, p+ret);
283 bool error(const char *format, ...)
286 int limit = sizeof(buffer);
288 va_start(arg_ptr, format);
289 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
291 if (ret < 0 || ret >= limit)
296 printf("ERROR: %s\n", buffer);
301 void ParseString(const string& str, char c, vector<string>& v)
305 string::size_type i1 = 0;
306 string::size_type i2;
309 i2 = str.find(c, i1);
312 v.push_back(str.substr(i1));
315 v.push_back(str.substr(i1, i2-i1));
321 string FormatMoney(int64 n, bool fPlus)
323 // Note: not using straight sprintf here because we do NOT want
324 // localized number formatting.
325 int64 n_abs = (n > 0 ? n : -n);
326 int64 quotient = n_abs/COIN;
327 int64 remainder = n_abs%COIN;
328 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
330 // Right-trim excess 0's before the decimal point:
332 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
335 str.erase(str.size()-nTrim, nTrim);
338 str.insert((unsigned int)0, 1, '-');
339 else if (fPlus && n > 0)
340 str.insert((unsigned int)0, 1, '+');
345 bool ParseMoney(const string& str, int64& nRet)
347 return ParseMoney(str.c_str(), nRet);
350 bool ParseMoney(const char* pszIn, int64& nRet)
354 const char* p = pszIn;
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() > 10) // guard against 63 bit overflow
381 if (nUnits < 0 || nUnits > COIN)
383 int64 nWhole = atoi64(strWhole);
384 int64 nValue = nWhole*COIN + nUnits;
391 static char phexdigit[256] =
392 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
393 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
394 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
395 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
396 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
397 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
409 bool IsHex(const string& str)
411 BOOST_FOREACH(unsigned char c, str)
413 if (phexdigit[c] < 0)
416 return (str.size() > 0) && (str.size()%2 == 0);
419 vector<unsigned char> ParseHex(const char* psz)
421 // convert hex dump to vector
422 vector<unsigned char> vch;
425 while (isspace(*psz))
427 char c = phexdigit[(unsigned char)*psz++];
430 unsigned char n = (c << 4);
431 c = phexdigit[(unsigned char)*psz++];
440 vector<unsigned char> ParseHex(const string& str)
442 return ParseHex(str.c_str());
445 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
447 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
448 if (name.find("-no") == 0)
450 std::string positive("-");
451 positive.append(name.begin()+3, name.end());
452 if (mapSettingsRet.count(positive) == 0)
454 bool value = !GetBoolArg(name);
455 mapSettingsRet[positive] = (value ? "1" : "0");
460 void ParseParameters(int argc, const char*const 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, '=');
482 mapArgs[psz] = pszValue;
483 mapMultiArgs[psz].push_back(pszValue);
487 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
489 string name = entry.first;
491 // interpret --foo as -foo (as long as both are not set)
492 if (name.find("--") == 0)
494 std::string singleDash(name.begin()+1, name.end());
495 if (mapArgs.count(singleDash) == 0)
496 mapArgs[singleDash] = entry.second;
500 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
501 InterpretNegativeSetting(name, mapArgs);
505 std::string GetArg(const std::string& strArg, const std::string& strDefault)
507 if (mapArgs.count(strArg))
508 return mapArgs[strArg];
512 int64 GetArg(const std::string& strArg, int64 nDefault)
514 if (mapArgs.count(strArg))
515 return atoi64(mapArgs[strArg]);
519 bool GetBoolArg(const std::string& strArg, bool fDefault)
521 if (mapArgs.count(strArg))
523 if (mapArgs[strArg].empty())
525 return (atoi(mapArgs[strArg]) != 0);
530 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
532 if (mapArgs.count(strArg))
534 mapArgs[strArg] = strValue;
538 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
541 return SoftSetArg(strArg, std::string("1"));
543 return SoftSetArg(strArg, std::string("0"));
547 string EncodeBase64(const unsigned char* pch, size_t len)
549 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
552 strRet.reserve((len+2)/3*4);
555 const unsigned char *pchEnd = pch+len;
562 case 0: // we have no bits
563 strRet += pbase64[enc >> 2];
564 left = (enc & 3) << 4;
568 case 1: // we have two bits
569 strRet += pbase64[left | (enc >> 4)];
570 left = (enc & 15) << 2;
574 case 2: // we have four bits
575 strRet += pbase64[left | (enc >> 6)];
576 strRet += pbase64[enc & 63];
584 strRet += pbase64[left];
593 string EncodeBase64(const string& str)
595 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
598 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
600 static const int decode64_table[256] =
602 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
603 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
604 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
605 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
606 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
607 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
608 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
609 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
610 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
611 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
612 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
613 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
614 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
620 vector<unsigned char> vchRet;
621 vchRet.reserve(strlen(p)*3/4);
628 int dec = decode64_table[*p];
629 if (dec == -1) break;
633 case 0: // we have no bits and get 6
638 case 1: // we have 6 bits and keep 4
639 vchRet.push_back((left<<2) | (dec>>4));
644 case 2: // we have 4 bits and get 6, we keep 2
645 vchRet.push_back((left<<4) | (dec>>2));
650 case 3: // we have 2 bits and get 6
651 vchRet.push_back((left<<6) | dec);
660 case 0: // 4n base64 characters processed: ok
663 case 1: // 4n+1 base64 character processed: impossible
667 case 2: // 4n+2 base64 characters processed: require '=='
668 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
672 case 3: // 4n+3 base64 characters processed: require '='
673 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
681 string DecodeBase64(const string& str)
683 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
684 return string((const char*)&vchRet[0], vchRet.size());
688 bool WildcardMatch(const char* psz, const char* mask)
695 return (*psz == '\0');
697 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
712 bool WildcardMatch(const string& str, const string& mask)
714 return WildcardMatch(str.c_str(), mask.c_str());
724 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
727 char pszModule[MAX_PATH];
729 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
731 const char* pszModule = "bitcoin";
734 snprintf(pszMessage, 1000,
735 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
737 snprintf(pszMessage, 1000,
738 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
741 void LogException(std::exception* pex, const char* pszThread)
743 char pszMessage[10000];
744 FormatException(pszMessage, pex, pszThread);
745 printf("\n%s", pszMessage);
748 void PrintException(std::exception* pex, const char* pszThread)
750 char pszMessage[10000];
751 FormatException(pszMessage, pex, pszThread);
752 printf("\n\n************************\n%s\n", pszMessage);
753 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
754 strMiscWarning = pszMessage;
758 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
760 char pszMessage[10000];
761 FormatException(pszMessage, pex, pszThread);
762 printf("\n\n************************\n%s\n", pszMessage);
763 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
764 strMiscWarning = pszMessage;
768 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
770 namespace fs = boost::filesystem;
772 char pszPath[MAX_PATH] = "";
773 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
775 return fs::path(pszPath);
777 else if (nFolder == CSIDL_STARTUP)
779 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
781 else if (nFolder == CSIDL_APPDATA)
783 return fs::path(getenv("APPDATA"));
789 boost::filesystem::path GetDefaultDataDir()
791 namespace fs = boost::filesystem;
793 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
794 // Mac: ~/Library/Application Support/Bitcoin
798 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
801 char* pszHome = getenv("HOME");
802 if (pszHome == NULL || strlen(pszHome) == 0)
803 pathRet = fs::path("/");
805 pathRet = fs::path(pszHome);
808 pathRet /= "Library/Application Support";
809 filesystem::create_directory(pathRet);
810 return pathRet / "Bitcoin";
813 return pathRet / ".bitcoin";
818 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
820 namespace fs = boost::filesystem;
822 static fs::path pathCached[2];
823 static CCriticalSection csPathCached;
824 static bool cachedPath[2] = {false, false};
826 fs::path &path = pathCached[fNetSpecific];
828 // This can be called during exceptions by printf, so we cache the
829 // value so we don't have to do memory allocations after that.
830 if (cachedPath[fNetSpecific])
835 if (mapArgs.count("-datadir")) {
836 path = mapArgs["-datadir"];
838 path = GetDefaultDataDir();
839 if (fNetSpecific && GetBoolArg("-testnet", false))
843 fs::create_directory(path);
845 cachedPath[fNetSpecific]=true;
849 boost::filesystem::path GetConfigFile()
851 namespace fs = boost::filesystem;
853 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
854 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
855 return pathConfigFile;
858 bool ReadConfigFile(map<string, string>& mapSettingsRet,
859 map<string, vector<string> >& mapMultiSettingsRet)
861 namespace fs = boost::filesystem;
862 namespace pod = boost::program_options::detail;
864 fs::ifstream streamConfig(GetConfigFile());
865 if (!streamConfig.good())
866 return true; // No bitcoin.conf file is OK
868 set<string> setOptions;
869 setOptions.insert("*");
871 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
873 // Don't overwrite existing settings so command line settings override bitcoin.conf
874 string strKey = string("-") + it->string_key;
875 if (mapSettingsRet.count(strKey) == 0)
877 mapSettingsRet[strKey] = it->value[0];
878 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
879 InterpretNegativeSetting(strKey, mapSettingsRet);
881 mapMultiSettingsRet[strKey].push_back(it->value[0]);
886 boost::filesystem::path GetPidFile()
888 namespace fs = boost::filesystem;
890 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
891 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
895 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
897 FILE* file = fopen(path.string().c_str(), "w");
900 fprintf(file, "%d\n", pid);
905 int GetFilesize(FILE* file)
907 int nSavePos = ftell(file);
909 if (fseek(file, 0, SEEK_END) == 0)
910 nFilesize = ftell(file);
911 fseek(file, nSavePos, SEEK_SET);
915 void ShrinkDebugFile()
917 // Scroll debug.log if it's getting too big
918 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
919 FILE* file = fopen(pathLog.string().c_str(), "r");
920 if (file && GetFilesize(file) > 10 * 1000000)
922 // Restart the file with some of the end
924 fseek(file, -sizeof(pch), SEEK_END);
925 int nBytes = fread(pch, 1, sizeof(pch), file);
928 file = fopen(pathLog.string().c_str(), "w");
931 fwrite(pch, 1, nBytes, file);
945 // "Never go to sea with two chronometers; take one or three."
946 // Our three time sources are:
948 // - Median of other nodes's clocks
949 // - The user (asking the user to fix the system clock if the first two disagree)
951 static int64 nMockTime = 0; // For unit testing
955 if (nMockTime) return nMockTime;
960 void SetMockTime(int64 nMockTimeIn)
962 nMockTime = nMockTimeIn;
965 static int64 nTimeOffset = 0;
967 int64 GetAdjustedTime()
969 return GetTime() + nTimeOffset;
972 void AddTimeData(const CNetAddr& ip, int64 nTime)
974 int64 nOffsetSample = nTime - GetTime();
977 static set<CNetAddr> setKnown;
978 if (!setKnown.insert(ip).second)
982 vTimeOffsets.input(nOffsetSample);
983 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
984 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
986 int64 nMedian = vTimeOffsets.median();
987 std::vector<int64> vSorted = vTimeOffsets.sorted();
988 // Only let other nodes change our time by so much
989 if (abs64(nMedian) < 70 * 60)
991 nTimeOffset = nMedian;
1000 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1001 bool fMatch = false;
1002 BOOST_FOREACH(int64 nOffset, vSorted)
1003 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1009 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1010 strMiscWarning = strMessage;
1011 printf("*** %s\n", strMessage.c_str());
1012 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1017 BOOST_FOREACH(int64 n, vSorted)
1018 printf("%+"PRI64d" ", n);
1021 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1032 string FormatVersion(int nVersion)
1034 if (nVersion%100 == 0)
1035 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1037 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1040 string FormatFullVersion()
1042 return CLIENT_BUILD;
1045 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1046 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1048 std::ostringstream ss;
1050 ss << name << ":" << FormatVersion(nClientVersion);
1051 if (!comments.empty())
1052 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1059 #ifdef DEBUG_LOCKORDER
1061 // Early deadlock detection.
1062 // Problem being solved:
1063 // Thread 1 locks A, then B, then C
1064 // Thread 2 locks D, then C, then A
1065 // --> may result in deadlock between the two threads, depending on when they run.
1066 // Solution implemented here:
1067 // Keep track of pairs of locks: (A before B), (A before C), etc.
1068 // Complain if any thread trys to lock in a different order.
1071 struct CLockLocation
1073 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1075 mutexName = pszName;
1076 sourceFile = pszFile;
1080 std::string ToString() const
1082 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1086 std::string mutexName;
1087 std::string sourceFile;
1091 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1093 static boost::interprocess::interprocess_mutex dd_mutex;
1094 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1095 static boost::thread_specific_ptr<LockStack> lockstack;
1098 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1100 printf("POTENTIAL DEADLOCK DETECTED\n");
1101 printf("Previous lock order was:\n");
1102 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1104 if (i.first == mismatch.first) printf(" (1)");
1105 if (i.first == mismatch.second) printf(" (2)");
1106 printf(" %s\n", i.second.ToString().c_str());
1108 printf("Current lock order is:\n");
1109 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1111 if (i.first == mismatch.first) printf(" (1)");
1112 if (i.first == mismatch.second) printf(" (2)");
1113 printf(" %s\n", i.second.ToString().c_str());
1117 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1119 bool fOrderOK = true;
1120 if (lockstack.get() == NULL)
1121 lockstack.reset(new LockStack);
1123 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1126 (*lockstack).push_back(std::make_pair(c, locklocation));
1128 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1130 if (i.first == c) break;
1132 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1133 if (lockorders.count(p1))
1135 lockorders[p1] = (*lockstack);
1137 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1138 if (lockorders.count(p2))
1140 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1147 static void pop_lock()
1151 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1152 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1155 (*lockstack).pop_back();
1159 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1161 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1164 void LeaveCritical()
1169 #endif /* DEBUG_LOCKORDER */