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)
306 printf("ERROR: %s\n", buffer);
311 void ParseString(const string& str, char c, vector<string>& v)
315 string::size_type i1 = 0;
316 string::size_type i2;
319 i2 = str.find(c, i1);
322 v.push_back(str.substr(i1));
325 v.push_back(str.substr(i1, i2-i1));
331 string FormatMoney(int64 n, bool fPlus)
333 // Note: not using straight sprintf here because we do NOT want
334 // localized number formatting.
335 int64 n_abs = (n > 0 ? n : -n);
336 int64 quotient = n_abs/COIN;
337 int64 remainder = n_abs%COIN;
338 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
340 // Right-trim excess 0's before the decimal point:
342 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
345 str.erase(str.size()-nTrim, nTrim);
348 str.insert((unsigned int)0, 1, '-');
349 else if (fPlus && n > 0)
350 str.insert((unsigned int)0, 1, '+');
355 bool ParseMoney(const string& str, int64& nRet)
357 return ParseMoney(str.c_str(), nRet);
360 bool ParseMoney(const char* pszIn, int64& nRet)
364 const char* p = pszIn;
372 int64 nMult = CENT*10;
373 while (isdigit(*p) && (nMult > 0))
375 nUnits += nMult * (*p++ - '0');
384 strWhole.insert(strWhole.end(), *p);
389 if (strWhole.size() > 10) // guard against 63 bit overflow
391 if (nUnits < 0 || nUnits > COIN)
393 int64 nWhole = atoi64(strWhole);
394 int64 nValue = nWhole*COIN + nUnits;
401 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
406 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
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 -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, };
419 bool IsHex(const string& str)
421 BOOST_FOREACH(unsigned char c, str)
423 if (phexdigit[c] < 0)
426 return (str.size() > 0) && (str.size()%2 == 0);
429 vector<unsigned char> ParseHex(const char* psz)
431 // convert hex dump to vector
432 vector<unsigned char> vch;
435 while (isspace(*psz))
437 char c = phexdigit[(unsigned char)*psz++];
440 unsigned char n = (c << 4);
441 c = phexdigit[(unsigned char)*psz++];
450 vector<unsigned char> ParseHex(const string& str)
452 return ParseHex(str.c_str());
455 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
457 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
458 if (name.find("-no") == 0)
460 std::string positive("-");
461 positive.append(name.begin()+3, name.end());
462 if (mapSettingsRet.count(positive) == 0)
464 bool value = !GetBoolArg(name);
465 mapSettingsRet[positive] = (value ? "1" : "0");
470 void ParseParameters(int argc, const char*const argv[])
473 mapMultiArgs.clear();
474 for (int i = 1; i < argc; i++)
477 strlcpy(psz, argv[i], sizeof(psz));
478 char* pszValue = (char*)"";
479 if (strchr(psz, '='))
481 pszValue = strchr(psz, '=');
492 mapArgs[psz] = pszValue;
493 mapMultiArgs[psz].push_back(pszValue);
497 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
499 string name = entry.first;
501 // interpret --foo as -foo (as long as both are not set)
502 if (name.find("--") == 0)
504 std::string singleDash(name.begin()+1, name.end());
505 if (mapArgs.count(singleDash) == 0)
506 mapArgs[singleDash] = entry.second;
510 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
511 InterpretNegativeSetting(name, mapArgs);
515 std::string GetArg(const std::string& strArg, const std::string& strDefault)
517 if (mapArgs.count(strArg))
518 return mapArgs[strArg];
522 int64 GetArg(const std::string& strArg, int64 nDefault)
524 if (mapArgs.count(strArg))
525 return atoi64(mapArgs[strArg]);
529 bool GetBoolArg(const std::string& strArg, bool fDefault)
531 if (mapArgs.count(strArg))
533 if (mapArgs[strArg].empty())
535 return (atoi(mapArgs[strArg]) != 0);
540 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
542 if (mapArgs.count(strArg))
544 mapArgs[strArg] = strValue;
548 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
551 return SoftSetArg(strArg, std::string("1"));
553 return SoftSetArg(strArg, std::string("0"));
557 string EncodeBase64(const unsigned char* pch, size_t len)
559 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
562 strRet.reserve((len+2)/3*4);
565 const unsigned char *pchEnd = pch+len;
572 case 0: // we have no bits
573 strRet += pbase64[enc >> 2];
574 left = (enc & 3) << 4;
578 case 1: // we have two bits
579 strRet += pbase64[left | (enc >> 4)];
580 left = (enc & 15) << 2;
584 case 2: // we have four bits
585 strRet += pbase64[left | (enc >> 6)];
586 strRet += pbase64[enc & 63];
594 strRet += pbase64[left];
603 string EncodeBase64(const string& str)
605 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
608 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
610 static const int decode64_table[256] =
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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
615 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
616 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
617 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
618 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
619 -1, -1, -1, -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
630 vector<unsigned char> vchRet;
631 vchRet.reserve(strlen(p)*3/4);
638 int dec = decode64_table[(unsigned char)*p];
639 if (dec == -1) break;
643 case 0: // we have no bits and get 6
648 case 1: // we have 6 bits and keep 4
649 vchRet.push_back((left<<2) | (dec>>4));
654 case 2: // we have 4 bits and get 6, we keep 2
655 vchRet.push_back((left<<4) | (dec>>2));
660 case 3: // we have 2 bits and get 6
661 vchRet.push_back((left<<6) | dec);
670 case 0: // 4n base64 characters processed: ok
673 case 1: // 4n+1 base64 character processed: impossible
677 case 2: // 4n+2 base64 characters processed: require '=='
678 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
682 case 3: // 4n+3 base64 characters processed: require '='
683 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
691 string DecodeBase64(const string& str)
693 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
694 return string((const char*)&vchRet[0], vchRet.size());
698 bool WildcardMatch(const char* psz, const char* mask)
705 return (*psz == '\0');
707 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
722 bool WildcardMatch(const string& str, const string& mask)
724 return WildcardMatch(str.c_str(), mask.c_str());
734 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
737 char pszModule[MAX_PATH];
739 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
741 const char* pszModule = "bitcoin";
744 snprintf(pszMessage, 1000,
745 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
747 snprintf(pszMessage, 1000,
748 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
751 void LogException(std::exception* pex, const char* pszThread)
753 char pszMessage[10000];
754 FormatException(pszMessage, pex, pszThread);
755 printf("\n%s", pszMessage);
758 void PrintException(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 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
770 char pszMessage[10000];
771 FormatException(pszMessage, pex, pszThread);
772 printf("\n\n************************\n%s\n", pszMessage);
773 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
774 strMiscWarning = pszMessage;
778 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
780 namespace fs = boost::filesystem;
782 char pszPath[MAX_PATH] = "";
783 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
785 return fs::path(pszPath);
787 else if (nFolder == CSIDL_STARTUP)
789 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
791 else if (nFolder == CSIDL_APPDATA)
793 return fs::path(getenv("APPDATA"));
799 boost::filesystem::path GetDefaultDataDir()
801 namespace fs = boost::filesystem;
803 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
804 // Mac: ~/Library/Application Support/Bitcoin
808 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
811 char* pszHome = getenv("HOME");
812 if (pszHome == NULL || strlen(pszHome) == 0)
813 pathRet = fs::path("/");
815 pathRet = fs::path(pszHome);
818 pathRet /= "Library/Application Support";
819 filesystem::create_directory(pathRet);
820 return pathRet / "Bitcoin";
823 return pathRet / ".bitcoin";
828 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
830 namespace fs = boost::filesystem;
832 static fs::path pathCached[2];
833 static CCriticalSection csPathCached;
834 static bool cachedPath[2] = {false, false};
836 fs::path &path = pathCached[fNetSpecific];
838 // This can be called during exceptions by printf, so we cache the
839 // value so we don't have to do memory allocations after that.
840 if (cachedPath[fNetSpecific])
845 if (mapArgs.count("-datadir")) {
846 path = mapArgs["-datadir"];
848 path = GetDefaultDataDir();
850 if (fNetSpecific && GetBoolArg("-testnet", false))
853 fs::create_directory(path);
855 cachedPath[fNetSpecific]=true;
859 boost::filesystem::path GetConfigFile()
861 namespace fs = boost::filesystem;
863 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
864 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
865 return pathConfigFile;
868 bool ReadConfigFile(map<string, string>& mapSettingsRet,
869 map<string, vector<string> >& mapMultiSettingsRet)
871 namespace fs = boost::filesystem;
872 namespace pod = boost::program_options::detail;
874 fs::ifstream streamConfig(GetConfigFile());
875 if (!streamConfig.good())
876 return true; // No bitcoin.conf file is OK
878 set<string> setOptions;
879 setOptions.insert("*");
881 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
883 // Don't overwrite existing settings so command line settings override bitcoin.conf
884 string strKey = string("-") + it->string_key;
885 if (mapSettingsRet.count(strKey) == 0)
887 mapSettingsRet[strKey] = it->value[0];
888 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
889 InterpretNegativeSetting(strKey, mapSettingsRet);
891 mapMultiSettingsRet[strKey].push_back(it->value[0]);
896 boost::filesystem::path GetPidFile()
898 namespace fs = boost::filesystem;
900 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
901 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
905 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
907 FILE* file = fopen(path.string().c_str(), "w");
910 fprintf(file, "%d\n", pid);
915 int GetFilesize(FILE* file)
917 int nSavePos = ftell(file);
919 if (fseek(file, 0, SEEK_END) == 0)
920 nFilesize = ftell(file);
921 fseek(file, nSavePos, SEEK_SET);
925 void ShrinkDebugFile()
927 // Scroll debug.log if it's getting too big
928 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
929 FILE* file = fopen(pathLog.string().c_str(), "r");
930 if (file && GetFilesize(file) > 10 * 1000000)
932 // Restart the file with some of the end
934 fseek(file, -sizeof(pch), SEEK_END);
935 int nBytes = fread(pch, 1, sizeof(pch), file);
938 file = fopen(pathLog.string().c_str(), "w");
941 fwrite(pch, 1, nBytes, file);
955 // "Never go to sea with two chronometers; take one or three."
956 // Our three time sources are:
958 // - Median of other nodes's clocks
959 // - The user (asking the user to fix the system clock if the first two disagree)
961 static int64 nMockTime = 0; // For unit testing
965 if (nMockTime) return nMockTime;
970 void SetMockTime(int64 nMockTimeIn)
972 nMockTime = nMockTimeIn;
975 static int64 nTimeOffset = 0;
977 int64 GetAdjustedTime()
979 return GetTime() + nTimeOffset;
982 void AddTimeData(const CNetAddr& ip, int64 nTime)
984 int64 nOffsetSample = nTime - GetTime();
987 static set<CNetAddr> setKnown;
988 if (!setKnown.insert(ip).second)
992 vTimeOffsets.input(nOffsetSample);
993 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
994 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
996 int64 nMedian = vTimeOffsets.median();
997 std::vector<int64> vSorted = vTimeOffsets.sorted();
998 // Only let other nodes change our time by so much
999 if (abs64(nMedian) < 70 * 60)
1001 nTimeOffset = nMedian;
1010 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1011 bool fMatch = false;
1012 BOOST_FOREACH(int64 nOffset, vSorted)
1013 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1019 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1020 strMiscWarning = strMessage;
1021 printf("*** %s\n", strMessage.c_str());
1022 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1027 BOOST_FOREACH(int64 n, vSorted)
1028 printf("%+"PRI64d" ", n);
1031 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1042 string FormatVersion(int nVersion)
1044 if (nVersion%100 == 0)
1045 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1047 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1050 string FormatFullVersion()
1052 return CLIENT_BUILD;
1055 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1056 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1058 std::ostringstream ss;
1060 ss << name << ":" << FormatVersion(nClientVersion);
1061 if (!comments.empty())
1062 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1069 #ifdef DEBUG_LOCKORDER
1071 // Early deadlock detection.
1072 // Problem being solved:
1073 // Thread 1 locks A, then B, then C
1074 // Thread 2 locks D, then C, then A
1075 // --> may result in deadlock between the two threads, depending on when they run.
1076 // Solution implemented here:
1077 // Keep track of pairs of locks: (A before B), (A before C), etc.
1078 // Complain if any thread trys to lock in a different order.
1081 struct CLockLocation
1083 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1085 mutexName = pszName;
1086 sourceFile = pszFile;
1090 std::string ToString() const
1092 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1096 std::string mutexName;
1097 std::string sourceFile;
1101 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1103 static boost::interprocess::interprocess_mutex dd_mutex;
1104 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1105 static boost::thread_specific_ptr<LockStack> lockstack;
1108 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1110 printf("POTENTIAL DEADLOCK DETECTED\n");
1111 printf("Previous lock order was:\n");
1112 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1114 if (i.first == mismatch.first) printf(" (1)");
1115 if (i.first == mismatch.second) printf(" (2)");
1116 printf(" %s\n", i.second.ToString().c_str());
1118 printf("Current lock order is:\n");
1119 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1121 if (i.first == mismatch.first) printf(" (1)");
1122 if (i.first == mismatch.second) printf(" (2)");
1123 printf(" %s\n", i.second.ToString().c_str());
1127 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1129 bool fOrderOK = true;
1130 if (lockstack.get() == NULL)
1131 lockstack.reset(new LockStack);
1133 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1136 (*lockstack).push_back(std::make_pair(c, locklocation));
1138 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1140 if (i.first == c) break;
1142 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1143 if (lockorders.count(p1))
1145 lockorders[p1] = (*lockstack);
1147 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1148 if (lockorders.count(p2))
1150 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1157 static void pop_lock()
1161 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1162 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1165 (*lockstack).pop_back();
1169 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1171 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1174 void LeaveCritical()
1179 #endif /* DEBUG_LOCKORDER */