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.
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 <openssl/crypto.h>
30 #include <openssl/rand.h>
34 #pragma warning(disable:4786)
35 #pragma warning(disable:4804)
36 #pragma warning(disable:4805)
37 #pragma warning(disable:4717)
42 #define _WIN32_WINNT 0x0501
46 #define _WIN32_IE 0x0400
47 #define WIN32_LEAN_AND_MEAN 1
56 using namespace boost;
58 map<string, string> mapArgs;
59 map<string, vector<string> > mapMultiArgs;
61 bool fPrintToConsole = false;
62 bool fPrintToDebugger = false;
63 bool fRequestShutdown = false;
64 bool fShutdown = false;
67 bool fCommandLine = false;
68 string strMiscWarning;
69 bool fTestNet = false;
70 bool fNoListen = false;
71 bool fLogTimestamps = false;
72 CMedianFilter<int64> vTimeOffsets(200,0);
74 // Init openssl library multithreading support
75 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
76 void locking_callback(int mode, int i, const char* file, int line)
78 if (mode & CRYPTO_LOCK)
79 ppmutexOpenSSL[i]->lock();
81 ppmutexOpenSSL[i]->unlock();
90 // Init openssl library multithreading support
91 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
92 for (int i = 0; i < CRYPTO_num_locks(); i++)
93 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
94 CRYPTO_set_locking_callback(locking_callback);
97 // Seed random number generator with screen scrape and other hardware sources
101 // Seed random number generator with performance counter
106 // Shutdown openssl library multithreading support
107 CRYPTO_set_locking_callback(NULL);
108 for (int i = 0; i < CRYPTO_num_locks(); i++)
109 delete ppmutexOpenSSL[i];
110 OPENSSL_free(ppmutexOpenSSL);
124 // Seed with CPU performance counter
125 int64 nCounter = GetPerformanceCounter();
126 RAND_add(&nCounter, sizeof(nCounter), 1.5);
127 memset(&nCounter, 0, sizeof(nCounter));
130 void RandAddSeedPerfmon()
134 // This can take up to 2 seconds, so only do it every 10 minutes
135 static int64 nLastPerfmon;
136 if (GetTime() < nLastPerfmon + 10 * 60)
138 nLastPerfmon = GetTime();
141 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
142 // Seed with the entire set of perfmon data
143 unsigned char pdata[250000];
144 memset(pdata, 0, sizeof(pdata));
145 unsigned long nSize = sizeof(pdata);
146 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
147 RegCloseKey(HKEY_PERFORMANCE_DATA);
148 if (ret == ERROR_SUCCESS)
150 RAND_add(pdata, nSize, nSize/100.0);
151 memset(pdata, 0, nSize);
152 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
157 uint64 GetRand(uint64 nMax)
162 // The range of the random source must be a multiple of the modulus
163 // to give every possible output value an equal possibility
164 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
167 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
168 while (nRand >= nRange);
169 return (nRand % nMax);
172 int GetRandInt(int nMax)
174 return GetRand(nMax);
177 uint256 GetRandHash()
180 RAND_bytes((unsigned char*)&hash, sizeof(hash));
193 inline int OutputDebugStringF(const char* pszFormat, ...)
200 va_start(arg_ptr, pszFormat);
201 ret = vprintf(pszFormat, arg_ptr);
206 // print to debug.log
207 static FILE* fileout = NULL;
211 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
212 fileout = fopen(pathDebug.string().c_str(), "a");
213 if (fileout) setbuf(fileout, NULL); // unbuffered
217 static bool fStartedNewLine = true;
219 // Debug print useful for profiling
220 if (fLogTimestamps && fStartedNewLine)
221 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
222 if (pszFormat[strlen(pszFormat) - 1] == '\n')
223 fStartedNewLine = true;
225 fStartedNewLine = false;
228 va_start(arg_ptr, pszFormat);
229 ret = vfprintf(fileout, pszFormat, arg_ptr);
235 if (fPrintToDebugger)
237 static CCriticalSection cs_OutputDebugStringF;
239 // accumulate a line at a time
241 LOCK(cs_OutputDebugStringF);
242 static char pszBuffer[50000];
247 va_start(arg_ptr, pszFormat);
248 int limit = END(pszBuffer) - pend - 2;
249 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
251 if (ret < 0 || ret >= limit)
253 pend = END(pszBuffer) - 2;
259 char* p1 = pszBuffer;
261 while ((p2 = strchr(p1, '\n')))
266 OutputDebugStringA(p1);
271 memmove(pszBuffer, p1, pend - p1 + 1);
272 pend -= (p1 - pszBuffer);
281 // - prints up to limit-1 characters
282 // - output string is always null terminated even if limit reached
283 // - return value is the number of characters actually printed
284 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
289 va_start(arg_ptr, format);
290 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
292 if (ret < 0 || ret >= (int)limit)
300 string real_strprintf(const std::string &format, int dummy, ...)
304 int limit = sizeof(buffer);
309 va_start(arg_ptr, dummy);
310 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
312 if (ret >= 0 && ret < limit)
319 throw std::bad_alloc();
321 string str(p, p+ret);
327 bool error(const char *format, ...)
330 int limit = sizeof(buffer);
332 va_start(arg_ptr, format);
333 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
335 if (ret < 0 || ret >= limit)
339 printf("ERROR: %s\n", buffer);
344 void ParseString(const string& str, char c, vector<string>& v)
348 string::size_type i1 = 0;
349 string::size_type i2;
352 i2 = str.find(c, i1);
355 v.push_back(str.substr(i1));
358 v.push_back(str.substr(i1, i2-i1));
364 string FormatMoney(int64 n, bool fPlus)
366 // Note: not using straight sprintf here because we do NOT want
367 // localized number formatting.
368 int64 n_abs = (n > 0 ? n : -n);
369 int64 quotient = n_abs/COIN;
370 int64 remainder = n_abs%COIN;
371 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
373 // Right-trim excess 0's before the decimal point:
375 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
378 str.erase(str.size()-nTrim, nTrim);
381 str.insert((unsigned int)0, 1, '-');
382 else if (fPlus && n > 0)
383 str.insert((unsigned int)0, 1, '+');
388 bool ParseMoney(const string& str, int64& nRet)
390 return ParseMoney(str.c_str(), nRet);
393 bool ParseMoney(const char* pszIn, int64& nRet)
397 const char* p = pszIn;
405 int64 nMult = CENT*10;
406 while (isdigit(*p) && (nMult > 0))
408 nUnits += nMult * (*p++ - '0');
417 strWhole.insert(strWhole.end(), *p);
422 if (strWhole.size() > 10) // guard against 63 bit overflow
424 if (nUnits < 0 || nUnits > COIN)
426 int64 nWhole = atoi64(strWhole);
427 int64 nValue = nWhole*COIN + nUnits;
434 static signed char phexdigit[256] =
435 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
436 -1,-1,-1,-1,-1,-1,-1,-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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
439 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
448 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
449 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
450 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
452 bool IsHex(const string& str)
454 BOOST_FOREACH(unsigned char c, str)
456 if (phexdigit[c] < 0)
459 return (str.size() > 0) && (str.size()%2 == 0);
462 vector<unsigned char> ParseHex(const char* psz)
464 // convert hex dump to vector
465 vector<unsigned char> vch;
468 while (isspace(*psz))
470 signed char c = phexdigit[(unsigned char)*psz++];
471 if (c == (signed char)-1)
473 unsigned char n = (c << 4);
474 c = phexdigit[(unsigned char)*psz++];
475 if (c == (signed char)-1)
483 vector<unsigned char> ParseHex(const string& str)
485 return ParseHex(str.c_str());
488 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
490 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
491 if (name.find("-no") == 0)
493 std::string positive("-");
494 positive.append(name.begin()+3, name.end());
495 if (mapSettingsRet.count(positive) == 0)
497 bool value = !GetBoolArg(name);
498 mapSettingsRet[positive] = (value ? "1" : "0");
503 void ParseParameters(int argc, const char*const argv[])
506 mapMultiArgs.clear();
507 for (int i = 1; i < argc; i++)
510 strlcpy(psz, argv[i], sizeof(psz));
511 char* pszValue = (char*)"";
512 if (strchr(psz, '='))
514 pszValue = strchr(psz, '=');
525 mapArgs[psz] = pszValue;
526 mapMultiArgs[psz].push_back(pszValue);
530 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
532 string name = entry.first;
534 // interpret --foo as -foo (as long as both are not set)
535 if (name.find("--") == 0)
537 std::string singleDash(name.begin()+1, name.end());
538 if (mapArgs.count(singleDash) == 0)
539 mapArgs[singleDash] = entry.second;
543 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
544 InterpretNegativeSetting(name, mapArgs);
548 std::string GetArg(const std::string& strArg, const std::string& strDefault)
550 if (mapArgs.count(strArg))
551 return mapArgs[strArg];
555 int64 GetArg(const std::string& strArg, int64 nDefault)
557 if (mapArgs.count(strArg))
558 return atoi64(mapArgs[strArg]);
562 bool GetBoolArg(const std::string& strArg, bool fDefault)
564 if (mapArgs.count(strArg))
566 if (mapArgs[strArg].empty())
568 return (atoi(mapArgs[strArg]) != 0);
573 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
575 if (mapArgs.count(strArg))
577 mapArgs[strArg] = strValue;
581 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
584 return SoftSetArg(strArg, std::string("1"));
586 return SoftSetArg(strArg, std::string("0"));
590 string EncodeBase64(const unsigned char* pch, size_t len)
592 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
595 strRet.reserve((len+2)/3*4);
598 const unsigned char *pchEnd = pch+len;
605 case 0: // we have no bits
606 strRet += pbase64[enc >> 2];
607 left = (enc & 3) << 4;
611 case 1: // we have two bits
612 strRet += pbase64[left | (enc >> 4)];
613 left = (enc & 15) << 2;
617 case 2: // we have four bits
618 strRet += pbase64[left | (enc >> 6)];
619 strRet += pbase64[enc & 63];
627 strRet += pbase64[left];
636 string EncodeBase64(const string& str)
638 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
641 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
643 static const int decode64_table[256] =
645 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
646 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
647 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
648 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
649 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
650 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
651 49, 50, 51, -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, -1, -1, -1, -1,
655 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
656 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
657 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
663 vector<unsigned char> vchRet;
664 vchRet.reserve(strlen(p)*3/4);
671 int dec = decode64_table[(unsigned char)*p];
672 if (dec == -1) break;
676 case 0: // we have no bits and get 6
681 case 1: // we have 6 bits and keep 4
682 vchRet.push_back((left<<2) | (dec>>4));
687 case 2: // we have 4 bits and get 6, we keep 2
688 vchRet.push_back((left<<4) | (dec>>2));
693 case 3: // we have 2 bits and get 6
694 vchRet.push_back((left<<6) | dec);
703 case 0: // 4n base64 characters processed: ok
706 case 1: // 4n+1 base64 character processed: impossible
710 case 2: // 4n+2 base64 characters processed: require '=='
711 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
715 case 3: // 4n+3 base64 characters processed: require '='
716 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
724 string DecodeBase64(const string& str)
726 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
727 return string((const char*)&vchRet[0], vchRet.size());
731 bool WildcardMatch(const char* psz, const char* mask)
738 return (*psz == '\0');
740 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
755 bool WildcardMatch(const string& str, const string& mask)
757 return WildcardMatch(str.c_str(), mask.c_str());
767 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
770 char pszModule[MAX_PATH];
772 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
774 const char* pszModule = "bitcoin";
777 snprintf(pszMessage, 1000,
778 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
780 snprintf(pszMessage, 1000,
781 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
784 void LogException(std::exception* pex, const char* pszThread)
786 char pszMessage[10000];
787 FormatException(pszMessage, pex, pszThread);
788 printf("\n%s", pszMessage);
791 void PrintException(std::exception* pex, const char* pszThread)
793 char pszMessage[10000];
794 FormatException(pszMessage, pex, pszThread);
795 printf("\n\n************************\n%s\n", pszMessage);
796 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
797 strMiscWarning = pszMessage;
801 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
803 char pszMessage[10000];
804 FormatException(pszMessage, pex, pszThread);
805 printf("\n\n************************\n%s\n", pszMessage);
806 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
807 strMiscWarning = pszMessage;
811 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
813 namespace fs = boost::filesystem;
815 char pszPath[MAX_PATH] = "";
816 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
818 return fs::path(pszPath);
820 else if (nFolder == CSIDL_STARTUP)
822 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
824 else if (nFolder == CSIDL_APPDATA)
826 return fs::path(getenv("APPDATA"));
832 boost::filesystem::path GetDefaultDataDir()
834 namespace fs = boost::filesystem;
836 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
837 // Mac: ~/Library/Application Support/Bitcoin
841 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
844 char* pszHome = getenv("HOME");
845 if (pszHome == NULL || strlen(pszHome) == 0)
846 pathRet = fs::path("/");
848 pathRet = fs::path(pszHome);
851 pathRet /= "Library/Application Support";
852 filesystem::create_directory(pathRet);
853 return pathRet / "Bitcoin";
856 return pathRet / ".bitcoin";
861 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
863 namespace fs = boost::filesystem;
865 static fs::path pathCached[2];
866 static CCriticalSection csPathCached;
867 static bool cachedPath[2] = {false, false};
869 fs::path &path = pathCached[fNetSpecific];
871 // This can be called during exceptions by printf, so we cache the
872 // value so we don't have to do memory allocations after that.
873 if (cachedPath[fNetSpecific])
878 if (mapArgs.count("-datadir")) {
879 path = fs::system_complete(mapArgs["-datadir"]);
880 if (!fs::is_directory(path)) {
885 path = GetDefaultDataDir();
887 if (fNetSpecific && GetBoolArg("-testnet", false))
890 fs::create_directory(path);
892 cachedPath[fNetSpecific]=true;
896 boost::filesystem::path GetConfigFile()
898 namespace fs = boost::filesystem;
900 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
901 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
902 return pathConfigFile;
905 void ReadConfigFile(map<string, string>& mapSettingsRet,
906 map<string, vector<string> >& mapMultiSettingsRet)
908 namespace fs = boost::filesystem;
909 namespace pod = boost::program_options::detail;
911 fs::ifstream streamConfig(GetConfigFile());
912 if (!streamConfig.good())
913 return; // No bitcoin.conf file is OK
915 set<string> setOptions;
916 setOptions.insert("*");
918 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
920 // Don't overwrite existing settings so command line settings override bitcoin.conf
921 string strKey = string("-") + it->string_key;
922 if (mapSettingsRet.count(strKey) == 0)
924 mapSettingsRet[strKey] = it->value[0];
925 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
926 InterpretNegativeSetting(strKey, mapSettingsRet);
928 mapMultiSettingsRet[strKey].push_back(it->value[0]);
932 boost::filesystem::path GetPidFile()
934 namespace fs = boost::filesystem;
936 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
937 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
941 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
943 FILE* file = fopen(path.string().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 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
965 FILE* file = fopen(pathLog.string().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(pathLog.string().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 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
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 return CLIENT_BUILD;
1091 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1092 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1094 std::ostringstream ss;
1096 ss << name << ":" << FormatVersion(nClientVersion);
1097 if (!comments.empty())
1098 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1104 boost::filesystem::path static StartupShortcutPath()
1106 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
1109 bool GetStartOnSystemStartup()
1111 return filesystem::exists(StartupShortcutPath());
1114 bool SetStartOnSystemStartup(bool fAutoStart)
1116 // If the shortcut exists already, remove it for updating
1117 boost::filesystem::remove(StartupShortcutPath());
1123 // Get a pointer to the IShellLink interface.
1124 IShellLink* psl = NULL;
1125 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1126 CLSCTX_INPROC_SERVER, IID_IShellLink,
1127 reinterpret_cast<void**>(&psl));
1129 if (SUCCEEDED(hres))
1131 // Get the current executable path
1132 TCHAR pszExePath[MAX_PATH];
1133 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1135 TCHAR pszArgs[5] = TEXT("-min");
1137 // Set the path to the shortcut target
1138 psl->SetPath(pszExePath);
1139 PathRemoveFileSpec(pszExePath);
1140 psl->SetWorkingDirectory(pszExePath);
1141 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1142 psl->SetArguments(pszArgs);
1144 // Query IShellLink for the IPersistFile interface for
1145 // saving the shortcut in persistent storage.
1146 IPersistFile* ppf = NULL;
1147 hres = psl->QueryInterface(IID_IPersistFile,
1148 reinterpret_cast<void**>(&ppf));
1149 if (SUCCEEDED(hres))
1151 WCHAR pwsz[MAX_PATH];
1152 // Ensure that the string is ANSI.
1153 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1154 // Save the link by calling IPersistFile::Save.
1155 hres = ppf->Save(pwsz, TRUE);
1169 #elif defined(LINUX)
1171 // Follow the Desktop Application Autostart Spec:
1172 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1174 boost::filesystem::path static GetAutostartDir()
1176 namespace fs = boost::filesystem;
1178 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1179 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1180 char* pszHome = getenv("HOME");
1181 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1185 boost::filesystem::path static GetAutostartFilePath()
1187 return GetAutostartDir() / "bitcoin.desktop";
1190 bool GetStartOnSystemStartup()
1192 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1193 if (!optionFile.good())
1195 // Scan through file for "Hidden=true":
1197 while (!optionFile.eof())
1199 getline(optionFile, line);
1200 if (line.find("Hidden") != string::npos &&
1201 line.find("true") != string::npos)
1209 bool SetStartOnSystemStartup(bool fAutoStart)
1212 boost::filesystem::remove(GetAutostartFilePath());
1215 char pszExePath[MAX_PATH+1];
1216 memset(pszExePath, 0, sizeof(pszExePath));
1217 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1220 boost::filesystem::create_directories(GetAutostartDir());
1222 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1223 if (!optionFile.good())
1225 // Write a bitcoin.desktop file to the autostart directory:
1226 optionFile << "[Desktop Entry]\n";
1227 optionFile << "Type=Application\n";
1228 optionFile << "Name=Bitcoin\n";
1229 optionFile << "Exec=" << pszExePath << " -min\n";
1230 optionFile << "Terminal=false\n";
1231 optionFile << "Hidden=false\n";
1238 // TODO: OSX startup stuff; see:
1239 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1241 bool GetStartOnSystemStartup() { return false; }
1242 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1248 #ifdef DEBUG_LOCKORDER
1250 // Early deadlock detection.
1251 // Problem being solved:
1252 // Thread 1 locks A, then B, then C
1253 // Thread 2 locks D, then C, then A
1254 // --> may result in deadlock between the two threads, depending on when they run.
1255 // Solution implemented here:
1256 // Keep track of pairs of locks: (A before B), (A before C), etc.
1257 // Complain if any thread trys to lock in a different order.
1260 struct CLockLocation
1262 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1264 mutexName = pszName;
1265 sourceFile = pszFile;
1269 std::string ToString() const
1271 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1275 std::string mutexName;
1276 std::string sourceFile;
1280 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1282 static boost::interprocess::interprocess_mutex dd_mutex;
1283 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1284 static boost::thread_specific_ptr<LockStack> lockstack;
1287 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1289 printf("POTENTIAL DEADLOCK DETECTED\n");
1290 printf("Previous lock order was:\n");
1291 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1293 if (i.first == mismatch.first) printf(" (1)");
1294 if (i.first == mismatch.second) printf(" (2)");
1295 printf(" %s\n", i.second.ToString().c_str());
1297 printf("Current lock order is:\n");
1298 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1300 if (i.first == mismatch.first) printf(" (1)");
1301 if (i.first == mismatch.second) printf(" (2)");
1302 printf(" %s\n", i.second.ToString().c_str());
1306 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1308 bool fOrderOK = true;
1309 if (lockstack.get() == NULL)
1310 lockstack.reset(new LockStack);
1312 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1315 (*lockstack).push_back(std::make_pair(c, locklocation));
1317 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1319 if (i.first == c) break;
1321 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1322 if (lockorders.count(p1))
1324 lockorders[p1] = (*lockstack);
1326 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1327 if (lockorders.count(p2))
1329 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1336 static void pop_lock()
1340 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1341 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1344 (*lockstack).pop_back();
1348 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1350 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1353 void LeaveCritical()
1358 #endif /* DEBUG_LOCKORDER */