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 char pszSetDataDir[MAX_PATH] = "";
26 bool fRequestShutdown = false;
27 bool fShutdown = false;
30 bool fCommandLine = false;
31 string strMiscWarning;
32 bool fTestNet = false;
33 bool fNoListen = false;
34 bool fLogTimestamps = false;
35 CMedianFilter<int64> vTimeOffsets(200,0);
37 // Init openssl library multithreading support
38 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
39 void locking_callback(int mode, int i, const char* file, int line)
41 if (mode & CRYPTO_LOCK)
42 ppmutexOpenSSL[i]->lock();
44 ppmutexOpenSSL[i]->unlock();
53 // Init openssl library multithreading support
54 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
55 for (int i = 0; i < CRYPTO_num_locks(); i++)
56 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
57 CRYPTO_set_locking_callback(locking_callback);
60 // Seed random number generator with screen scrape and other hardware sources
64 // Seed random number generator with performance counter
69 // Shutdown openssl library multithreading support
70 CRYPTO_set_locking_callback(NULL);
71 for (int i = 0; i < CRYPTO_num_locks(); i++)
72 delete ppmutexOpenSSL[i];
73 OPENSSL_free(ppmutexOpenSSL);
87 // Seed with CPU performance counter
88 int64 nCounter = GetPerformanceCounter();
89 RAND_add(&nCounter, sizeof(nCounter), 1.5);
90 memset(&nCounter, 0, sizeof(nCounter));
93 void RandAddSeedPerfmon()
97 // This can take up to 2 seconds, so only do it every 10 minutes
98 static int64 nLastPerfmon;
99 if (GetTime() < nLastPerfmon + 10 * 60)
101 nLastPerfmon = GetTime();
104 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
105 // Seed with the entire set of perfmon data
106 unsigned char pdata[250000];
107 memset(pdata, 0, sizeof(pdata));
108 unsigned long nSize = sizeof(pdata);
109 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
110 RegCloseKey(HKEY_PERFORMANCE_DATA);
111 if (ret == ERROR_SUCCESS)
113 RAND_add(pdata, nSize, nSize/100.0);
114 memset(pdata, 0, nSize);
115 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
120 uint64 GetRand(uint64 nMax)
125 // The range of the random source must be a multiple of the modulus
126 // to give every possible output value an equal possibility
127 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
130 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
131 while (nRand >= nRange);
132 return (nRand % nMax);
135 int GetRandInt(int nMax)
137 return GetRand(nMax);
150 inline int OutputDebugStringF(const char* pszFormat, ...)
157 va_start(arg_ptr, pszFormat);
158 ret = vprintf(pszFormat, arg_ptr);
163 // print to debug.log
164 static FILE* fileout = NULL;
168 char pszFile[MAX_PATH+100];
170 strlcat(pszFile, "/debug.log", sizeof(pszFile));
171 fileout = fopen(pszFile, "a");
172 if (fileout) setbuf(fileout, NULL); // unbuffered
176 static bool fStartedNewLine = true;
178 // Debug print useful for profiling
179 if (fLogTimestamps && fStartedNewLine)
180 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
181 if (pszFormat[strlen(pszFormat) - 1] == '\n')
182 fStartedNewLine = true;
184 fStartedNewLine = false;
187 va_start(arg_ptr, pszFormat);
188 ret = vfprintf(fileout, pszFormat, arg_ptr);
194 if (fPrintToDebugger)
196 static CCriticalSection cs_OutputDebugStringF;
198 // accumulate a line at a time
200 LOCK(cs_OutputDebugStringF);
201 static char pszBuffer[50000];
206 va_start(arg_ptr, pszFormat);
207 int limit = END(pszBuffer) - pend - 2;
208 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
210 if (ret < 0 || ret >= limit)
212 pend = END(pszBuffer) - 2;
218 char* p1 = pszBuffer;
220 while (p2 = strchr(p1, '\n'))
225 OutputDebugStringA(p1);
230 memmove(pszBuffer, p1, pend - p1 + 1);
231 pend -= (p1 - pszBuffer);
240 // - prints up to limit-1 characters
241 // - output string is always null terminated even if limit reached
242 // - return value is the number of characters actually printed
243 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
248 va_start(arg_ptr, format);
249 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
251 if (ret < 0 || ret >= limit)
259 string real_strprintf(const std::string &format, int dummy, ...)
263 int limit = sizeof(buffer);
268 va_start(arg_ptr, dummy);
269 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
271 if (ret >= 0 && ret < limit)
278 throw std::bad_alloc();
280 string str(p, p+ret);
286 bool error(const char *format, ...)
289 int limit = sizeof(buffer);
291 va_start(arg_ptr, format);
292 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
294 if (ret < 0 || ret >= limit)
299 printf("ERROR: %s\n", buffer);
304 void ParseString(const string& str, char c, vector<string>& v)
308 string::size_type i1 = 0;
309 string::size_type i2;
312 i2 = str.find(c, i1);
315 v.push_back(str.substr(i1));
318 v.push_back(str.substr(i1, i2-i1));
324 string FormatMoney(int64 n, bool fPlus)
326 // Note: not using straight sprintf here because we do NOT want
327 // localized number formatting.
328 int64 n_abs = (n > 0 ? n : -n);
329 int64 quotient = n_abs/COIN;
330 int64 remainder = n_abs%COIN;
331 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
333 // Right-trim excess 0's before the decimal point:
335 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
338 str.erase(str.size()-nTrim, nTrim);
341 str.insert((unsigned int)0, 1, '-');
342 else if (fPlus && n > 0)
343 str.insert((unsigned int)0, 1, '+');
348 bool ParseMoney(const string& str, int64& nRet)
350 return ParseMoney(str.c_str(), nRet);
353 bool ParseMoney(const char* pszIn, int64& nRet)
357 const char* p = pszIn;
365 int64 nMult = CENT*10;
366 while (isdigit(*p) && (nMult > 0))
368 nUnits += nMult * (*p++ - '0');
377 strWhole.insert(strWhole.end(), *p);
382 if (strWhole.size() > 10) // guard against 63 bit overflow
384 if (nUnits < 0 || nUnits > COIN)
386 int64 nWhole = atoi64(strWhole);
387 int64 nValue = nWhole*COIN + nUnits;
394 static char phexdigit[256] =
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 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
398 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
399 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
410 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
412 bool IsHex(const string& str)
414 BOOST_FOREACH(unsigned char c, str)
416 if (phexdigit[c] < 0)
419 return (str.size() > 0) && (str.size()%2 == 0);
422 vector<unsigned char> ParseHex(const char* psz)
424 // convert hex dump to vector
425 vector<unsigned char> vch;
428 while (isspace(*psz))
430 char c = phexdigit[(unsigned char)*psz++];
433 unsigned char n = (c << 4);
434 c = phexdigit[(unsigned char)*psz++];
443 vector<unsigned char> ParseHex(const string& str)
445 return ParseHex(str.c_str());
448 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
450 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
451 if (name.find("-no") == 0)
453 std::string positive("-");
454 positive.append(name.begin()+3, name.end());
455 if (mapSettingsRet.count(positive) == 0)
457 bool value = !GetBoolArg(name);
458 mapSettingsRet[positive] = (value ? "1" : "0");
463 void ParseParameters(int argc, const char*const argv[])
466 mapMultiArgs.clear();
467 for (int i = 1; i < argc; i++)
470 strlcpy(psz, argv[i], sizeof(psz));
471 char* pszValue = (char*)"";
472 if (strchr(psz, '='))
474 pszValue = strchr(psz, '=');
485 mapArgs[psz] = pszValue;
486 mapMultiArgs[psz].push_back(pszValue);
490 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
492 string name = entry.first;
494 // interpret --foo as -foo (as long as both are not set)
495 if (name.find("--") == 0)
497 std::string singleDash(name.begin()+1, name.end());
498 if (mapArgs.count(singleDash) == 0)
499 mapArgs[singleDash] = entry.second;
503 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
504 InterpretNegativeSetting(name, mapArgs);
508 std::string GetArg(const std::string& strArg, const std::string& strDefault)
510 if (mapArgs.count(strArg))
511 return mapArgs[strArg];
515 int64 GetArg(const std::string& strArg, int64 nDefault)
517 if (mapArgs.count(strArg))
518 return atoi64(mapArgs[strArg]);
522 bool GetBoolArg(const std::string& strArg, bool fDefault)
524 if (mapArgs.count(strArg))
526 if (mapArgs[strArg].empty())
528 return (atoi(mapArgs[strArg]) != 0);
533 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
535 if (mapArgs.count(strArg))
537 mapArgs[strArg] = strValue;
541 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
544 return SoftSetArg(strArg, std::string("1"));
546 return SoftSetArg(strArg, std::string("0"));
550 string EncodeBase64(const unsigned char* pch, size_t len)
552 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
555 strRet.reserve((len+2)/3*4);
558 const unsigned char *pchEnd = pch+len;
565 case 0: // we have no bits
566 strRet += pbase64[enc >> 2];
567 left = (enc & 3) << 4;
571 case 1: // we have two bits
572 strRet += pbase64[left | (enc >> 4)];
573 left = (enc & 15) << 2;
577 case 2: // we have four bits
578 strRet += pbase64[left | (enc >> 6)];
579 strRet += pbase64[enc & 63];
587 strRet += pbase64[left];
596 string EncodeBase64(const string& str)
598 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
601 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
603 static const int decode64_table[256] =
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
607 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
608 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
609 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
610 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
611 49, 50, 51, -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, -1, -1, -1, -1,
617 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
623 vector<unsigned char> vchRet;
624 vchRet.reserve(strlen(p)*3/4);
631 int dec = decode64_table[*p];
632 if (dec == -1) break;
636 case 0: // we have no bits and get 6
641 case 1: // we have 6 bits and keep 4
642 vchRet.push_back((left<<2) | (dec>>4));
647 case 2: // we have 4 bits and get 6, we keep 2
648 vchRet.push_back((left<<4) | (dec>>2));
653 case 3: // we have 2 bits and get 6
654 vchRet.push_back((left<<6) | dec);
663 case 0: // 4n base64 characters processed: ok
666 case 1: // 4n+1 base64 character processed: impossible
670 case 2: // 4n+2 base64 characters processed: require '=='
671 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
675 case 3: // 4n+3 base64 characters processed: require '='
676 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
684 string DecodeBase64(const string& str)
686 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
687 return string((const char*)&vchRet[0], vchRet.size());
691 bool WildcardMatch(const char* psz, const char* mask)
698 return (*psz == '\0');
700 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
715 bool WildcardMatch(const string& str, const string& mask)
717 return WildcardMatch(str.c_str(), mask.c_str());
727 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
730 char pszModule[MAX_PATH];
732 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
734 const char* pszModule = "bitcoin";
737 snprintf(pszMessage, 1000,
738 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
740 snprintf(pszMessage, 1000,
741 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
744 void LogException(std::exception* pex, const char* pszThread)
746 char pszMessage[10000];
747 FormatException(pszMessage, pex, pszThread);
748 printf("\n%s", pszMessage);
751 void PrintException(std::exception* pex, const char* pszThread)
753 char pszMessage[10000];
754 FormatException(pszMessage, pex, pszThread);
755 printf("\n\n************************\n%s\n", pszMessage);
756 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
757 strMiscWarning = pszMessage;
761 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
763 char pszMessage[10000];
764 FormatException(pszMessage, pex, pszThread);
765 printf("\n\n************************\n%s\n", pszMessage);
766 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
767 strMiscWarning = pszMessage;
771 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
773 char pszPath[MAX_PATH] = "";
774 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
778 else if (nFolder == CSIDL_STARTUP)
780 return string(getenv("USERPROFILE")) + "\\Start Menu\\Programs\\Startup";
782 else if (nFolder == CSIDL_APPDATA)
784 return getenv("APPDATA");
790 string GetDefaultDataDir()
792 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
793 // Mac: ~/Library/Application Support/Bitcoin
797 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
799 char* pszHome = getenv("HOME");
800 if (pszHome == NULL || strlen(pszHome) == 0)
801 pszHome = (char*)"/";
802 string strHome = pszHome;
803 if (strHome[strHome.size()-1] != '/')
807 strHome += "Library/Application Support/";
808 filesystem::create_directory(strHome.c_str());
809 return strHome + "Bitcoin";
812 return strHome + ".bitcoin";
817 void GetDataDir(char* pszDir)
819 // pszDir must be at least MAX_PATH length.
821 if (pszSetDataDir[0] != 0)
823 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
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 static char pszCachedDir[MAX_PATH];
831 if (pszCachedDir[0] == 0)
832 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
833 strlcpy(pszDir, pszCachedDir, MAX_PATH);
838 char* p = pszDir + strlen(pszDir);
839 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
841 strcpy(p, "testnet");
844 static bool pfMkdir[4];
845 if (!pfMkdir[nVariation])
847 pfMkdir[nVariation] = true;
848 boost::filesystem::create_directory(pszDir);
854 char pszDir[MAX_PATH];
859 string GetConfigFile()
861 namespace fs = boost::filesystem;
863 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
864 if (!pathConfigFile.is_complete()) pathConfigFile = fs::path(GetDataDir()) / pathConfigFile;
865 return pathConfigFile.string();
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 if (mapSettingsRet.count("-datadir"))
876 if (fs::is_directory(fs::system_complete(mapSettingsRet["-datadir"])))
878 fs::path pathDataDir(fs::system_complete(mapSettingsRet["-datadir"]));
880 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
888 fs::ifstream streamConfig(GetConfigFile());
889 if (!streamConfig.good())
890 return true; // No bitcoin.conf file is OK
892 set<string> setOptions;
893 setOptions.insert("*");
895 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
897 // Don't overwrite existing settings so command line settings override bitcoin.conf
898 string strKey = string("-") + it->string_key;
899 if (mapSettingsRet.count(strKey) == 0)
901 mapSettingsRet[strKey] = it->value[0];
902 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
903 InterpretNegativeSetting(strKey, mapSettingsRet);
905 mapMultiSettingsRet[strKey].push_back(it->value[0]);
912 namespace fs = boost::filesystem;
914 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
915 if (!pathPidFile.is_complete()) pathPidFile = fs::path(GetDataDir()) / pathPidFile;
916 return pathPidFile.string();
919 void CreatePidFile(string pidFile, pid_t pid)
921 FILE* file = fopen(pidFile.c_str(), "w");
924 fprintf(file, "%d\n", pid);
929 int GetFilesize(FILE* file)
931 int nSavePos = ftell(file);
933 if (fseek(file, 0, SEEK_END) == 0)
934 nFilesize = ftell(file);
935 fseek(file, nSavePos, SEEK_SET);
939 void ShrinkDebugFile()
941 // Scroll debug.log if it's getting too big
942 string strFile = GetDataDir() + "/debug.log";
943 FILE* file = fopen(strFile.c_str(), "r");
944 if (file && GetFilesize(file) > 10 * 1000000)
946 // Restart the file with some of the end
948 fseek(file, -sizeof(pch), SEEK_END);
949 int nBytes = fread(pch, 1, sizeof(pch), file);
952 file = fopen(strFile.c_str(), "w");
955 fwrite(pch, 1, nBytes, file);
969 // "Never go to sea with two chronometers; take one or three."
970 // Our three time sources are:
972 // - Median of other nodes's clocks
973 // - The user (asking the user to fix the system clock if the first two disagree)
975 static int64 nMockTime = 0; // For unit testing
979 if (nMockTime) return nMockTime;
984 void SetMockTime(int64 nMockTimeIn)
986 nMockTime = nMockTimeIn;
989 static int64 nTimeOffset = 0;
991 int64 GetAdjustedTime()
993 return GetTime() + nTimeOffset;
996 void AddTimeData(const CNetAddr& ip, int64 nTime)
998 int64 nOffsetSample = nTime - GetTime();
1000 // Ignore duplicates
1001 static set<CNetAddr> setKnown;
1002 if (!setKnown.insert(ip).second)
1006 vTimeOffsets.input(nOffsetSample);
1007 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1008 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1010 int64 nMedian = vTimeOffsets.median();
1011 std::vector<int64> vSorted = vTimeOffsets.sorted();
1012 // Only let other nodes change our time by so much
1013 if (abs64(nMedian) < 70 * 60)
1015 nTimeOffset = nMedian;
1024 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1025 bool fMatch = false;
1026 BOOST_FOREACH(int64 nOffset, vSorted)
1027 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1033 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1034 strMiscWarning = strMessage;
1035 printf("*** %s\n", strMessage.c_str());
1036 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1041 BOOST_FOREACH(int64 n, vSorted)
1042 printf("%+"PRI64d" ", n);
1045 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1056 string FormatVersion(int nVersion)
1058 if (nVersion%100 == 0)
1059 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1061 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1064 string FormatFullVersion()
1066 return CLIENT_BUILD;
1069 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1070 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1072 std::ostringstream ss;
1074 ss << name << ":" << FormatVersion(nClientVersion);
1075 if (!comments.empty())
1076 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1083 #ifdef DEBUG_LOCKORDER
1085 // Early deadlock detection.
1086 // Problem being solved:
1087 // Thread 1 locks A, then B, then C
1088 // Thread 2 locks D, then C, then A
1089 // --> may result in deadlock between the two threads, depending on when they run.
1090 // Solution implemented here:
1091 // Keep track of pairs of locks: (A before B), (A before C), etc.
1092 // Complain if any thread trys to lock in a different order.
1095 struct CLockLocation
1097 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1099 mutexName = pszName;
1100 sourceFile = pszFile;
1104 std::string ToString() const
1106 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1110 std::string mutexName;
1111 std::string sourceFile;
1115 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1117 static boost::interprocess::interprocess_mutex dd_mutex;
1118 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1119 static boost::thread_specific_ptr<LockStack> lockstack;
1122 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1124 printf("POTENTIAL DEADLOCK DETECTED\n");
1125 printf("Previous lock order was:\n");
1126 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1128 if (i.first == mismatch.first) printf(" (1)");
1129 if (i.first == mismatch.second) printf(" (2)");
1130 printf(" %s\n", i.second.ToString().c_str());
1132 printf("Current lock order is:\n");
1133 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1135 if (i.first == mismatch.first) printf(" (1)");
1136 if (i.first == mismatch.second) printf(" (2)");
1137 printf(" %s\n", i.second.ToString().c_str());
1141 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1143 bool fOrderOK = true;
1144 if (lockstack.get() == NULL)
1145 lockstack.reset(new LockStack);
1147 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1150 (*lockstack).push_back(std::make_pair(c, locklocation));
1152 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1154 if (i.first == c) break;
1156 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1157 if (lockorders.count(p1))
1159 lockorders[p1] = (*lockstack);
1161 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1162 if (lockorders.count(p2))
1164 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1171 static void pop_lock()
1175 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1176 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1179 (*lockstack).pop_back();
1183 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1185 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1188 void LeaveCritical()
1193 #endif /* DEBUG_LOCKORDER */