1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/algorithm/string/join.hpp>
8 #include <boost/program_options/detail/config_file.hpp>
9 #include <boost/program_options/parsers.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12 #include <boost/interprocess/sync/interprocess_mutex.hpp>
13 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
14 #include <boost/foreach.hpp>
17 using namespace boost;
19 map<string, string> mapArgs;
20 map<string, vector<string> > mapMultiArgs;
22 bool fPrintToConsole = false;
23 bool fPrintToDebugger = false;
24 char pszSetDataDir[MAX_PATH] = "";
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 char pszFile[MAX_PATH+100];
169 strlcat(pszFile, "/debug.log", sizeof(pszFile));
170 fileout = fopen(pszFile, "a");
171 if (fileout) setbuf(fileout, NULL); // unbuffered
175 static bool fStartedNewLine = true;
177 // Debug print useful for profiling
178 if (fLogTimestamps && fStartedNewLine)
179 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
180 if (pszFormat[strlen(pszFormat) - 1] == '\n')
181 fStartedNewLine = true;
183 fStartedNewLine = false;
186 va_start(arg_ptr, pszFormat);
187 ret = vfprintf(fileout, pszFormat, arg_ptr);
193 if (fPrintToDebugger)
195 static CCriticalSection cs_OutputDebugStringF;
197 // accumulate a line at a time
199 LOCK(cs_OutputDebugStringF);
200 static char pszBuffer[50000];
205 va_start(arg_ptr, pszFormat);
206 int limit = END(pszBuffer) - pend - 2;
207 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
209 if (ret < 0 || ret >= limit)
211 pend = END(pszBuffer) - 2;
217 char* p1 = pszBuffer;
219 while (p2 = strchr(p1, '\n'))
224 OutputDebugStringA(p1);
229 memmove(pszBuffer, p1, pend - p1 + 1);
230 pend -= (p1 - pszBuffer);
239 // - prints up to limit-1 characters
240 // - output string is always null terminated even if limit reached
241 // - return value is the number of characters actually printed
242 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
247 va_start(arg_ptr, format);
248 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
250 if (ret < 0 || ret >= limit)
258 string real_strprintf(const std::string &format, int dummy, ...)
262 int limit = sizeof(buffer);
267 va_start(arg_ptr, dummy);
268 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
270 if (ret >= 0 && ret < limit)
277 throw std::bad_alloc();
279 string str(p, p+ret);
285 bool error(const char *format, ...)
288 int limit = sizeof(buffer);
290 va_start(arg_ptr, format);
291 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
293 if (ret < 0 || ret >= limit)
298 printf("ERROR: %s\n", buffer);
303 void ParseString(const string& str, char c, vector<string>& v)
307 string::size_type i1 = 0;
308 string::size_type i2;
311 i2 = str.find(c, i1);
314 v.push_back(str.substr(i1));
317 v.push_back(str.substr(i1, i2-i1));
323 string FormatMoney(int64 n, bool fPlus)
325 // Note: not using straight sprintf here because we do NOT want
326 // localized number formatting.
327 int64 n_abs = (n > 0 ? n : -n);
328 int64 quotient = n_abs/COIN;
329 int64 remainder = n_abs%COIN;
330 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
332 // Right-trim excess 0's before the decimal point:
334 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
337 str.erase(str.size()-nTrim, nTrim);
340 str.insert((unsigned int)0, 1, '-');
341 else if (fPlus && n > 0)
342 str.insert((unsigned int)0, 1, '+');
347 bool ParseMoney(const string& str, int64& nRet)
349 return ParseMoney(str.c_str(), nRet);
352 bool ParseMoney(const char* pszIn, int64& nRet)
356 const char* p = pszIn;
364 int64 nMult = CENT*10;
365 while (isdigit(*p) && (nMult > 0))
367 nUnits += nMult * (*p++ - '0');
376 strWhole.insert(strWhole.end(), *p);
381 if (strWhole.size() > 10) // guard against 63 bit overflow
383 if (nUnits < 0 || nUnits > COIN)
385 int64 nWhole = atoi64(strWhole);
386 int64 nValue = nWhole*COIN + nUnits;
393 static char phexdigit[256] =
394 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
395 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
396 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
397 0,1,2,3,4,5,6,7,8,9,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
408 -1,-1,-1,-1,-1,-1,-1,-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, };
411 bool IsHex(const string& str)
413 BOOST_FOREACH(unsigned char c, str)
415 if (phexdigit[c] < 0)
418 return (str.size() > 0) && (str.size()%2 == 0);
421 vector<unsigned char> ParseHex(const char* psz)
423 // convert hex dump to vector
424 vector<unsigned char> vch;
427 while (isspace(*psz))
429 char c = phexdigit[(unsigned char)*psz++];
432 unsigned char n = (c << 4);
433 c = phexdigit[(unsigned char)*psz++];
442 vector<unsigned char> ParseHex(const string& str)
444 return ParseHex(str.c_str());
447 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
449 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
450 if (name.find("-no") == 0)
452 std::string positive("-");
453 positive.append(name.begin()+3, name.end());
454 if (mapSettingsRet.count(positive) == 0)
456 bool value = !GetBoolArg(name);
457 mapSettingsRet[positive] = (value ? "1" : "0");
462 void ParseParameters(int argc, const char*const argv[])
465 mapMultiArgs.clear();
466 for (int i = 1; i < argc; i++)
469 strlcpy(psz, argv[i], sizeof(psz));
470 char* pszValue = (char*)"";
471 if (strchr(psz, '='))
473 pszValue = strchr(psz, '=');
484 mapArgs[psz] = pszValue;
485 mapMultiArgs[psz].push_back(pszValue);
489 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
491 string name = entry.first;
493 // interpret --foo as -foo (as long as both are not set)
494 if (name.find("--") == 0)
496 std::string singleDash(name.begin()+1, name.end());
497 if (mapArgs.count(singleDash) == 0)
498 mapArgs[singleDash] = entry.second;
502 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
503 InterpretNegativeSetting(name, mapArgs);
507 std::string GetArg(const std::string& strArg, const std::string& strDefault)
509 if (mapArgs.count(strArg))
510 return mapArgs[strArg];
514 int64 GetArg(const std::string& strArg, int64 nDefault)
516 if (mapArgs.count(strArg))
517 return atoi64(mapArgs[strArg]);
521 bool GetBoolArg(const std::string& strArg, bool fDefault)
523 if (mapArgs.count(strArg))
525 if (mapArgs[strArg].empty())
527 return (atoi(mapArgs[strArg]) != 0);
532 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
534 if (mapArgs.count(strArg))
536 mapArgs[strArg] = strValue;
540 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
543 return SoftSetArg(strArg, std::string("1"));
545 return SoftSetArg(strArg, std::string("0"));
549 string EncodeBase64(const unsigned char* pch, size_t len)
551 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
554 strRet.reserve((len+2)/3*4);
557 const unsigned char *pchEnd = pch+len;
564 case 0: // we have no bits
565 strRet += pbase64[enc >> 2];
566 left = (enc & 3) << 4;
570 case 1: // we have two bits
571 strRet += pbase64[left | (enc >> 4)];
572 left = (enc & 15) << 2;
576 case 2: // we have four bits
577 strRet += pbase64[left | (enc >> 6)];
578 strRet += pbase64[enc & 63];
586 strRet += pbase64[left];
595 string EncodeBase64(const string& str)
597 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
600 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
602 static const int decode64_table[256] =
604 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
605 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
606 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
607 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
608 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
609 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
610 49, 50, 51, -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, -1, -1, -1, -1,
615 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
616 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
622 vector<unsigned char> vchRet;
623 vchRet.reserve(strlen(p)*3/4);
630 int dec = decode64_table[*p];
631 if (dec == -1) break;
635 case 0: // we have no bits and get 6
640 case 1: // we have 6 bits and keep 4
641 vchRet.push_back((left<<2) | (dec>>4));
646 case 2: // we have 4 bits and get 6, we keep 2
647 vchRet.push_back((left<<4) | (dec>>2));
652 case 3: // we have 2 bits and get 6
653 vchRet.push_back((left<<6) | dec);
662 case 0: // 4n base64 characters processed: ok
665 case 1: // 4n+1 base64 character processed: impossible
669 case 2: // 4n+2 base64 characters processed: require '=='
670 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
674 case 3: // 4n+3 base64 characters processed: require '='
675 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
683 string DecodeBase64(const string& str)
685 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
686 return string((const char*)&vchRet[0], vchRet.size());
690 bool WildcardMatch(const char* psz, const char* mask)
697 return (*psz == '\0');
699 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
714 bool WildcardMatch(const string& str, const string& mask)
716 return WildcardMatch(str.c_str(), mask.c_str());
726 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
729 char pszModule[MAX_PATH];
731 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
733 const char* pszModule = "bitcoin";
736 snprintf(pszMessage, 1000,
737 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
739 snprintf(pszMessage, 1000,
740 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
743 void LogException(std::exception* pex, const char* pszThread)
745 char pszMessage[10000];
746 FormatException(pszMessage, pex, pszThread);
747 printf("\n%s", pszMessage);
750 void PrintException(std::exception* pex, const char* pszThread)
752 char pszMessage[10000];
753 FormatException(pszMessage, pex, pszThread);
754 printf("\n\n************************\n%s\n", pszMessage);
755 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
756 strMiscWarning = pszMessage;
760 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
762 char pszMessage[10000];
763 FormatException(pszMessage, pex, pszThread);
764 printf("\n\n************************\n%s\n", pszMessage);
765 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
766 strMiscWarning = pszMessage;
770 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
772 char pszPath[MAX_PATH] = "";
773 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
777 else if (nFolder == CSIDL_STARTUP)
779 return string(getenv("USERPROFILE")) + "\\Start Menu\\Programs\\Startup";
781 else if (nFolder == CSIDL_APPDATA)
783 return getenv("APPDATA");
789 string GetDefaultDataDir()
791 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
792 // Mac: ~/Library/Application Support/Bitcoin
796 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
798 char* pszHome = getenv("HOME");
799 if (pszHome == NULL || strlen(pszHome) == 0)
800 pszHome = (char*)"/";
801 string strHome = pszHome;
802 if (strHome[strHome.size()-1] != '/')
806 strHome += "Library/Application Support/";
807 filesystem::create_directory(strHome.c_str());
808 return strHome + "Bitcoin";
811 return strHome + ".bitcoin";
816 void GetDataDir(char* pszDir)
818 // pszDir must be at least MAX_PATH length.
820 if (pszSetDataDir[0] != 0)
822 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
827 // This can be called during exceptions by printf, so we cache the
828 // value so we don't have to do memory allocations after that.
829 static char pszCachedDir[MAX_PATH];
830 if (pszCachedDir[0] == 0)
831 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
832 strlcpy(pszDir, pszCachedDir, MAX_PATH);
837 char* p = pszDir + strlen(pszDir);
838 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
840 strcpy(p, "testnet");
843 static bool pfMkdir[4];
844 if (!pfMkdir[nVariation])
846 pfMkdir[nVariation] = true;
847 boost::filesystem::create_directory(pszDir);
853 char pszDir[MAX_PATH];
858 string GetConfigFile()
860 namespace fs = boost::filesystem;
861 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
862 if (!pathConfig.is_complete())
863 pathConfig = fs::path(GetDataDir()) / pathConfig;
864 return pathConfig.string();
867 bool ReadConfigFile(map<string, string>& mapSettingsRet,
868 map<string, vector<string> >& mapMultiSettingsRet)
870 namespace fs = boost::filesystem;
871 namespace pod = boost::program_options::detail;
873 if (mapSettingsRet.count("-datadir"))
875 if (fs::is_directory(fs::system_complete(mapSettingsRet["-datadir"])))
877 fs::path pathDataDir = fs::system_complete(mapSettingsRet["-datadir"]);
878 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
886 fs::ifstream streamConfig(GetConfigFile());
887 if (!streamConfig.good())
888 return true; // No bitcoin.conf file is OK
890 set<string> setOptions;
891 setOptions.insert("*");
893 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
895 // Don't overwrite existing settings so command line settings override bitcoin.conf
896 string strKey = string("-") + it->string_key;
897 if (mapSettingsRet.count(strKey) == 0)
899 mapSettingsRet[strKey] = it->value[0];
900 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
901 InterpretNegativeSetting(strKey, mapSettingsRet);
903 mapMultiSettingsRet[strKey].push_back(it->value[0]);
910 namespace fs = boost::filesystem;
911 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
912 if (!pathConfig.is_complete())
913 pathConfig = fs::path(GetDataDir()) / pathConfig;
914 return pathConfig.string();
917 void CreatePidFile(string pidFile, pid_t pid)
919 FILE* file = fopen(pidFile.c_str(), "w");
922 fprintf(file, "%d\n", pid);
927 int GetFilesize(FILE* file)
929 int nSavePos = ftell(file);
931 if (fseek(file, 0, SEEK_END) == 0)
932 nFilesize = ftell(file);
933 fseek(file, nSavePos, SEEK_SET);
937 void ShrinkDebugFile()
939 // Scroll debug.log if it's getting too big
940 string strFile = GetDataDir() + "/debug.log";
941 FILE* file = fopen(strFile.c_str(), "r");
942 if (file && GetFilesize(file) > 10 * 1000000)
944 // Restart the file with some of the end
946 fseek(file, -sizeof(pch), SEEK_END);
947 int nBytes = fread(pch, 1, sizeof(pch), file);
950 file = fopen(strFile.c_str(), "w");
953 fwrite(pch, 1, nBytes, file);
967 // "Never go to sea with two chronometers; take one or three."
968 // Our three time sources are:
970 // - Median of other nodes's clocks
971 // - The user (asking the user to fix the system clock if the first two disagree)
973 static int64 nMockTime = 0; // For unit testing
977 if (nMockTime) return nMockTime;
982 void SetMockTime(int64 nMockTimeIn)
984 nMockTime = nMockTimeIn;
987 static int64 nTimeOffset = 0;
989 int64 GetAdjustedTime()
991 return GetTime() + nTimeOffset;
994 void AddTimeData(const CNetAddr& ip, int64 nTime)
996 int64 nOffsetSample = nTime - GetTime();
999 static set<CNetAddr> setKnown;
1000 if (!setKnown.insert(ip).second)
1004 vTimeOffsets.input(nOffsetSample);
1005 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1006 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1008 int64 nMedian = vTimeOffsets.median();
1009 std::vector<int64> vSorted = vTimeOffsets.sorted();
1010 // Only let other nodes change our time by so much
1011 if (abs64(nMedian) < 70 * 60)
1013 nTimeOffset = nMedian;
1022 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1023 bool fMatch = false;
1024 BOOST_FOREACH(int64 nOffset, vSorted)
1025 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1031 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1032 strMiscWarning = strMessage;
1033 printf("*** %s\n", strMessage.c_str());
1034 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1039 BOOST_FOREACH(int64 n, vSorted)
1040 printf("%+"PRI64d" ", n);
1043 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1054 string FormatVersion(int nVersion)
1056 if (nVersion%100 == 0)
1057 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1059 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1062 string FormatFullVersion()
1064 string s = FormatVersion(CLIENT_VERSION);
1065 if (VERSION_IS_BETA) {
1072 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1073 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1075 std::ostringstream ss;
1077 ss << name << ":" << FormatVersion(nClientVersion);
1078 if (!comments.empty())
1079 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1086 #ifdef DEBUG_LOCKORDER
1088 // Early deadlock detection.
1089 // Problem being solved:
1090 // Thread 1 locks A, then B, then C
1091 // Thread 2 locks D, then C, then A
1092 // --> may result in deadlock between the two threads, depending on when they run.
1093 // Solution implemented here:
1094 // Keep track of pairs of locks: (A before B), (A before C), etc.
1095 // Complain if any thread trys to lock in a different order.
1098 struct CLockLocation
1100 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1102 mutexName = pszName;
1103 sourceFile = pszFile;
1107 std::string ToString() const
1109 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1113 std::string mutexName;
1114 std::string sourceFile;
1118 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1120 static boost::interprocess::interprocess_mutex dd_mutex;
1121 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1122 static boost::thread_specific_ptr<LockStack> lockstack;
1125 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1127 printf("POTENTIAL DEADLOCK DETECTED\n");
1128 printf("Previous lock order was:\n");
1129 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1131 if (i.first == mismatch.first) printf(" (1)");
1132 if (i.first == mismatch.second) printf(" (2)");
1133 printf(" %s\n", i.second.ToString().c_str());
1135 printf("Current lock order is:\n");
1136 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1138 if (i.first == mismatch.first) printf(" (1)");
1139 if (i.first == mismatch.second) printf(" (2)");
1140 printf(" %s\n", i.second.ToString().c_str());
1144 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1146 bool fOrderOK = true;
1147 if (lockstack.get() == NULL)
1148 lockstack.reset(new LockStack);
1150 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1153 (*lockstack).push_back(std::make_pair(c, locklocation));
1155 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1157 if (i.first == c) break;
1159 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1160 if (lockorders.count(p1))
1162 lockorders[p1] = (*lockstack);
1164 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1165 if (lockorders.count(p2))
1167 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1174 static void pop_lock()
1178 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1179 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1182 (*lockstack).pop_back();
1186 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs)
1188 push_lock(cs, CLockLocation(pszName, pszFile, nLine));
1191 void LeaveCritical()
1196 #endif /* DEBUG_LOCKORDER */