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.
9 #include "ui_interface.h"
10 #include <boost/algorithm/string/join.hpp>
12 // Work around clang compilation problem in Boost 1.46:
13 // /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
14 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
15 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
17 namespace program_options {
18 std::string to_internal(const std::string&);
22 #include <boost/program_options/detail/config_file.hpp>
23 #include <boost/program_options/parsers.hpp>
24 #include <boost/filesystem.hpp>
25 #include <boost/filesystem/fstream.hpp>
26 #include <boost/interprocess/sync/interprocess_mutex.hpp>
27 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
28 #include <boost/foreach.hpp>
29 #include <boost/thread.hpp>
30 #include <openssl/crypto.h>
31 #include <openssl/rand.h>
35 #pragma warning(disable:4786)
36 #pragma warning(disable:4804)
37 #pragma warning(disable:4805)
38 #pragma warning(disable:4717)
43 #define _WIN32_WINNT 0x0501
47 #define _WIN32_IE 0x0400
48 #define WIN32_LEAN_AND_MEAN 1
57 using namespace boost;
59 map<string, string> mapArgs;
60 map<string, vector<string> > mapMultiArgs;
62 bool fPrintToConsole = false;
63 bool fPrintToDebugger = false;
64 bool fRequestShutdown = false;
65 bool fShutdown = false;
68 bool fCommandLine = false;
69 string strMiscWarning;
70 bool fTestNet = false;
71 bool fNoListen = false;
72 bool fLogTimestamps = false;
73 CMedianFilter<int64> vTimeOffsets(200,0);
75 // Init openssl library multithreading support
76 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
77 void locking_callback(int mode, int i, const char* file, int line)
79 if (mode & CRYPTO_LOCK)
80 ppmutexOpenSSL[i]->lock();
82 ppmutexOpenSSL[i]->unlock();
91 // Init openssl library multithreading support
92 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
93 for (int i = 0; i < CRYPTO_num_locks(); i++)
94 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
95 CRYPTO_set_locking_callback(locking_callback);
98 // Seed random number generator with screen scrape and other hardware sources
102 // Seed random number generator with performance counter
107 // Shutdown openssl library multithreading support
108 CRYPTO_set_locking_callback(NULL);
109 for (int i = 0; i < CRYPTO_num_locks(); i++)
110 delete ppmutexOpenSSL[i];
111 OPENSSL_free(ppmutexOpenSSL);
125 // Seed with CPU performance counter
126 int64 nCounter = GetPerformanceCounter();
127 RAND_add(&nCounter, sizeof(nCounter), 1.5);
128 memset(&nCounter, 0, sizeof(nCounter));
131 void RandAddSeedPerfmon()
135 // This can take up to 2 seconds, so only do it every 10 minutes
136 static int64 nLastPerfmon;
137 if (GetTime() < nLastPerfmon + 10 * 60)
139 nLastPerfmon = GetTime();
142 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
143 // Seed with the entire set of perfmon data
144 unsigned char pdata[250000];
145 memset(pdata, 0, sizeof(pdata));
146 unsigned long nSize = sizeof(pdata);
147 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
148 RegCloseKey(HKEY_PERFORMANCE_DATA);
149 if (ret == ERROR_SUCCESS)
151 RAND_add(pdata, nSize, nSize/100.0);
152 memset(pdata, 0, nSize);
153 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
158 uint64 GetRand(uint64 nMax)
163 // The range of the random source must be a multiple of the modulus
164 // to give every possible output value an equal possibility
165 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
168 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
169 while (nRand >= nRange);
170 return (nRand % nMax);
173 int GetRandInt(int nMax)
175 return GetRand(nMax);
188 inline int OutputDebugStringF(const char* pszFormat, ...)
195 va_start(arg_ptr, pszFormat);
196 ret = vprintf(pszFormat, arg_ptr);
201 // print to debug.log
202 static FILE* fileout = NULL;
206 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
207 fileout = fopen(pathDebug.string().c_str(), "a");
208 if (fileout) setbuf(fileout, NULL); // unbuffered
212 static bool fStartedNewLine = true;
213 static boost::mutex mutexDebugLog;
214 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
216 // Debug print useful for profiling
217 if (fLogTimestamps && fStartedNewLine)
218 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
219 if (pszFormat[strlen(pszFormat) - 1] == '\n')
220 fStartedNewLine = true;
222 fStartedNewLine = false;
225 va_start(arg_ptr, pszFormat);
226 ret = vfprintf(fileout, pszFormat, arg_ptr);
232 if (fPrintToDebugger)
234 static CCriticalSection cs_OutputDebugStringF;
236 // accumulate a line at a time
238 LOCK(cs_OutputDebugStringF);
239 static char pszBuffer[50000];
244 va_start(arg_ptr, pszFormat);
245 int limit = END(pszBuffer) - pend - 2;
246 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
248 if (ret < 0 || ret >= limit)
250 pend = END(pszBuffer) - 2;
256 char* p1 = pszBuffer;
258 while ((p2 = strchr(p1, '\n')))
263 OutputDebugStringA(p1);
268 memmove(pszBuffer, p1, pend - p1 + 1);
269 pend -= (p1 - pszBuffer);
278 // - prints up to limit-1 characters
279 // - output string is always null terminated even if limit reached
280 // - return value is the number of characters actually printed
281 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
286 va_start(arg_ptr, format);
287 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
289 if (ret < 0 || ret >= (int)limit)
297 string real_strprintf(const std::string &format, int dummy, ...)
301 int limit = sizeof(buffer);
306 va_start(arg_ptr, dummy);
307 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
309 if (ret >= 0 && ret < limit)
316 throw std::bad_alloc();
318 string str(p, p+ret);
324 bool error(const char *format, ...)
327 int limit = sizeof(buffer);
329 va_start(arg_ptr, format);
330 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
332 if (ret < 0 || ret >= limit)
336 printf("ERROR: %s\n", buffer);
341 void ParseString(const string& str, char c, vector<string>& v)
345 string::size_type i1 = 0;
346 string::size_type i2;
349 i2 = str.find(c, i1);
352 v.push_back(str.substr(i1));
355 v.push_back(str.substr(i1, i2-i1));
361 string FormatMoney(int64 n, bool fPlus)
363 // Note: not using straight sprintf here because we do NOT want
364 // localized number formatting.
365 int64 n_abs = (n > 0 ? n : -n);
366 int64 quotient = n_abs/COIN;
367 int64 remainder = n_abs%COIN;
368 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
370 // Right-trim excess 0's before the decimal point:
372 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
375 str.erase(str.size()-nTrim, nTrim);
378 str.insert((unsigned int)0, 1, '-');
379 else if (fPlus && n > 0)
380 str.insert((unsigned int)0, 1, '+');
385 bool ParseMoney(const string& str, int64& nRet)
387 return ParseMoney(str.c_str(), nRet);
390 bool ParseMoney(const char* pszIn, int64& nRet)
394 const char* p = pszIn;
402 int64 nMult = CENT*10;
403 while (isdigit(*p) && (nMult > 0))
405 nUnits += nMult * (*p++ - '0');
414 strWhole.insert(strWhole.end(), *p);
419 if (strWhole.size() > 10) // guard against 63 bit overflow
421 if (nUnits < 0 || nUnits > COIN)
423 int64 nWhole = atoi64(strWhole);
424 int64 nValue = nWhole*COIN + nUnits;
431 static signed char phexdigit[256] =
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,
434 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
435 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
436 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
437 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
438 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
439 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
440 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
441 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
442 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
443 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
444 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
445 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
446 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
447 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
449 bool IsHex(const string& str)
451 BOOST_FOREACH(unsigned char c, str)
453 if (phexdigit[c] < 0)
456 return (str.size() > 0) && (str.size()%2 == 0);
459 vector<unsigned char> ParseHex(const char* psz)
461 // convert hex dump to vector
462 vector<unsigned char> vch;
465 while (isspace(*psz))
467 signed char c = phexdigit[(unsigned char)*psz++];
468 if (c == (signed char)-1)
470 unsigned char n = (c << 4);
471 c = phexdigit[(unsigned char)*psz++];
472 if (c == (signed char)-1)
480 vector<unsigned char> ParseHex(const string& str)
482 return ParseHex(str.c_str());
485 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
487 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
488 if (name.find("-no") == 0)
490 std::string positive("-");
491 positive.append(name.begin()+3, name.end());
492 if (mapSettingsRet.count(positive) == 0)
494 bool value = !GetBoolArg(name);
495 mapSettingsRet[positive] = (value ? "1" : "0");
500 void ParseParameters(int argc, const char*const argv[])
503 mapMultiArgs.clear();
504 for (int i = 1; i < argc; i++)
507 strlcpy(psz, argv[i], sizeof(psz));
508 char* pszValue = (char*)"";
509 if (strchr(psz, '='))
511 pszValue = strchr(psz, '=');
522 mapArgs[psz] = pszValue;
523 mapMultiArgs[psz].push_back(pszValue);
527 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
529 string name = entry.first;
531 // interpret --foo as -foo (as long as both are not set)
532 if (name.find("--") == 0)
534 std::string singleDash(name.begin()+1, name.end());
535 if (mapArgs.count(singleDash) == 0)
536 mapArgs[singleDash] = entry.second;
540 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
541 InterpretNegativeSetting(name, mapArgs);
545 std::string GetArg(const std::string& strArg, const std::string& strDefault)
547 if (mapArgs.count(strArg))
548 return mapArgs[strArg];
552 int64 GetArg(const std::string& strArg, int64 nDefault)
554 if (mapArgs.count(strArg))
555 return atoi64(mapArgs[strArg]);
559 bool GetBoolArg(const std::string& strArg, bool fDefault)
561 if (mapArgs.count(strArg))
563 if (mapArgs[strArg].empty())
565 return (atoi(mapArgs[strArg]) != 0);
570 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
572 if (mapArgs.count(strArg))
574 mapArgs[strArg] = strValue;
578 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
581 return SoftSetArg(strArg, std::string("1"));
583 return SoftSetArg(strArg, std::string("0"));
587 string EncodeBase64(const unsigned char* pch, size_t len)
589 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
592 strRet.reserve((len+2)/3*4);
595 const unsigned char *pchEnd = pch+len;
602 case 0: // we have no bits
603 strRet += pbase64[enc >> 2];
604 left = (enc & 3) << 4;
608 case 1: // we have two bits
609 strRet += pbase64[left | (enc >> 4)];
610 left = (enc & 15) << 2;
614 case 2: // we have four bits
615 strRet += pbase64[left | (enc >> 6)];
616 strRet += pbase64[enc & 63];
624 strRet += pbase64[left];
633 string EncodeBase64(const string& str)
635 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
638 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
640 static const int decode64_table[256] =
642 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
643 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
644 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
645 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
646 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
647 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
648 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
649 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
650 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
651 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
652 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
653 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
654 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
660 vector<unsigned char> vchRet;
661 vchRet.reserve(strlen(p)*3/4);
668 int dec = decode64_table[(unsigned char)*p];
669 if (dec == -1) break;
673 case 0: // we have no bits and get 6
678 case 1: // we have 6 bits and keep 4
679 vchRet.push_back((left<<2) | (dec>>4));
684 case 2: // we have 4 bits and get 6, we keep 2
685 vchRet.push_back((left<<4) | (dec>>2));
690 case 3: // we have 2 bits and get 6
691 vchRet.push_back((left<<6) | dec);
700 case 0: // 4n base64 characters processed: ok
703 case 1: // 4n+1 base64 character processed: impossible
707 case 2: // 4n+2 base64 characters processed: require '=='
708 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
712 case 3: // 4n+3 base64 characters processed: require '='
713 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
721 string DecodeBase64(const string& str)
723 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
724 return string((const char*)&vchRet[0], vchRet.size());
728 bool WildcardMatch(const char* psz, const char* mask)
735 return (*psz == '\0');
737 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
752 bool WildcardMatch(const string& str, const string& mask)
754 return WildcardMatch(str.c_str(), mask.c_str());
764 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
767 char pszModule[MAX_PATH];
769 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
771 const char* pszModule = "bitcoin";
774 snprintf(pszMessage, 1000,
775 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
777 snprintf(pszMessage, 1000,
778 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
781 void LogException(std::exception* pex, const char* pszThread)
783 char pszMessage[10000];
784 FormatException(pszMessage, pex, pszThread);
785 printf("\n%s", pszMessage);
788 void PrintException(std::exception* pex, const char* pszThread)
790 char pszMessage[10000];
791 FormatException(pszMessage, pex, pszThread);
792 printf("\n\n************************\n%s\n", pszMessage);
793 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
794 strMiscWarning = pszMessage;
798 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
800 char pszMessage[10000];
801 FormatException(pszMessage, pex, pszThread);
802 printf("\n\n************************\n%s\n", pszMessage);
803 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
804 strMiscWarning = pszMessage;
808 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
810 namespace fs = boost::filesystem;
812 char pszPath[MAX_PATH] = "";
813 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
815 return fs::path(pszPath);
817 else if (nFolder == CSIDL_STARTUP)
819 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
821 else if (nFolder == CSIDL_APPDATA)
823 return fs::path(getenv("APPDATA"));
829 boost::filesystem::path GetDefaultDataDir()
831 namespace fs = boost::filesystem;
833 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
834 // Mac: ~/Library/Application Support/Bitcoin
838 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
841 char* pszHome = getenv("HOME");
842 if (pszHome == NULL || strlen(pszHome) == 0)
843 pathRet = fs::path("/");
845 pathRet = fs::path(pszHome);
848 pathRet /= "Library/Application Support";
849 fs::create_directory(pathRet);
850 return pathRet / "Bitcoin";
853 return pathRet / ".bitcoin";
858 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
860 namespace fs = boost::filesystem;
862 static fs::path pathCached[2];
863 static CCriticalSection csPathCached;
864 static bool cachedPath[2] = {false, false};
866 fs::path &path = pathCached[fNetSpecific];
868 // This can be called during exceptions by printf, so we cache the
869 // value so we don't have to do memory allocations after that.
870 if (cachedPath[fNetSpecific])
875 if (mapArgs.count("-datadir")) {
876 path = fs::system_complete(mapArgs["-datadir"]);
877 if (!fs::is_directory(path)) {
882 path = GetDefaultDataDir();
884 if (fNetSpecific && GetBoolArg("-testnet", false))
887 fs::create_directory(path);
889 cachedPath[fNetSpecific]=true;
893 boost::filesystem::path GetConfigFile()
895 namespace fs = boost::filesystem;
897 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
898 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
899 return pathConfigFile;
902 void ReadConfigFile(map<string, string>& mapSettingsRet,
903 map<string, vector<string> >& mapMultiSettingsRet)
905 namespace fs = boost::filesystem;
906 namespace pod = boost::program_options::detail;
908 fs::ifstream streamConfig(GetConfigFile());
909 if (!streamConfig.good())
910 return; // No bitcoin.conf file is OK
912 set<string> setOptions;
913 setOptions.insert("*");
915 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
917 // Don't overwrite existing settings so command line settings override bitcoin.conf
918 string strKey = string("-") + it->string_key;
919 if (mapSettingsRet.count(strKey) == 0)
921 mapSettingsRet[strKey] = it->value[0];
922 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
923 InterpretNegativeSetting(strKey, mapSettingsRet);
925 mapMultiSettingsRet[strKey].push_back(it->value[0]);
929 boost::filesystem::path GetPidFile()
931 namespace fs = boost::filesystem;
933 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
934 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
938 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
940 FILE* file = fopen(path.string().c_str(), "w");
943 fprintf(file, "%d\n", pid);
948 int GetFilesize(FILE* file)
950 int nSavePos = ftell(file);
952 if (fseek(file, 0, SEEK_END) == 0)
953 nFilesize = ftell(file);
954 fseek(file, nSavePos, SEEK_SET);
958 void ShrinkDebugFile()
960 // Scroll debug.log if it's getting too big
961 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
962 FILE* file = fopen(pathLog.string().c_str(), "r");
963 if (file && GetFilesize(file) > 10 * 1000000)
965 // Restart the file with some of the end
967 fseek(file, -sizeof(pch), SEEK_END);
968 int nBytes = fread(pch, 1, sizeof(pch), file);
971 file = fopen(pathLog.string().c_str(), "w");
974 fwrite(pch, 1, nBytes, file);
988 // "Never go to sea with two chronometers; take one or three."
989 // Our three time sources are:
991 // - Median of other nodes's clocks
992 // - The user (asking the user to fix the system clock if the first two disagree)
994 static int64 nMockTime = 0; // For unit testing
998 if (nMockTime) return nMockTime;
1003 void SetMockTime(int64 nMockTimeIn)
1005 nMockTime = nMockTimeIn;
1008 static int64 nTimeOffset = 0;
1010 int64 GetAdjustedTime()
1012 return GetTime() + nTimeOffset;
1015 void AddTimeData(const CNetAddr& ip, int64 nTime)
1017 int64 nOffsetSample = nTime - GetTime();
1019 // Ignore duplicates
1020 static set<CNetAddr> setKnown;
1021 if (!setKnown.insert(ip).second)
1025 vTimeOffsets.input(nOffsetSample);
1026 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1027 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1029 int64 nMedian = vTimeOffsets.median();
1030 std::vector<int64> vSorted = vTimeOffsets.sorted();
1031 // Only let other nodes change our time by so much
1032 if (abs64(nMedian) < 70 * 60)
1034 nTimeOffset = nMedian;
1043 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1044 bool fMatch = false;
1045 BOOST_FOREACH(int64 nOffset, vSorted)
1046 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1052 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1053 strMiscWarning = strMessage;
1054 printf("*** %s\n", strMessage.c_str());
1055 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1060 BOOST_FOREACH(int64 n, vSorted)
1061 printf("%+"PRI64d" ", n);
1064 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1075 string FormatVersion(int nVersion)
1077 if (nVersion%100 == 0)
1078 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1080 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1083 string FormatFullVersion()
1085 return CLIENT_BUILD;
1088 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1089 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1091 std::ostringstream ss;
1093 ss << name << ":" << FormatVersion(nClientVersion);
1094 if (!comments.empty())
1095 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1101 boost::filesystem::path static StartupShortcutPath()
1103 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
1106 bool GetStartOnSystemStartup()
1108 return filesystem::exists(StartupShortcutPath());
1111 bool SetStartOnSystemStartup(bool fAutoStart)
1113 // If the shortcut exists already, remove it for updating
1114 boost::filesystem::remove(StartupShortcutPath());
1120 // Get a pointer to the IShellLink interface.
1121 IShellLink* psl = NULL;
1122 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1123 CLSCTX_INPROC_SERVER, IID_IShellLink,
1124 reinterpret_cast<void**>(&psl));
1126 if (SUCCEEDED(hres))
1128 // Get the current executable path
1129 TCHAR pszExePath[MAX_PATH];
1130 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1132 TCHAR pszArgs[5] = TEXT("-min");
1134 // Set the path to the shortcut target
1135 psl->SetPath(pszExePath);
1136 PathRemoveFileSpec(pszExePath);
1137 psl->SetWorkingDirectory(pszExePath);
1138 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1139 psl->SetArguments(pszArgs);
1141 // Query IShellLink for the IPersistFile interface for
1142 // saving the shortcut in persistent storage.
1143 IPersistFile* ppf = NULL;
1144 hres = psl->QueryInterface(IID_IPersistFile,
1145 reinterpret_cast<void**>(&ppf));
1146 if (SUCCEEDED(hres))
1148 WCHAR pwsz[MAX_PATH];
1149 // Ensure that the string is ANSI.
1150 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1151 // Save the link by calling IPersistFile::Save.
1152 hres = ppf->Save(pwsz, TRUE);
1166 #elif defined(LINUX)
1168 // Follow the Desktop Application Autostart Spec:
1169 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1171 boost::filesystem::path static GetAutostartDir()
1173 namespace fs = boost::filesystem;
1175 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1176 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1177 char* pszHome = getenv("HOME");
1178 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1182 boost::filesystem::path static GetAutostartFilePath()
1184 return GetAutostartDir() / "bitcoin.desktop";
1187 bool GetStartOnSystemStartup()
1189 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1190 if (!optionFile.good())
1192 // Scan through file for "Hidden=true":
1194 while (!optionFile.eof())
1196 getline(optionFile, line);
1197 if (line.find("Hidden") != string::npos &&
1198 line.find("true") != string::npos)
1206 bool SetStartOnSystemStartup(bool fAutoStart)
1209 boost::filesystem::remove(GetAutostartFilePath());
1212 char pszExePath[MAX_PATH+1];
1213 memset(pszExePath, 0, sizeof(pszExePath));
1214 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1217 boost::filesystem::create_directories(GetAutostartDir());
1219 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1220 if (!optionFile.good())
1222 // Write a bitcoin.desktop file to the autostart directory:
1223 optionFile << "[Desktop Entry]\n";
1224 optionFile << "Type=Application\n";
1225 optionFile << "Name=Bitcoin\n";
1226 optionFile << "Exec=" << pszExePath << " -min\n";
1227 optionFile << "Terminal=false\n";
1228 optionFile << "Hidden=false\n";
1235 // TODO: OSX startup stuff; see:
1236 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1238 bool GetStartOnSystemStartup() { return false; }
1239 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1245 #ifdef DEBUG_LOCKORDER
1247 // Early deadlock detection.
1248 // Problem being solved:
1249 // Thread 1 locks A, then B, then C
1250 // Thread 2 locks D, then C, then A
1251 // --> may result in deadlock between the two threads, depending on when they run.
1252 // Solution implemented here:
1253 // Keep track of pairs of locks: (A before B), (A before C), etc.
1254 // Complain if any thread trys to lock in a different order.
1257 struct CLockLocation
1259 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1261 mutexName = pszName;
1262 sourceFile = pszFile;
1266 std::string ToString() const
1268 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1272 std::string mutexName;
1273 std::string sourceFile;
1277 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1279 static boost::interprocess::interprocess_mutex dd_mutex;
1280 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1281 static boost::thread_specific_ptr<LockStack> lockstack;
1284 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1286 printf("POTENTIAL DEADLOCK DETECTED\n");
1287 printf("Previous lock order was:\n");
1288 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1290 if (i.first == mismatch.first) printf(" (1)");
1291 if (i.first == mismatch.second) printf(" (2)");
1292 printf(" %s\n", i.second.ToString().c_str());
1294 printf("Current lock order is:\n");
1295 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1297 if (i.first == mismatch.first) printf(" (1)");
1298 if (i.first == mismatch.second) printf(" (2)");
1299 printf(" %s\n", i.second.ToString().c_str());
1303 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1305 bool fOrderOK = true;
1306 if (lockstack.get() == NULL)
1307 lockstack.reset(new LockStack);
1309 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1312 (*lockstack).push_back(std::make_pair(c, locklocation));
1314 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1316 if (i.first == c) break;
1318 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1319 if (lockorders.count(p1))
1321 lockorders[p1] = (*lockstack);
1323 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1324 if (lockorders.count(p2))
1326 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1333 static void pop_lock()
1337 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1338 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1341 (*lockstack).pop_back();
1345 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1347 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1350 void LeaveCritical()
1355 #endif /* DEBUG_LOCKORDER */