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 COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/algorithm/string/join.hpp>
9 // Work around clang compilation problem in Boost 1.46:
10 // /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
11 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
12 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
14 namespace program_options {
15 std::string to_internal(const std::string&);
19 #include <boost/program_options/detail/config_file.hpp>
20 #include <boost/program_options/parsers.hpp>
21 #include <boost/filesystem.hpp>
22 #include <boost/filesystem/fstream.hpp>
23 #include <boost/interprocess/sync/interprocess_mutex.hpp>
24 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
25 #include <boost/foreach.hpp>
26 #include <boost/thread.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 char pszSetDataDir[MAX_PATH] = "";
37 bool fRequestShutdown = false;
38 bool fShutdown = false;
41 bool fCommandLine = false;
42 string strMiscWarning;
43 bool fTestNet = false;
44 bool fNoListen = false;
45 bool fLogTimestamps = false;
46 CMedianFilter<int64> vTimeOffsets(200,0);
50 // Workaround for "multiple definition of `_tls_used'"
51 // http://svn.boost.org/trac/boost/ticket/4258
52 extern "C" void tss_cleanup_implemented() { }
58 // Init openssl library multithreading support
59 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
60 void locking_callback(int mode, int i, const char* file, int line)
62 if (mode & CRYPTO_LOCK)
63 ppmutexOpenSSL[i]->lock();
65 ppmutexOpenSSL[i]->unlock();
74 // Init openssl library multithreading support
75 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
76 for (int i = 0; i < CRYPTO_num_locks(); i++)
77 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
78 CRYPTO_set_locking_callback(locking_callback);
81 // Seed random number generator with screen scrape and other hardware sources
85 // Seed random number generator with performance counter
90 // Shutdown openssl library multithreading support
91 CRYPTO_set_locking_callback(NULL);
92 for (int i = 0; i < CRYPTO_num_locks(); i++)
93 delete ppmutexOpenSSL[i];
94 OPENSSL_free(ppmutexOpenSSL);
108 // Seed with CPU performance counter
109 int64 nCounter = GetPerformanceCounter();
110 RAND_add(&nCounter, sizeof(nCounter), 1.5);
111 memset(&nCounter, 0, sizeof(nCounter));
114 void RandAddSeedPerfmon()
118 // This can take up to 2 seconds, so only do it every 10 minutes
119 static int64 nLastPerfmon;
120 if (GetTime() < nLastPerfmon + 10 * 60)
122 nLastPerfmon = GetTime();
125 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
126 // Seed with the entire set of perfmon data
127 unsigned char pdata[250000];
128 memset(pdata, 0, sizeof(pdata));
129 unsigned long nSize = sizeof(pdata);
130 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
131 RegCloseKey(HKEY_PERFORMANCE_DATA);
132 if (ret == ERROR_SUCCESS)
134 RAND_add(pdata, nSize, nSize/100.0);
135 memset(pdata, 0, nSize);
136 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
141 uint64 GetRand(uint64 nMax)
146 // The range of the random source must be a multiple of the modulus
147 // to give every possible output value an equal possibility
148 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
151 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
152 while (nRand >= nRange);
153 return (nRand % nMax);
156 int GetRandInt(int nMax)
158 return GetRand(nMax);
171 inline int OutputDebugStringF(const char* pszFormat, ...)
178 va_start(arg_ptr, pszFormat);
179 ret = vprintf(pszFormat, arg_ptr);
184 // print to debug.log
185 static FILE* fileout = NULL;
189 char pszFile[MAX_PATH+100];
191 strlcat(pszFile, "/debug.log", sizeof(pszFile));
192 fileout = fopen(pszFile, "a");
193 if (fileout) setbuf(fileout, NULL); // unbuffered
197 static bool fStartedNewLine = true;
198 static boost::mutex mutexDebugLog;
199 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
201 // Debug print useful for profiling
202 if (fLogTimestamps && fStartedNewLine)
203 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
204 if (pszFormat[strlen(pszFormat) - 1] == '\n')
205 fStartedNewLine = true;
207 fStartedNewLine = false;
210 va_start(arg_ptr, pszFormat);
211 ret = vfprintf(fileout, pszFormat, arg_ptr);
217 if (fPrintToDebugger)
219 static CCriticalSection cs_OutputDebugStringF;
221 // accumulate a line at a time
222 CRITICAL_BLOCK(cs_OutputDebugStringF)
224 static char pszBuffer[50000];
229 va_start(arg_ptr, pszFormat);
230 int limit = END(pszBuffer) - pend - 2;
231 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
233 if (ret < 0 || ret >= limit)
235 pend = END(pszBuffer) - 2;
241 char* p1 = pszBuffer;
243 while ((p2 = strchr(p1, '\n')))
248 OutputDebugStringA(p1);
253 memmove(pszBuffer, p1, pend - p1 + 1);
254 pend -= (p1 - pszBuffer);
263 // - prints up to limit-1 characters
264 // - output string is always null terminated even if limit reached
265 // - return value is the number of characters actually printed
266 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
271 va_start(arg_ptr, format);
272 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
274 if (ret < 0 || ret >= limit)
282 string strprintf(const std::string &format, ...)
286 int limit = sizeof(buffer);
291 va_start(arg_ptr, format);
292 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
294 if (ret >= 0 && ret < limit)
301 throw std::bad_alloc();
303 string str(p, p+ret);
309 bool error(const std::string &format, ...)
312 int limit = sizeof(buffer);
314 va_start(arg_ptr, format);
315 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
317 if (ret < 0 || ret >= limit)
322 printf("ERROR: %s\n", buffer);
327 void ParseString(const string& str, char c, vector<string>& v)
331 string::size_type i1 = 0;
332 string::size_type i2;
335 i2 = str.find(c, i1);
338 v.push_back(str.substr(i1));
341 v.push_back(str.substr(i1, i2-i1));
347 string FormatMoney(int64 n, bool fPlus)
349 // Note: not using straight sprintf here because we do NOT want
350 // localized number formatting.
351 int64 n_abs = (n > 0 ? n : -n);
352 int64 quotient = n_abs/COIN;
353 int64 remainder = n_abs%COIN;
354 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
356 // Right-trim excess 0's before the decimal point:
358 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
361 str.erase(str.size()-nTrim, nTrim);
364 str.insert((unsigned int)0, 1, '-');
365 else if (fPlus && n > 0)
366 str.insert((unsigned int)0, 1, '+');
371 bool ParseMoney(const string& str, int64& nRet)
373 return ParseMoney(str.c_str(), nRet);
376 bool ParseMoney(const char* pszIn, int64& nRet)
380 const char* p = pszIn;
388 int64 nMult = CENT*10;
389 while (isdigit(*p) && (nMult > 0))
391 nUnits += nMult * (*p++ - '0');
400 strWhole.insert(strWhole.end(), *p);
405 if (strWhole.size() > 10) // guard against 63 bit overflow
407 if (nUnits < 0 || nUnits > COIN)
409 int64 nWhole = atoi64(strWhole);
410 int64 nValue = nWhole*COIN + nUnits;
417 static signed char phexdigit[256] =
418 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
419 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
420 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
421 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
422 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
423 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
424 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
425 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
426 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
427 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
428 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
429 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
430 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
431 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
432 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
433 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
435 bool IsHex(const string& str)
437 BOOST_FOREACH(unsigned char c, str)
439 if (phexdigit[c] < 0)
442 return (str.size() > 0) && (str.size()%2 == 0);
445 vector<unsigned char> ParseHex(const char* psz)
447 // convert hex dump to vector
448 vector<unsigned char> vch;
451 while (isspace(*psz))
453 signed char c = phexdigit[(unsigned char)*psz++];
454 if (c == (signed char)-1)
456 unsigned char n = (c << 4);
457 c = phexdigit[(unsigned char)*psz++];
458 if (c == (signed char)-1)
466 vector<unsigned char> ParseHex(const string& str)
468 return ParseHex(str.c_str());
471 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
473 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
474 if (name.find("-no") == 0)
476 std::string positive("-");
477 positive.append(name.begin()+3, name.end());
478 if (mapSettingsRet.count(positive) == 0)
480 bool value = !GetBoolArg(name);
481 mapSettingsRet[positive] = (value ? "1" : "0");
486 void ParseParameters(int argc, const char*const argv[])
489 mapMultiArgs.clear();
490 for (int i = 1; i < argc; i++)
493 strlcpy(psz, argv[i], sizeof(psz));
494 char* pszValue = (char*)"";
495 if (strchr(psz, '='))
497 pszValue = strchr(psz, '=');
508 mapArgs[psz] = pszValue;
509 mapMultiArgs[psz].push_back(pszValue);
513 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
515 string name = entry.first;
517 // interpret --foo as -foo (as long as both are not set)
518 if (name.find("--") == 0)
520 std::string singleDash(name.begin()+1, name.end());
521 if (mapArgs.count(singleDash) == 0)
522 mapArgs[singleDash] = entry.second;
526 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
527 InterpretNegativeSetting(name, mapArgs);
531 std::string GetArg(const std::string& strArg, const std::string& strDefault)
533 if (mapArgs.count(strArg))
534 return mapArgs[strArg];
538 int64 GetArg(const std::string& strArg, int64 nDefault)
540 if (mapArgs.count(strArg))
541 return atoi64(mapArgs[strArg]);
545 bool GetBoolArg(const std::string& strArg, bool fDefault)
547 if (mapArgs.count(strArg))
549 if (mapArgs[strArg].empty())
551 return (atoi(mapArgs[strArg]) != 0);
556 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
558 if (mapArgs.count(strArg))
560 mapArgs[strArg] = strValue;
564 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
567 return SoftSetArg(strArg, std::string("1"));
569 return SoftSetArg(strArg, std::string("0"));
573 string EncodeBase64(const unsigned char* pch, size_t len)
575 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
578 strRet.reserve((len+2)/3*4);
581 const unsigned char *pchEnd = pch+len;
588 case 0: // we have no bits
589 strRet += pbase64[enc >> 2];
590 left = (enc & 3) << 4;
594 case 1: // we have two bits
595 strRet += pbase64[left | (enc >> 4)];
596 left = (enc & 15) << 2;
600 case 2: // we have four bits
601 strRet += pbase64[left | (enc >> 6)];
602 strRet += pbase64[enc & 63];
610 strRet += pbase64[left];
619 string EncodeBase64(const string& str)
621 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
624 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
626 static const int decode64_table[256] =
628 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
629 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
630 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
631 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
632 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
633 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
634 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
635 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
636 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
637 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
638 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
639 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
640 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
646 vector<unsigned char> vchRet;
647 vchRet.reserve(strlen(p)*3/4);
654 int dec = decode64_table[(unsigned char)*p];
655 if (dec == -1) break;
659 case 0: // we have no bits and get 6
664 case 1: // we have 6 bits and keep 4
665 vchRet.push_back((left<<2) | (dec>>4));
670 case 2: // we have 4 bits and get 6, we keep 2
671 vchRet.push_back((left<<4) | (dec>>2));
676 case 3: // we have 2 bits and get 6
677 vchRet.push_back((left<<6) | dec);
686 case 0: // 4n base64 characters processed: ok
689 case 1: // 4n+1 base64 character processed: impossible
693 case 2: // 4n+2 base64 characters processed: require '=='
694 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
698 case 3: // 4n+3 base64 characters processed: require '='
699 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
707 string DecodeBase64(const string& str)
709 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
710 return string((const char*)&vchRet[0], vchRet.size());
714 bool WildcardMatch(const char* psz, const char* mask)
721 return (*psz == '\0');
723 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
738 bool WildcardMatch(const string& str, const string& mask)
740 return WildcardMatch(str.c_str(), mask.c_str());
750 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
753 char pszModule[MAX_PATH];
755 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
757 const char* pszModule = "bitcoin";
760 snprintf(pszMessage, 1000,
761 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
763 snprintf(pszMessage, 1000,
764 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
767 void LogException(std::exception* pex, const char* pszThread)
769 char pszMessage[10000];
770 FormatException(pszMessage, pex, pszThread);
771 printf("\n%s", pszMessage);
774 void PrintException(std::exception* pex, const char* pszThread)
776 char pszMessage[10000];
777 FormatException(pszMessage, pex, pszThread);
778 printf("\n\n************************\n%s\n", pszMessage);
779 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
780 strMiscWarning = pszMessage;
784 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
786 char pszMessage[10000];
787 FormatException(pszMessage, pex, pszThread);
788 printf("\n\n************************\n%s\n", pszMessage);
789 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
790 strMiscWarning = pszMessage;
794 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
796 char pszPath[MAX_PATH] = "";
797 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
801 else if (nFolder == CSIDL_STARTUP)
803 return string(getenv("USERPROFILE")) + "\\Start Menu\\Programs\\Startup";
805 else if (nFolder == CSIDL_APPDATA)
807 return getenv("APPDATA");
813 string GetDefaultDataDir()
815 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
816 // Mac: ~/Library/Application Support/Bitcoin
820 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
822 char* pszHome = getenv("HOME");
823 if (pszHome == NULL || strlen(pszHome) == 0)
824 pszHome = (char*)"/";
825 string strHome = pszHome;
826 if (strHome[strHome.size()-1] != '/')
830 strHome += "Library/Application Support/";
831 filesystem::create_directory(strHome.c_str());
832 return strHome + "Bitcoin";
835 return strHome + ".bitcoin";
840 void GetDataDir(char* pszDir)
842 // pszDir must be at least MAX_PATH length.
844 if (pszSetDataDir[0] != 0)
846 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
851 // This can be called during exceptions by printf, so we cache the
852 // value so we don't have to do memory allocations after that.
853 static char pszCachedDir[MAX_PATH];
854 if (pszCachedDir[0] == 0)
855 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
856 strlcpy(pszDir, pszCachedDir, MAX_PATH);
861 char* p = pszDir + strlen(pszDir);
862 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
864 strcpy(p, "testnet");
867 static bool pfMkdir[4];
868 if (!pfMkdir[nVariation])
870 pfMkdir[nVariation] = true;
871 boost::filesystem::create_directory(pszDir);
877 char pszDir[MAX_PATH];
882 string GetConfigFile()
884 namespace fs = boost::filesystem;
885 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
886 if (!pathConfig.is_complete())
887 pathConfig = fs::path(GetDataDir()) / pathConfig;
888 return pathConfig.string();
891 bool ReadConfigFile(map<string, string>& mapSettingsRet,
892 map<string, vector<string> >& mapMultiSettingsRet)
894 namespace fs = boost::filesystem;
895 namespace pod = boost::program_options::detail;
897 if (mapSettingsRet.count("-datadir"))
899 if (fs::is_directory(fs::system_complete(mapSettingsRet["-datadir"])))
901 fs::path pathDataDir = fs::system_complete(mapSettingsRet["-datadir"]);
902 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
910 fs::ifstream streamConfig(GetConfigFile());
911 if (!streamConfig.good())
912 return true; // No bitcoin.conf file is OK
914 set<string> setOptions;
915 setOptions.insert("*");
917 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
919 // Don't overwrite existing settings so command line settings override bitcoin.conf
920 string strKey = string("-") + it->string_key;
921 if (mapSettingsRet.count(strKey) == 0)
923 mapSettingsRet[strKey] = it->value[0];
924 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
925 InterpretNegativeSetting(strKey, mapSettingsRet);
927 mapMultiSettingsRet[strKey].push_back(it->value[0]);
934 namespace fs = boost::filesystem;
935 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
936 if (!pathConfig.is_complete())
937 pathConfig = fs::path(GetDataDir()) / pathConfig;
938 return pathConfig.string();
941 void CreatePidFile(string pidFile, pid_t pid)
943 FILE* file = fopen(pidFile.c_str(), "w");
946 fprintf(file, "%d\n", pid);
951 int GetFilesize(FILE* file)
953 int nSavePos = ftell(file);
955 if (fseek(file, 0, SEEK_END) == 0)
956 nFilesize = ftell(file);
957 fseek(file, nSavePos, SEEK_SET);
961 void ShrinkDebugFile()
963 // Scroll debug.log if it's getting too big
964 string strFile = GetDataDir() + "/debug.log";
965 FILE* file = fopen(strFile.c_str(), "r");
966 if (file && GetFilesize(file) > 10 * 1000000)
968 // Restart the file with some of the end
970 fseek(file, -sizeof(pch), SEEK_END);
971 int nBytes = fread(pch, 1, sizeof(pch), file);
974 file = fopen(strFile.c_str(), "w");
977 fwrite(pch, 1, nBytes, file);
991 // "Never go to sea with two chronometers; take one or three."
992 // Our three time sources are:
994 // - Median of other nodes's clocks
995 // - The user (asking the user to fix the system clock if the first two disagree)
997 static int64 nMockTime = 0; // For unit testing
1001 if (nMockTime) return nMockTime;
1006 void SetMockTime(int64 nMockTimeIn)
1008 nMockTime = nMockTimeIn;
1011 static int64 nTimeOffset = 0;
1013 int64 GetAdjustedTime()
1015 return GetTime() + nTimeOffset;
1018 void AddTimeData(const CNetAddr& ip, int64 nTime)
1020 int64 nOffsetSample = nTime - GetTime();
1022 // Ignore duplicates
1023 static set<CNetAddr> setKnown;
1024 if (!setKnown.insert(ip).second)
1028 vTimeOffsets.input(nOffsetSample);
1029 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1030 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1032 int64 nMedian = vTimeOffsets.median();
1033 std::vector<int64> vSorted = vTimeOffsets.sorted();
1034 // Only let other nodes change our time by so much
1035 if (abs64(nMedian) < 70 * 60)
1037 nTimeOffset = nMedian;
1046 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1047 bool fMatch = false;
1048 BOOST_FOREACH(int64 nOffset, vSorted)
1049 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1055 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1056 strMiscWarning = strMessage;
1057 printf("*** %s\n", strMessage.c_str());
1058 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
1063 BOOST_FOREACH(int64 n, vSorted)
1064 printf("%+"PRI64d" ", n);
1067 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1078 string FormatVersion(int nVersion)
1080 if (nVersion%100 == 0)
1081 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1083 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1086 string FormatFullVersion()
1088 string s = FormatVersion(CLIENT_VERSION);
1089 if (VERSION_IS_BETA) {
1096 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1097 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1099 std::ostringstream ss;
1101 ss << name << ":" << FormatVersion(nClientVersion);
1102 if (!comments.empty())
1103 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1110 #ifdef DEBUG_LOCKORDER
1112 // Early deadlock detection.
1113 // Problem being solved:
1114 // Thread 1 locks A, then B, then C
1115 // Thread 2 locks D, then C, then A
1116 // --> may result in deadlock between the two threads, depending on when they run.
1117 // Solution implemented here:
1118 // Keep track of pairs of locks: (A before B), (A before C), etc.
1119 // Complain if any thread trys to lock in a different order.
1122 struct CLockLocation
1124 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1126 mutexName = pszName;
1127 sourceFile = pszFile;
1131 std::string ToString() const
1133 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1137 std::string mutexName;
1138 std::string sourceFile;
1142 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
1144 static boost::interprocess::interprocess_mutex dd_mutex;
1145 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
1146 static boost::thread_specific_ptr<LockStack> lockstack;
1149 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
1151 printf("POTENTIAL DEADLOCK DETECTED\n");
1152 printf("Previous lock order was:\n");
1153 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
1155 if (i.first == mismatch.first) printf(" (1)");
1156 if (i.first == mismatch.second) printf(" (2)");
1157 printf(" %s\n", i.second.ToString().c_str());
1159 printf("Current lock order is:\n");
1160 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
1162 if (i.first == mismatch.first) printf(" (1)");
1163 if (i.first == mismatch.second) printf(" (2)");
1164 printf(" %s\n", i.second.ToString().c_str());
1168 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
1170 bool fOrderOK = true;
1171 if (lockstack.get() == NULL)
1172 lockstack.reset(new LockStack);
1174 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1177 (*lockstack).push_back(std::make_pair(c, locklocation));
1179 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1181 if (i.first == c) break;
1183 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1184 if (lockorders.count(p1))
1186 lockorders[p1] = (*lockstack);
1188 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1189 if (lockorders.count(p2))
1191 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1198 static void pop_lock()
1202 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1203 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1206 (*lockstack).pop_back();
1210 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1212 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1213 #ifdef DEBUG_LOCKCONTENTION
1214 bool result = mutex.try_lock();
1217 printf("LOCKCONTENTION: %s\n", pszName);
1218 printf("Locker: %s:%d\n", pszFile, nLine);
1226 void CCriticalSection::Leave()
1231 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1233 push_lock(this, CLockLocation(pszName, pszFile, nLine));
1234 bool result = mutex.try_lock();
1235 if (!result) pop_lock();
1241 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1243 #ifdef DEBUG_LOCKCONTENTION
1244 bool result = mutex.try_lock();
1247 printf("LOCKCONTENTION: %s\n", pszName);
1248 printf("Locker: %s:%d\n", pszFile, nLine);
1256 void CCriticalSection::Leave()
1261 bool CCriticalSection::TryEnter(const char*, const char*, int)
1263 bool result = mutex.try_lock();
1267 #endif /* DEBUG_LOCKORDER */