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>
10 // Work around clang compilation problem in Boost 1.46:
11 // /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
12 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
13 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
15 namespace program_options {
16 std::string to_internal(const std::string&);
20 #include <boost/program_options/detail/config_file.hpp>
21 #include <boost/program_options/parsers.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/fstream.hpp>
24 #include <boost/interprocess/sync/interprocess_mutex.hpp>
25 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
26 #include <boost/foreach.hpp>
29 using namespace boost;
31 map<string, string> mapArgs;
32 map<string, vector<string> > mapMultiArgs;
34 bool fPrintToConsole = false;
35 bool fPrintToDebugger = false;
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;
45 CMedianFilter<int64> vTimeOffsets(200,0);
47 // Init openssl library multithreading support
48 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
49 void locking_callback(int mode, int i, const char* file, int line)
51 if (mode & CRYPTO_LOCK)
52 ppmutexOpenSSL[i]->lock();
54 ppmutexOpenSSL[i]->unlock();
63 // Init openssl library multithreading support
64 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
65 for (int i = 0; i < CRYPTO_num_locks(); i++)
66 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
67 CRYPTO_set_locking_callback(locking_callback);
70 // Seed random number generator with screen scrape and other hardware sources
74 // Seed random number generator with performance counter
79 // Shutdown openssl library multithreading support
80 CRYPTO_set_locking_callback(NULL);
81 for (int i = 0; i < CRYPTO_num_locks(); i++)
82 delete ppmutexOpenSSL[i];
83 OPENSSL_free(ppmutexOpenSSL);
97 // Seed with CPU performance counter
98 int64 nCounter = GetPerformanceCounter();
99 RAND_add(&nCounter, sizeof(nCounter), 1.5);
100 memset(&nCounter, 0, sizeof(nCounter));
103 void RandAddSeedPerfmon()
107 // This can take up to 2 seconds, so only do it every 10 minutes
108 static int64 nLastPerfmon;
109 if (GetTime() < nLastPerfmon + 10 * 60)
111 nLastPerfmon = GetTime();
114 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
115 // Seed with the entire set of perfmon data
116 unsigned char pdata[250000];
117 memset(pdata, 0, sizeof(pdata));
118 unsigned long nSize = sizeof(pdata);
119 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
120 RegCloseKey(HKEY_PERFORMANCE_DATA);
121 if (ret == ERROR_SUCCESS)
123 RAND_add(pdata, nSize, nSize/100.0);
124 memset(pdata, 0, nSize);
125 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
130 uint64 GetRand(uint64 nMax)
135 // The range of the random source must be a multiple of the modulus
136 // to give every possible output value an equal possibility
137 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
140 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
141 while (nRand >= nRange);
142 return (nRand % nMax);
145 int GetRandInt(int nMax)
147 return GetRand(nMax);
160 inline int OutputDebugStringF(const char* pszFormat, ...)
167 va_start(arg_ptr, pszFormat);
168 ret = vprintf(pszFormat, arg_ptr);
173 // print to debug.log
174 static FILE* fileout = NULL;
178 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
179 fileout = fopen(pathDebug.string().c_str(), "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
208 LOCK(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 real_strprintf(const std::string &format, int dummy, ...)
271 int limit = sizeof(buffer);
276 va_start(arg_ptr, dummy);
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 char *format, ...)
297 int limit = sizeof(buffer);
299 va_start(arg_ptr, format);
300 int ret = _vsnprintf(buffer, limit, format, 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 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
407 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
408 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
420 bool IsHex(const string& str)
422 BOOST_FOREACH(unsigned char c, str)
424 if (phexdigit[c] < 0)
427 return (str.size() > 0) && (str.size()%2 == 0);
430 vector<unsigned char> ParseHex(const char* psz)
432 // convert hex dump to vector
433 vector<unsigned char> vch;
436 while (isspace(*psz))
438 char c = phexdigit[(unsigned char)*psz++];
441 unsigned char n = (c << 4);
442 c = phexdigit[(unsigned char)*psz++];
451 vector<unsigned char> ParseHex(const string& str)
453 return ParseHex(str.c_str());
456 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
458 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
459 if (name.find("-no") == 0)
461 std::string positive("-");
462 positive.append(name.begin()+3, name.end());
463 if (mapSettingsRet.count(positive) == 0)
465 bool value = !GetBoolArg(name);
466 mapSettingsRet[positive] = (value ? "1" : "0");
471 void ParseParameters(int argc, const char*const argv[])
474 mapMultiArgs.clear();
475 for (int i = 1; i < argc; i++)
478 strlcpy(psz, argv[i], sizeof(psz));
479 char* pszValue = (char*)"";
480 if (strchr(psz, '='))
482 pszValue = strchr(psz, '=');
493 mapArgs[psz] = pszValue;
494 mapMultiArgs[psz].push_back(pszValue);
498 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
500 string name = entry.first;
502 // interpret --foo as -foo (as long as both are not set)
503 if (name.find("--") == 0)
505 std::string singleDash(name.begin()+1, name.end());
506 if (mapArgs.count(singleDash) == 0)
507 mapArgs[singleDash] = entry.second;
511 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
512 InterpretNegativeSetting(name, mapArgs);
516 std::string GetArg(const std::string& strArg, const std::string& strDefault)
518 if (mapArgs.count(strArg))
519 return mapArgs[strArg];
523 int64 GetArg(const std::string& strArg, int64 nDefault)
525 if (mapArgs.count(strArg))
526 return atoi64(mapArgs[strArg]);
530 bool GetBoolArg(const std::string& strArg, bool fDefault)
532 if (mapArgs.count(strArg))
534 if (mapArgs[strArg].empty())
536 return (atoi(mapArgs[strArg]) != 0);
541 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
543 if (mapArgs.count(strArg))
545 mapArgs[strArg] = strValue;
549 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
552 return SoftSetArg(strArg, std::string("1"));
554 return SoftSetArg(strArg, std::string("0"));
558 string EncodeBase64(const unsigned char* pch, size_t len)
560 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
563 strRet.reserve((len+2)/3*4);
566 const unsigned char *pchEnd = pch+len;
573 case 0: // we have no bits
574 strRet += pbase64[enc >> 2];
575 left = (enc & 3) << 4;
579 case 1: // we have two bits
580 strRet += pbase64[left | (enc >> 4)];
581 left = (enc & 15) << 2;
585 case 2: // we have four bits
586 strRet += pbase64[left | (enc >> 6)];
587 strRet += pbase64[enc & 63];
595 strRet += pbase64[left];
604 string EncodeBase64(const string& str)
606 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
609 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
611 static const int decode64_table[256] =
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, -1, -1, -1, -1,
615 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
616 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
617 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
618 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
619 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
620 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
621 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
622 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
623 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
624 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
625 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
631 vector<unsigned char> vchRet;
632 vchRet.reserve(strlen(p)*3/4);
639 int dec = decode64_table[*p];
640 if (dec == -1) break;
644 case 0: // we have no bits and get 6
649 case 1: // we have 6 bits and keep 4
650 vchRet.push_back((left<<2) | (dec>>4));
655 case 2: // we have 4 bits and get 6, we keep 2
656 vchRet.push_back((left<<4) | (dec>>2));
661 case 3: // we have 2 bits and get 6
662 vchRet.push_back((left<<6) | dec);
671 case 0: // 4n base64 characters processed: ok
674 case 1: // 4n+1 base64 character processed: impossible
678 case 2: // 4n+2 base64 characters processed: require '=='
679 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
683 case 3: // 4n+3 base64 characters processed: require '='
684 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
692 string DecodeBase64(const string& str)
694 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
695 return string((const char*)&vchRet[0], vchRet.size());
699 bool WildcardMatch(const char* psz, const char* mask)
706 return (*psz == '\0');
708 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
723 bool WildcardMatch(const string& str, const string& mask)
725 return WildcardMatch(str.c_str(), mask.c_str());
735 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
738 char pszModule[MAX_PATH];
740 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
742 const char* pszModule = "bitcoin";
745 snprintf(pszMessage, 1000,
746 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
748 snprintf(pszMessage, 1000,
749 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
752 void LogException(std::exception* pex, const char* pszThread)
754 char pszMessage[10000];
755 FormatException(pszMessage, pex, pszThread);
756 printf("\n%s", pszMessage);
759 void PrintException(std::exception* pex, const char* pszThread)
761 char pszMessage[10000];
762 FormatException(pszMessage, pex, pszThread);
763 printf("\n\n************************\n%s\n", pszMessage);
764 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
765 strMiscWarning = pszMessage;
769 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
771 char pszMessage[10000];
772 FormatException(pszMessage, pex, pszThread);
773 printf("\n\n************************\n%s\n", pszMessage);
774 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
775 strMiscWarning = pszMessage;
779 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
781 namespace fs = boost::filesystem;
783 char pszPath[MAX_PATH] = "";
784 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
786 return fs::path(pszPath);
788 else if (nFolder == CSIDL_STARTUP)
790 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
792 else if (nFolder == CSIDL_APPDATA)
794 return fs::path(getenv("APPDATA"));
800 boost::filesystem::path GetDefaultDataDir()
802 namespace fs = boost::filesystem;
804 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
805 // Mac: ~/Library/Application Support/Bitcoin
809 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
812 char* pszHome = getenv("HOME");
813 if (pszHome == NULL || strlen(pszHome) == 0)
814 pathRet = fs::path("/");
816 pathRet = fs::path(pszHome);
819 pathRet /= "Library/Application Support";
820 filesystem::create_directory(pathRet);
821 return pathRet / "Bitcoin";
824 return pathRet / ".bitcoin";
829 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
831 namespace fs = boost::filesystem;
833 static fs::path pathCached[2];
834 static CCriticalSection csPathCached;
835 static bool cachedPath[2] = {false, false};
837 fs::path &path = pathCached[fNetSpecific];
839 // This can be called during exceptions by printf, so we cache the
840 // value so we don't have to do memory allocations after that.
841 if (cachedPath[fNetSpecific])
846 if (mapArgs.count("-datadir")) {
847 path = mapArgs["-datadir"];
849 path = GetDefaultDataDir();
851 if (fNetSpecific && GetBoolArg("-testnet", false))
854 fs::create_directory(path);
856 cachedPath[fNetSpecific]=true;
860 boost::filesystem::path GetConfigFile()
862 namespace fs = boost::filesystem;
864 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
865 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
866 return pathConfigFile;
869 bool ReadConfigFile(map<string, string>& mapSettingsRet,
870 map<string, vector<string> >& mapMultiSettingsRet)
872 namespace fs = boost::filesystem;
873 namespace pod = boost::program_options::detail;
875 fs::ifstream streamConfig(GetConfigFile());
876 if (!streamConfig.good())
877 return true; // No bitcoin.conf file is OK
879 set<string> setOptions;
880 setOptions.insert("*");
882 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
884 // Don't overwrite existing settings so command line settings override bitcoin.conf
885 string strKey = string("-") + it->string_key;
886 if (mapSettingsRet.count(strKey) == 0)
888 mapSettingsRet[strKey] = it->value[0];
889 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
890 InterpretNegativeSetting(strKey, mapSettingsRet);
892 mapMultiSettingsRet[strKey].push_back(it->value[0]);
897 boost::filesystem::path GetPidFile()
899 namespace fs = boost::filesystem;
901 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
902 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
906 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
908 FILE* file = fopen(path.string().c_str(), "w");
911 fprintf(file, "%d\n", pid);
916 int GetFilesize(FILE* file)
918 int nSavePos = ftell(file);
920 if (fseek(file, 0, SEEK_END) == 0)
921 nFilesize = ftell(file);
922 fseek(file, nSavePos, SEEK_SET);
926 void ShrinkDebugFile()
928 // Scroll debug.log if it's getting too big
929 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
930 FILE* file = fopen(pathLog.string().c_str(), "r");
931 if (file && GetFilesize(file) > 10 * 1000000)
933 // Restart the file with some of the end
935 fseek(file, -sizeof(pch), SEEK_END);
936 int nBytes = fread(pch, 1, sizeof(pch), file);
939 file = fopen(pathLog.string().c_str(), "w");
942 fwrite(pch, 1, nBytes, file);
956 // "Never go to sea with two chronometers; take one or three."
957 // Our three time sources are:
959 // - Median of other nodes's clocks
960 // - The user (asking the user to fix the system clock if the first two disagree)
962 static int64 nMockTime = 0; // For unit testing
966 if (nMockTime) return nMockTime;
971 void SetMockTime(int64 nMockTimeIn)
973 nMockTime = nMockTimeIn;
976 static int64 nTimeOffset = 0;
978 int64 GetAdjustedTime()
980 return GetTime() + nTimeOffset;
983 void AddTimeData(const CNetAddr& ip, int64 nTime)
985 int64 nOffsetSample = nTime - GetTime();
988 static set<CNetAddr> setKnown;
989 if (!setKnown.insert(ip).second)
993 vTimeOffsets.input(nOffsetSample);
994 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
995 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
997 int64 nMedian = vTimeOffsets.median();
998 std::vector<int64> vSorted = vTimeOffsets.sorted();
999 // Only let other nodes change our time by so much
1000 if (abs64(nMedian) < 70 * 60)
1002 nTimeOffset = nMedian;
1011 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1012 bool fMatch = false;
1013 BOOST_FOREACH(int64 nOffset, vSorted)
1014 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1020 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1021 strMiscWarning = strMessage;
1022 printf("*** %s\n", strMessage.c_str());
1023 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1028 BOOST_FOREACH(int64 n, vSorted)
1029 printf("%+"PRI64d" ", n);
1032 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1043 string FormatVersion(int nVersion)
1045 if (nVersion%100 == 0)
1046 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1048 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1051 string FormatFullVersion()
1053 return CLIENT_BUILD;
1056 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1057 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1059 std::ostringstream ss;
1061 ss << name << ":" << FormatVersion(nClientVersion);
1062 if (!comments.empty())
1063 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1070 #ifdef DEBUG_LOCKORDER
1072 // Early deadlock detection.
1073 // Problem being solved:
1074 // Thread 1 locks A, then B, then C
1075 // Thread 2 locks D, then C, then A
1076 // --> may result in deadlock between the two threads, depending on when they run.
1077 // Solution implemented here:
1078 // Keep track of pairs of locks: (A before B), (A before C), etc.
1079 // Complain if any thread trys to lock in a different order.
1082 struct CLockLocation
1084 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1086 mutexName = pszName;
1087 sourceFile = pszFile;
1091 std::string ToString() const
1093 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1097 std::string mutexName;
1098 std::string sourceFile;
1102 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1104 static boost::interprocess::interprocess_mutex dd_mutex;
1105 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1106 static boost::thread_specific_ptr<LockStack> lockstack;
1109 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1111 printf("POTENTIAL DEADLOCK DETECTED\n");
1112 printf("Previous lock order was:\n");
1113 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1115 if (i.first == mismatch.first) printf(" (1)");
1116 if (i.first == mismatch.second) printf(" (2)");
1117 printf(" %s\n", i.second.ToString().c_str());
1119 printf("Current lock order is:\n");
1120 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1122 if (i.first == mismatch.first) printf(" (1)");
1123 if (i.first == mismatch.second) printf(" (2)");
1124 printf(" %s\n", i.second.ToString().c_str());
1128 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1130 bool fOrderOK = true;
1131 if (lockstack.get() == NULL)
1132 lockstack.reset(new LockStack);
1134 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1137 (*lockstack).push_back(std::make_pair(c, locklocation));
1139 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1141 if (i.first == c) break;
1143 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1144 if (lockorders.count(p1))
1146 lockorders[p1] = (*lockstack);
1148 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1149 if (lockorders.count(p2))
1151 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1158 static void pop_lock()
1162 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1163 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1166 (*lockstack).pop_back();
1170 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1172 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1175 void LeaveCritical()
1180 #endif /* DEBUG_LOCKORDER */