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 <boost/algorithm/string/join.hpp>
11 // Work around clang compilation problem in Boost 1.46:
12 // /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
13 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
14 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
16 namespace program_options {
17 std::string to_internal(const std::string&);
21 #include <boost/program_options/detail/config_file.hpp>
22 #include <boost/program_options/parsers.hpp>
23 #include <boost/filesystem.hpp>
24 #include <boost/filesystem/fstream.hpp>
25 #include <boost/interprocess/sync/interprocess_mutex.hpp>
26 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
27 #include <boost/foreach.hpp>
28 #include <openssl/crypto.h>
29 #include <openssl/rand.h>
33 #pragma warning(disable:4786)
34 #pragma warning(disable:4804)
35 #pragma warning(disable:4805)
36 #pragma warning(disable:4717)
41 #define _WIN32_WINNT 0x0501
45 #define _WIN32_IE 0x0400
46 #define WIN32_LEAN_AND_MEAN 1
55 using namespace boost;
57 map<string, string> mapArgs;
58 map<string, vector<string> > mapMultiArgs;
60 bool fPrintToConsole = false;
61 bool fPrintToDebugger = false;
62 bool fRequestShutdown = false;
63 bool fShutdown = false;
66 bool fCommandLine = false;
67 string strMiscWarning;
68 bool fTestNet = false;
69 bool fNoListen = false;
70 bool fLogTimestamps = false;
71 CMedianFilter<int64> vTimeOffsets(200,0);
73 // Init openssl library multithreading support
74 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
75 void locking_callback(int mode, int i, const char* file, int line)
77 if (mode & CRYPTO_LOCK)
78 ppmutexOpenSSL[i]->lock();
80 ppmutexOpenSSL[i]->unlock();
89 // Init openssl library multithreading support
90 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
91 for (int i = 0; i < CRYPTO_num_locks(); i++)
92 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
93 CRYPTO_set_locking_callback(locking_callback);
96 // Seed random number generator with screen scrape and other hardware sources
100 // Seed random number generator with performance counter
105 // Shutdown openssl library multithreading support
106 CRYPTO_set_locking_callback(NULL);
107 for (int i = 0; i < CRYPTO_num_locks(); i++)
108 delete ppmutexOpenSSL[i];
109 OPENSSL_free(ppmutexOpenSSL);
123 // Seed with CPU performance counter
124 int64 nCounter = GetPerformanceCounter();
125 RAND_add(&nCounter, sizeof(nCounter), 1.5);
126 memset(&nCounter, 0, sizeof(nCounter));
129 void RandAddSeedPerfmon()
133 // This can take up to 2 seconds, so only do it every 10 minutes
134 static int64 nLastPerfmon;
135 if (GetTime() < nLastPerfmon + 10 * 60)
137 nLastPerfmon = GetTime();
140 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
141 // Seed with the entire set of perfmon data
142 unsigned char pdata[250000];
143 memset(pdata, 0, sizeof(pdata));
144 unsigned long nSize = sizeof(pdata);
145 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
146 RegCloseKey(HKEY_PERFORMANCE_DATA);
147 if (ret == ERROR_SUCCESS)
149 RAND_add(pdata, nSize, nSize/100.0);
150 memset(pdata, 0, nSize);
151 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
156 uint64 GetRand(uint64 nMax)
161 // The range of the random source must be a multiple of the modulus
162 // to give every possible output value an equal possibility
163 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
166 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
167 while (nRand >= nRange);
168 return (nRand % nMax);
171 int GetRandInt(int nMax)
173 return GetRand(nMax);
186 inline int OutputDebugStringF(const char* pszFormat, ...)
193 va_start(arg_ptr, pszFormat);
194 ret = vprintf(pszFormat, arg_ptr);
199 // print to debug.log
200 static FILE* fileout = NULL;
204 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
205 fileout = fopen(pathDebug.string().c_str(), "a");
206 if (fileout) setbuf(fileout, NULL); // unbuffered
210 static bool fStartedNewLine = true;
212 // Debug print useful for profiling
213 if (fLogTimestamps && fStartedNewLine)
214 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
215 if (pszFormat[strlen(pszFormat) - 1] == '\n')
216 fStartedNewLine = true;
218 fStartedNewLine = false;
221 va_start(arg_ptr, pszFormat);
222 ret = vfprintf(fileout, pszFormat, arg_ptr);
228 if (fPrintToDebugger)
230 static CCriticalSection cs_OutputDebugStringF;
232 // accumulate a line at a time
234 LOCK(cs_OutputDebugStringF);
235 static char pszBuffer[50000];
240 va_start(arg_ptr, pszFormat);
241 int limit = END(pszBuffer) - pend - 2;
242 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
244 if (ret < 0 || ret >= limit)
246 pend = END(pszBuffer) - 2;
252 char* p1 = pszBuffer;
254 while (p2 = strchr(p1, '\n'))
259 OutputDebugStringA(p1);
264 memmove(pszBuffer, p1, pend - p1 + 1);
265 pend -= (p1 - pszBuffer);
274 // - prints up to limit-1 characters
275 // - output string is always null terminated even if limit reached
276 // - return value is the number of characters actually printed
277 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
282 va_start(arg_ptr, format);
283 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
285 if (ret < 0 || ret >= limit)
293 string real_strprintf(const std::string &format, int dummy, ...)
297 int limit = sizeof(buffer);
302 va_start(arg_ptr, dummy);
303 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
305 if (ret >= 0 && ret < limit)
312 throw std::bad_alloc();
314 string str(p, p+ret);
320 bool error(const char *format, ...)
323 int limit = sizeof(buffer);
325 va_start(arg_ptr, format);
326 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
328 if (ret < 0 || ret >= limit)
332 printf("ERROR: %s\n", buffer);
337 void ParseString(const string& str, char c, vector<string>& v)
341 string::size_type i1 = 0;
342 string::size_type i2;
345 i2 = str.find(c, i1);
348 v.push_back(str.substr(i1));
351 v.push_back(str.substr(i1, i2-i1));
357 string FormatMoney(int64 n, bool fPlus)
359 // Note: not using straight sprintf here because we do NOT want
360 // localized number formatting.
361 int64 n_abs = (n > 0 ? n : -n);
362 int64 quotient = n_abs/COIN;
363 int64 remainder = n_abs%COIN;
364 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
366 // Right-trim excess 0's before the decimal point:
368 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
371 str.erase(str.size()-nTrim, nTrim);
374 str.insert((unsigned int)0, 1, '-');
375 else if (fPlus && n > 0)
376 str.insert((unsigned int)0, 1, '+');
381 bool ParseMoney(const string& str, int64& nRet)
383 return ParseMoney(str.c_str(), nRet);
386 bool ParseMoney(const char* pszIn, int64& nRet)
390 const char* p = pszIn;
398 int64 nMult = CENT*10;
399 while (isdigit(*p) && (nMult > 0))
401 nUnits += nMult * (*p++ - '0');
410 strWhole.insert(strWhole.end(), *p);
415 if (strWhole.size() > 10) // guard against 63 bit overflow
417 if (nUnits < 0 || nUnits > COIN)
419 int64 nWhole = atoi64(strWhole);
420 int64 nValue = nWhole*COIN + nUnits;
427 static char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
432 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
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 -1,-1,-1,-1,-1,-1,-1,-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, };
445 bool IsHex(const string& str)
447 BOOST_FOREACH(unsigned char c, str)
449 if (phexdigit[c] < 0)
452 return (str.size() > 0) && (str.size()%2 == 0);
455 vector<unsigned char> ParseHex(const char* psz)
457 // convert hex dump to vector
458 vector<unsigned char> vch;
461 while (isspace(*psz))
463 char c = phexdigit[(unsigned char)*psz++];
466 unsigned char n = (c << 4);
467 c = phexdigit[(unsigned char)*psz++];
476 vector<unsigned char> ParseHex(const string& str)
478 return ParseHex(str.c_str());
481 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
483 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
484 if (name.find("-no") == 0)
486 std::string positive("-");
487 positive.append(name.begin()+3, name.end());
488 if (mapSettingsRet.count(positive) == 0)
490 bool value = !GetBoolArg(name);
491 mapSettingsRet[positive] = (value ? "1" : "0");
496 void ParseParameters(int argc, const char*const argv[])
499 mapMultiArgs.clear();
500 for (int i = 1; i < argc; i++)
503 strlcpy(psz, argv[i], sizeof(psz));
504 char* pszValue = (char*)"";
505 if (strchr(psz, '='))
507 pszValue = strchr(psz, '=');
518 mapArgs[psz] = pszValue;
519 mapMultiArgs[psz].push_back(pszValue);
523 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
525 string name = entry.first;
527 // interpret --foo as -foo (as long as both are not set)
528 if (name.find("--") == 0)
530 std::string singleDash(name.begin()+1, name.end());
531 if (mapArgs.count(singleDash) == 0)
532 mapArgs[singleDash] = entry.second;
536 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
537 InterpretNegativeSetting(name, mapArgs);
541 std::string GetArg(const std::string& strArg, const std::string& strDefault)
543 if (mapArgs.count(strArg))
544 return mapArgs[strArg];
548 int64 GetArg(const std::string& strArg, int64 nDefault)
550 if (mapArgs.count(strArg))
551 return atoi64(mapArgs[strArg]);
555 bool GetBoolArg(const std::string& strArg, bool fDefault)
557 if (mapArgs.count(strArg))
559 if (mapArgs[strArg].empty())
561 return (atoi(mapArgs[strArg]) != 0);
566 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
568 if (mapArgs.count(strArg))
570 mapArgs[strArg] = strValue;
574 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
577 return SoftSetArg(strArg, std::string("1"));
579 return SoftSetArg(strArg, std::string("0"));
583 string EncodeBase64(const unsigned char* pch, size_t len)
585 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
588 strRet.reserve((len+2)/3*4);
591 const unsigned char *pchEnd = pch+len;
598 case 0: // we have no bits
599 strRet += pbase64[enc >> 2];
600 left = (enc & 3) << 4;
604 case 1: // we have two bits
605 strRet += pbase64[left | (enc >> 4)];
606 left = (enc & 15) << 2;
610 case 2: // we have four bits
611 strRet += pbase64[left | (enc >> 6)];
612 strRet += pbase64[enc & 63];
620 strRet += pbase64[left];
629 string EncodeBase64(const string& str)
631 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
634 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
636 static const int decode64_table[256] =
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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
641 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
642 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
643 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
644 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
648 -1, -1, -1, -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
656 vector<unsigned char> vchRet;
657 vchRet.reserve(strlen(p)*3/4);
664 int dec = decode64_table[(unsigned char)*p];
665 if (dec == -1) break;
669 case 0: // we have no bits and get 6
674 case 1: // we have 6 bits and keep 4
675 vchRet.push_back((left<<2) | (dec>>4));
680 case 2: // we have 4 bits and get 6, we keep 2
681 vchRet.push_back((left<<4) | (dec>>2));
686 case 3: // we have 2 bits and get 6
687 vchRet.push_back((left<<6) | dec);
696 case 0: // 4n base64 characters processed: ok
699 case 1: // 4n+1 base64 character processed: impossible
703 case 2: // 4n+2 base64 characters processed: require '=='
704 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
708 case 3: // 4n+3 base64 characters processed: require '='
709 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
717 string DecodeBase64(const string& str)
719 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
720 return string((const char*)&vchRet[0], vchRet.size());
724 bool WildcardMatch(const char* psz, const char* mask)
731 return (*psz == '\0');
733 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
748 bool WildcardMatch(const string& str, const string& mask)
750 return WildcardMatch(str.c_str(), mask.c_str());
760 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
763 char pszModule[MAX_PATH];
765 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
767 const char* pszModule = "bitcoin";
770 snprintf(pszMessage, 1000,
771 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
773 snprintf(pszMessage, 1000,
774 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
777 void LogException(std::exception* pex, const char* pszThread)
779 char pszMessage[10000];
780 FormatException(pszMessage, pex, pszThread);
781 printf("\n%s", pszMessage);
784 void PrintException(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 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
796 char pszMessage[10000];
797 FormatException(pszMessage, pex, pszThread);
798 printf("\n\n************************\n%s\n", pszMessage);
799 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
800 strMiscWarning = pszMessage;
804 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
806 namespace fs = boost::filesystem;
808 char pszPath[MAX_PATH] = "";
809 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
811 return fs::path(pszPath);
813 else if (nFolder == CSIDL_STARTUP)
815 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
817 else if (nFolder == CSIDL_APPDATA)
819 return fs::path(getenv("APPDATA"));
825 boost::filesystem::path GetDefaultDataDir()
827 namespace fs = boost::filesystem;
829 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
830 // Mac: ~/Library/Application Support/Bitcoin
834 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
837 char* pszHome = getenv("HOME");
838 if (pszHome == NULL || strlen(pszHome) == 0)
839 pathRet = fs::path("/");
841 pathRet = fs::path(pszHome);
844 pathRet /= "Library/Application Support";
845 filesystem::create_directory(pathRet);
846 return pathRet / "Bitcoin";
849 return pathRet / ".bitcoin";
854 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
856 namespace fs = boost::filesystem;
858 static fs::path pathCached[2];
859 static CCriticalSection csPathCached;
860 static bool cachedPath[2] = {false, false};
862 fs::path &path = pathCached[fNetSpecific];
864 // This can be called during exceptions by printf, so we cache the
865 // value so we don't have to do memory allocations after that.
866 if (cachedPath[fNetSpecific])
871 if (mapArgs.count("-datadir")) {
872 path = mapArgs["-datadir"];
874 path = GetDefaultDataDir();
876 if (fNetSpecific && GetBoolArg("-testnet", false))
879 fs::create_directory(path);
881 cachedPath[fNetSpecific]=true;
885 boost::filesystem::path GetConfigFile()
887 namespace fs = boost::filesystem;
889 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
890 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
891 return pathConfigFile;
894 bool ReadConfigFile(map<string, string>& mapSettingsRet,
895 map<string, vector<string> >& mapMultiSettingsRet)
897 namespace fs = boost::filesystem;
898 namespace pod = boost::program_options::detail;
900 fs::ifstream streamConfig(GetConfigFile());
901 if (!streamConfig.good())
902 return true; // No bitcoin.conf file is OK
904 set<string> setOptions;
905 setOptions.insert("*");
907 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
909 // Don't overwrite existing settings so command line settings override bitcoin.conf
910 string strKey = string("-") + it->string_key;
911 if (mapSettingsRet.count(strKey) == 0)
913 mapSettingsRet[strKey] = it->value[0];
914 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
915 InterpretNegativeSetting(strKey, mapSettingsRet);
917 mapMultiSettingsRet[strKey].push_back(it->value[0]);
922 boost::filesystem::path GetPidFile()
924 namespace fs = boost::filesystem;
926 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
927 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
931 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
933 FILE* file = fopen(path.string().c_str(), "w");
936 fprintf(file, "%d\n", pid);
941 int GetFilesize(FILE* file)
943 int nSavePos = ftell(file);
945 if (fseek(file, 0, SEEK_END) == 0)
946 nFilesize = ftell(file);
947 fseek(file, nSavePos, SEEK_SET);
951 void ShrinkDebugFile()
953 // Scroll debug.log if it's getting too big
954 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
955 FILE* file = fopen(pathLog.string().c_str(), "r");
956 if (file && GetFilesize(file) > 10 * 1000000)
958 // Restart the file with some of the end
960 fseek(file, -sizeof(pch), SEEK_END);
961 int nBytes = fread(pch, 1, sizeof(pch), file);
964 file = fopen(pathLog.string().c_str(), "w");
967 fwrite(pch, 1, nBytes, file);
981 // "Never go to sea with two chronometers; take one or three."
982 // Our three time sources are:
984 // - Median of other nodes's clocks
985 // - The user (asking the user to fix the system clock if the first two disagree)
987 static int64 nMockTime = 0; // For unit testing
991 if (nMockTime) return nMockTime;
996 void SetMockTime(int64 nMockTimeIn)
998 nMockTime = nMockTimeIn;
1001 static int64 nTimeOffset = 0;
1003 int64 GetAdjustedTime()
1005 return GetTime() + nTimeOffset;
1008 void AddTimeData(const CNetAddr& ip, int64 nTime)
1010 int64 nOffsetSample = nTime - GetTime();
1012 // Ignore duplicates
1013 static set<CNetAddr> setKnown;
1014 if (!setKnown.insert(ip).second)
1018 vTimeOffsets.input(nOffsetSample);
1019 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1020 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1022 int64 nMedian = vTimeOffsets.median();
1023 std::vector<int64> vSorted = vTimeOffsets.sorted();
1024 // Only let other nodes change our time by so much
1025 if (abs64(nMedian) < 70 * 60)
1027 nTimeOffset = nMedian;
1036 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1037 bool fMatch = false;
1038 BOOST_FOREACH(int64 nOffset, vSorted)
1039 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1045 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1046 strMiscWarning = strMessage;
1047 printf("*** %s\n", strMessage.c_str());
1048 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1053 BOOST_FOREACH(int64 n, vSorted)
1054 printf("%+"PRI64d" ", n);
1057 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1068 string FormatVersion(int nVersion)
1070 if (nVersion%100 == 0)
1071 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1073 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1076 string FormatFullVersion()
1078 return CLIENT_BUILD;
1081 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1082 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1084 std::ostringstream ss;
1086 ss << name << ":" << FormatVersion(nClientVersion);
1087 if (!comments.empty())
1088 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1094 boost::filesystem::path static StartupShortcutPath()
1096 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
1099 bool GetStartOnSystemStartup()
1101 return filesystem::exists(StartupShortcutPath());
1104 bool SetStartOnSystemStartup(bool fAutoStart)
1106 // If the shortcut exists already, remove it for updating
1107 boost::filesystem::remove(StartupShortcutPath());
1113 // Get a pointer to the IShellLink interface.
1114 IShellLink* psl = NULL;
1115 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1116 CLSCTX_INPROC_SERVER, IID_IShellLink,
1117 reinterpret_cast<void**>(&psl));
1119 if (SUCCEEDED(hres))
1121 // Get the current executable path
1122 TCHAR pszExePath[MAX_PATH];
1123 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1125 TCHAR pszArgs[5] = TEXT("-min");
1127 // Set the path to the shortcut target
1128 psl->SetPath(pszExePath);
1129 PathRemoveFileSpec(pszExePath);
1130 psl->SetWorkingDirectory(pszExePath);
1131 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1132 psl->SetArguments(pszArgs);
1134 // Query IShellLink for the IPersistFile interface for
1135 // saving the shortcut in persistent storage.
1136 IPersistFile* ppf = NULL;
1137 hres = psl->QueryInterface(IID_IPersistFile,
1138 reinterpret_cast<void**>(&ppf));
1139 if (SUCCEEDED(hres))
1141 WCHAR pwsz[MAX_PATH];
1142 // Ensure that the string is ANSI.
1143 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1144 // Save the link by calling IPersistFile::Save.
1145 hres = ppf->Save(pwsz, TRUE);
1159 #elif defined(LINUX)
1161 // Follow the Desktop Application Autostart Spec:
1162 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1164 boost::filesystem::path static GetAutostartDir()
1166 namespace fs = boost::filesystem;
1168 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1169 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1170 char* pszHome = getenv("HOME");
1171 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1175 boost::filesystem::path static GetAutostartFilePath()
1177 return GetAutostartDir() / "bitcoin.desktop";
1180 bool GetStartOnSystemStartup()
1182 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1183 if (!optionFile.good())
1185 // Scan through file for "Hidden=true":
1187 while (!optionFile.eof())
1189 getline(optionFile, line);
1190 if (line.find("Hidden") != string::npos &&
1191 line.find("true") != string::npos)
1199 bool SetStartOnSystemStartup(bool fAutoStart)
1202 boost::filesystem::remove(GetAutostartFilePath());
1205 char pszExePath[MAX_PATH+1];
1206 memset(pszExePath, 0, sizeof(pszExePath));
1207 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1210 boost::filesystem::create_directories(GetAutostartDir());
1212 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1213 if (!optionFile.good())
1215 // Write a bitcoin.desktop file to the autostart directory:
1216 optionFile << "[Desktop Entry]\n";
1217 optionFile << "Type=Application\n";
1218 optionFile << "Name=Bitcoin\n";
1219 optionFile << "Exec=" << pszExePath << " -min\n";
1220 optionFile << "Terminal=false\n";
1221 optionFile << "Hidden=false\n";
1228 // TODO: OSX startup stuff; see:
1229 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1231 bool GetStartOnSystemStartup() { return false; }
1232 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1238 #ifdef DEBUG_LOCKORDER
1240 // Early deadlock detection.
1241 // Problem being solved:
1242 // Thread 1 locks A, then B, then C
1243 // Thread 2 locks D, then C, then A
1244 // --> may result in deadlock between the two threads, depending on when they run.
1245 // Solution implemented here:
1246 // Keep track of pairs of locks: (A before B), (A before C), etc.
1247 // Complain if any thread trys to lock in a different order.
1250 struct CLockLocation
1252 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1254 mutexName = pszName;
1255 sourceFile = pszFile;
1259 std::string ToString() const
1261 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1265 std::string mutexName;
1266 std::string sourceFile;
1270 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1272 static boost::interprocess::interprocess_mutex dd_mutex;
1273 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1274 static boost::thread_specific_ptr<LockStack> lockstack;
1277 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1279 printf("POTENTIAL DEADLOCK DETECTED\n");
1280 printf("Previous lock order was:\n");
1281 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1283 if (i.first == mismatch.first) printf(" (1)");
1284 if (i.first == mismatch.second) printf(" (2)");
1285 printf(" %s\n", i.second.ToString().c_str());
1287 printf("Current lock order is:\n");
1288 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
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());
1296 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1298 bool fOrderOK = true;
1299 if (lockstack.get() == NULL)
1300 lockstack.reset(new LockStack);
1302 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1305 (*lockstack).push_back(std::make_pair(c, locklocation));
1307 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1309 if (i.first == c) break;
1311 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1312 if (lockorders.count(p1))
1314 lockorders[p1] = (*lockstack);
1316 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1317 if (lockorders.count(p2))
1319 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1326 static void pop_lock()
1330 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1331 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1334 (*lockstack).pop_back();
1338 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1340 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1343 void LeaveCritical()
1348 #endif /* DEBUG_LOCKORDER */