-
+ E9F41F507EC543B7F5F51C89504E6A1DAE600B4FAC7515E597E40CDDDCE2DB08EC97F29FA12D082146BC70A2DDA197C02EC6C603F5E18D5299F35864F9F7661D
bitcoin/src/util.cpp
(0 . 0)(1 . 1208)
24648 // /****************************\
24649 // * EXPERIMENTAL BRANCH. *
24650 // * FOR LABORATORY USE ONLY. *
24651 // ********************************
24652 // ************
24653 // **************
24654 // ****************
24655 // **** **** ****
24656 // *** *** ***
24657 // *** *** ***
24658 // *** * * **
24659 // ******** ********
24660 // ******* ******
24661 // *** **
24662 // * ******* **
24663 // ** * * * * *
24664 // ** * * ***
24665 // **** * * * * ****
24666 // **** *** * * ** ***
24667 // **** ********* ******
24668 // ******* ***** *******
24669 // ********* ****** **
24670 // ** ****** ******
24671 // ** ******* **
24672 // ** ******* ***
24673 // **** ******** ************
24674 // ************ ************
24675 // ******** *******
24676 // ****** ****
24677 // *** ***
24678 // ********************************
24679 // Copyright (c) 2009-2010 Satoshi Nakamoto
24680 // Copyright (c) 2009-2012 The Bitcoin developers
24681 // Distributed under the MIT/X11 software license, see the accompanying
24682 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
24683 #include "headers.h"
24684 #include "strlcpy.h"
24685 #include <boost/program_options/detail/config_file.hpp>
24686 #include <boost/program_options/parsers.hpp>
24687 #include <boost/filesystem.hpp>
24688 #include <boost/filesystem/fstream.hpp>
24689 #include <boost/interprocess/sync/interprocess_mutex.hpp>
24690 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
24691 #include <boost/foreach.hpp>
24692
24693 using namespace std;
24694 using namespace boost;
24695
24696 map<string, string> mapArgs;
24697 map<string, vector<string> > mapMultiArgs;
24698 bool fDebug = false;
24699 bool fPrintToConsole = false;
24700 bool fPrintToDebugger = false;
24701 char pszSetDataDir[MAX_PATH] = "";
24702 bool fRequestShutdown = false;
24703 bool fShutdown = false;
24704 bool fDaemon = false;
24705 bool fServer = false;
24706 bool fCommandLine = false;
24707 string strMiscWarning;
24708 bool fTestNet = false;
24709 bool fNoListen = false;
24710 bool fLogTimestamps = false;
24711
24712
24713
24714
24715 // Workaround for "multiple definition of `_tls_used'"
24716 // http://svn.boost.org/trac/boost/ticket/4258
24717 extern "C" void tss_cleanup_implemented() { }
24718
24719
24720
24721
24722
24723 // Init openssl library multithreading support
24724 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
24725 void locking_callback(int mode, int i, const char* file, int line)
24726 {
24727 if (mode & CRYPTO_LOCK)
24728 ppmutexOpenSSL[i]->lock();
24729 else
24730 ppmutexOpenSSL[i]->unlock();
24731 }
24732
24733 // Init
24734 class CInit
24735 {
24736 public:
24737 CInit()
24738 {
24739 // Init openssl library multithreading support
24740 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
24741 for (int i = 0; i < CRYPTO_num_locks(); i++)
24742 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
24743 CRYPTO_set_locking_callback(locking_callback);
24744
24745 #ifdef WIN32
24746 // Seed random number generator with screen scrape and other hardware sources
24747 RAND_screen();
24748 #endif
24749
24750 // Seed random number generator with performance counter
24751 RandAddSeed();
24752 }
24753 ~CInit()
24754 {
24755 // Shutdown openssl library multithreading support
24756 CRYPTO_set_locking_callback(NULL);
24757 for (int i = 0; i < CRYPTO_num_locks(); i++)
24758 delete ppmutexOpenSSL[i];
24759 OPENSSL_free(ppmutexOpenSSL);
24760 }
24761 }
24762 instance_of_cinit;
24763
24764
24765
24766
24767
24768
24769
24770
24771 void RandAddSeed()
24772 {
24773 // Seed with CPU performance counter
24774 int64 nCounter = GetPerformanceCounter();
24775 RAND_add(&nCounter, sizeof(nCounter), 1.5);
24776 memset(&nCounter, 0, sizeof(nCounter));
24777 }
24778
24779 void RandAddSeedPerfmon()
24780 {
24781 RandAddSeed();
24782
24783 // This can take up to 2 seconds, so only do it every 10 minutes
24784 static int64 nLastPerfmon;
24785 if (GetTime() < nLastPerfmon + 10 * 60)
24786 return;
24787 nLastPerfmon = GetTime();
24788
24789 #ifdef WIN32
24790 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
24791 // Seed with the entire set of perfmon data
24792 unsigned char pdata[250000];
24793 memset(pdata, 0, sizeof(pdata));
24794 unsigned long nSize = sizeof(pdata);
24795 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
24796 RegCloseKey(HKEY_PERFORMANCE_DATA);
24797 if (ret == ERROR_SUCCESS)
24798 {
24799 RAND_add(pdata, nSize, nSize/100.0);
24800 memset(pdata, 0, nSize);
24801 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
24802 }
24803 #endif
24804 }
24805
24806 uint64 GetRand(uint64 nMax)
24807 {
24808 if (nMax == 0)
24809 return 0;
24810
24811 // The range of the random source must be a multiple of the modulus
24812 // to give every possible output value an equal possibility
24813 uint64 nRange = (UINT64_MAX / nMax) * nMax;
24814 uint64 nRand = 0;
24815 do
24816 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
24817 while (nRand >= nRange);
24818 return (nRand % nMax);
24819 }
24820
24821 int GetRandInt(int nMax)
24822 {
24823 return GetRand(nMax);
24824 }
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836 inline int OutputDebugStringF(const char* pszFormat, ...)
24837 {
24838 int ret = 0;
24839 if (fPrintToConsole)
24840 {
24841 // print to console
24842 va_list arg_ptr;
24843 va_start(arg_ptr, pszFormat);
24844 ret = vprintf(pszFormat, arg_ptr);
24845 va_end(arg_ptr);
24846 }
24847 else
24848 {
24849 // print to debug.log
24850 static FILE* fileout = NULL;
24851
24852 if (!fileout)
24853 {
24854 char pszFile[MAX_PATH+100];
24855 GetDataDir(pszFile);
24856 strlcat(pszFile, "/debug.log", sizeof(pszFile));
24857 fileout = fopen(pszFile, "a");
24858 if (fileout) setbuf(fileout, NULL); // unbuffered
24859 }
24860 if (fileout)
24861 {
24862 static bool fStartedNewLine = true;
24863
24864 // Debug print useful for profiling
24865 if (fLogTimestamps && fStartedNewLine)
24866 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
24867 if (pszFormat[strlen(pszFormat) - 1] == '\n')
24868 fStartedNewLine = true;
24869 else
24870 fStartedNewLine = false;
24871
24872 va_list arg_ptr;
24873 va_start(arg_ptr, pszFormat);
24874 ret = vfprintf(fileout, pszFormat, arg_ptr);
24875 va_end(arg_ptr);
24876 }
24877 }
24878
24879 #ifdef WIN32
24880 if (fPrintToDebugger)
24881 {
24882 static CCriticalSection cs_OutputDebugStringF;
24883
24884 // accumulate a line at a time
24885 CRITICAL_BLOCK(cs_OutputDebugStringF)
24886 {
24887 static char pszBuffer[50000];
24888 static char* pend;
24889 if (pend == NULL)
24890 pend = pszBuffer;
24891 va_list arg_ptr;
24892 va_start(arg_ptr, pszFormat);
24893 int limit = END(pszBuffer) - pend - 2;
24894 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
24895 va_end(arg_ptr);
24896 if (ret < 0 || ret >= limit)
24897 {
24898 pend = END(pszBuffer) - 2;
24899 *pend++ = '\n';
24900 }
24901 else
24902 pend += ret;
24903 *pend = '\0';
24904 char* p1 = pszBuffer;
24905 char* p2;
24906 while (p2 = strchr(p1, '\n'))
24907 {
24908 p2++;
24909 char c = *p2;
24910 *p2 = '\0';
24911 OutputDebugStringA(p1);
24912 *p2 = c;
24913 p1 = p2;
24914 }
24915 if (p1 != pszBuffer)
24916 memmove(pszBuffer, p1, pend - p1 + 1);
24917 pend -= (p1 - pszBuffer);
24918 }
24919 }
24920 #endif
24921 return ret;
24922 }
24923
24924
24925 // Safer snprintf
24926 // - prints up to limit-1 characters
24927 // - output string is always null terminated even if limit reached
24928 // - return value is the number of characters actually printed
24929 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
24930 {
24931 if (limit == 0)
24932 return 0;
24933 va_list arg_ptr;
24934 va_start(arg_ptr, format);
24935 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
24936 va_end(arg_ptr);
24937 if (ret < 0 || ret >= limit)
24938 {
24939 ret = limit - 1;
24940 buffer[limit-1] = 0;
24941 }
24942 return ret;
24943 }
24944
24945 string strprintf(const std::string &format, ...)
24946 {
24947 char buffer[50000];
24948 char* p = buffer;
24949 int limit = sizeof(buffer);
24950 int ret;
24951 loop
24952 {
24953 va_list arg_ptr;
24954 va_start(arg_ptr, format);
24955 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
24956 va_end(arg_ptr);
24957 if (ret >= 0 && ret < limit)
24958 break;
24959 if (p != buffer)
24960 delete[] p;
24961 limit *= 2;
24962 p = new char[limit];
24963 if (p == NULL)
24964 throw std::bad_alloc();
24965 }
24966 string str(p, p+ret);
24967 if (p != buffer)
24968 delete[] p;
24969 return str;
24970 }
24971
24972 bool error(const std::string &format, ...)
24973 {
24974 char buffer[50000];
24975 int limit = sizeof(buffer);
24976 va_list arg_ptr;
24977 va_start(arg_ptr, format);
24978 int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
24979 va_end(arg_ptr);
24980 if (ret < 0 || ret >= limit)
24981 {
24982 ret = limit - 1;
24983 buffer[limit-1] = 0;
24984 }
24985 printf("ERROR: %s\n", buffer);
24986 return false;
24987 }
24988
24989
24990 void ParseString(const string& str, char c, vector<string>& v)
24991 {
24992 if (str.empty())
24993 return;
24994 string::size_type i1 = 0;
24995 string::size_type i2;
24996 loop
24997 {
24998 i2 = str.find(c, i1);
24999 if (i2 == str.npos)
25000 {
25001 v.push_back(str.substr(i1));
25002 return;
25003 }
25004 v.push_back(str.substr(i1, i2-i1));
25005 i1 = i2+1;
25006 }
25007 }
25008
25009
25010 string FormatMoney(int64 n, bool fPlus)
25011 {
25012 // Note: not using straight sprintf here because we do NOT want
25013 // localized number formatting.
25014 int64 n_abs = (n > 0 ? n : -n);
25015 int64 quotient = n_abs/COIN;
25016 int64 remainder = n_abs%COIN;
25017 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
25018
25019 // Right-trim excess 0's before the decimal point:
25020 int nTrim = 0;
25021 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
25022 ++nTrim;
25023 if (nTrim)
25024 str.erase(str.size()-nTrim, nTrim);
25025
25026 if (n < 0)
25027 str.insert((unsigned int)0, 1, '-');
25028 else if (fPlus && n > 0)
25029 str.insert((unsigned int)0, 1, '+');
25030 return str;
25031 }
25032
25033
25034 bool ParseMoney(const string& str, int64& nRet)
25035 {
25036 return ParseMoney(str.c_str(), nRet);
25037 }
25038
25039 bool ParseMoney(const char* pszIn, int64& nRet)
25040 {
25041 string strWhole;
25042 int64 nUnits = 0;
25043 const char* p = pszIn;
25044 while (isspace(*p))
25045 p++;
25046 for (; *p; p++)
25047 {
25048 if (*p == '.')
25049 {
25050 p++;
25051 int64 nMult = CENT*10;
25052 while (isdigit(*p) && (nMult > 0))
25053 {
25054 nUnits += nMult * (*p++ - '0');
25055 nMult /= 10;
25056 }
25057 break;
25058 }
25059 if (isspace(*p))
25060 break;
25061 if (!isdigit(*p))
25062 return false;
25063 strWhole.insert(strWhole.end(), *p);
25064 }
25065 for (; *p; p++)
25066 if (!isspace(*p))
25067 return false;
25068 if (strWhole.size() > 10) // guard against 63 bit overflow
25069 return false;
25070 if (nUnits < 0 || nUnits > COIN)
25071 return false;
25072 int64 nWhole = atoi64(strWhole);
25073 int64 nValue = nWhole*COIN + nUnits;
25074
25075 nRet = nValue;
25076 return true;
25077 }
25078
25079
25080 vector<unsigned char> ParseHex(const char* psz)
25081 {
25082 static char phexdigit[256] =
25083 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25084 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25085 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25086 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
25087 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25088 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25089 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
25090 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25091 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25092 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25093 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25094 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25095 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25096 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25097 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
25098 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
25099
25100 // convert hex dump to vector
25101 vector<unsigned char> vch;
25102 loop
25103 {
25104 while (isspace(*psz))
25105 psz++;
25106 char c = phexdigit[(unsigned char)*psz++];
25107 if (c == (char)-1)
25108 break;
25109 unsigned char n = (c << 4);
25110 c = phexdigit[(unsigned char)*psz++];
25111 if (c == (char)-1)
25112 break;
25113 n |= c;
25114 vch.push_back(n);
25115 }
25116 return vch;
25117 }
25118
25119 vector<unsigned char> ParseHex(const string& str)
25120 {
25121 return ParseHex(str.c_str());
25122 }
25123
25124 void ParseParameters(int argc, char* argv[])
25125 {
25126 mapArgs.clear();
25127 mapMultiArgs.clear();
25128 for (int i = 1; i < argc; i++)
25129 {
25130 char psz[10000];
25131 strlcpy(psz, argv[i], sizeof(psz));
25132 char* pszValue = (char*)"";
25133 if (strchr(psz, '='))
25134 {
25135 pszValue = strchr(psz, '=');
25136 *pszValue++ = '\0';
25137 }
25138 #ifdef WIN32
25139 _strlwr(psz);
25140 if (psz[0] == '/')
25141 psz[0] = '-';
25142 #endif
25143 if (psz[0] != '-')
25144 break;
25145 mapArgs[psz] = pszValue;
25146 mapMultiArgs[psz].push_back(pszValue);
25147 }
25148 }
25149
25150 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
25151 {
25152 if (mapArgs.count(strArg))
25153 return false;
25154 mapArgs[strArg] = strValue;
25155 return true;
25156 }
25157
25158 bool SoftSetArg(const std::string& strArg, bool fValue)
25159 {
25160 if (fValue)
25161 return SoftSetArg(strArg, std::string("1"));
25162 else
25163 return SoftSetArg(strArg, std::string("0"));
25164 }
25165
25166
25167 string EncodeBase64(const unsigned char* pch, size_t len)
25168 {
25169 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
25170
25171 string strRet="";
25172 strRet.reserve((len+2)/3*4);
25173
25174 int mode=0, left=0;
25175 const unsigned char *pchEnd = pch+len;
25176
25177 while (pch<pchEnd)
25178 {
25179 int enc = *(pch++);
25180 switch (mode)
25181 {
25182 case 0: // we have no bits
25183 strRet += pbase64[enc >> 2];
25184 left = (enc & 3) << 4;
25185 mode = 1;
25186 break;
25187
25188 case 1: // we have two bits
25189 strRet += pbase64[left | (enc >> 4)];
25190 left = (enc & 15) << 2;
25191 mode = 2;
25192 break;
25193
25194 case 2: // we have four bits
25195 strRet += pbase64[left | (enc >> 6)];
25196 strRet += pbase64[enc & 63];
25197 mode = 0;
25198 break;
25199 }
25200 }
25201
25202 if (mode)
25203 {
25204 strRet += pbase64[left];
25205 strRet += '=';
25206 if (mode == 1)
25207 strRet += '=';
25208 }
25209
25210 return strRet;
25211 }
25212
25213 string EncodeBase64(const string& str)
25214 {
25215 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
25216 }
25217
25218 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
25219 {
25220 static const int decode64_table[256] =
25221 {
25222 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25223 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25224 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
25225 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
25226 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
25227 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
25228 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25229 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25230 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25231 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25232 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25233 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25234 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
25235 };
25236
25237 if (pfInvalid)
25238 *pfInvalid = false;
25239
25240 vector<unsigned char> vchRet;
25241 vchRet.reserve(strlen(p)*3/4);
25242
25243 int mode = 0;
25244 int left = 0;
25245
25246 while (1)
25247 {
25248 int dec = decode64_table[*p];
25249 if (dec == -1) break;
25250 p++;
25251 switch (mode)
25252 {
25253 case 0: // we have no bits and get 6
25254 left = dec;
25255 mode = 1;
25256 break;
25257
25258 case 1: // we have 6 bits and keep 4
25259 vchRet.push_back((left<<2) | (dec>>4));
25260 left = dec & 15;
25261 mode = 2;
25262 break;
25263
25264 case 2: // we have 4 bits and get 6, we keep 2
25265 vchRet.push_back((left<<4) | (dec>>2));
25266 left = dec & 3;
25267 mode = 3;
25268 break;
25269
25270 case 3: // we have 2 bits and get 6
25271 vchRet.push_back((left<<6) | dec);
25272 mode = 0;
25273 break;
25274 }
25275 }
25276
25277 if (pfInvalid)
25278 switch (mode)
25279 {
25280 case 0: // 4n base64 characters processed: ok
25281 break;
25282
25283 case 1: // 4n+1 base64 character processed: impossible
25284 *pfInvalid = true;
25285 break;
25286
25287 case 2: // 4n+2 base64 characters processed: require '=='
25288 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
25289 *pfInvalid = true;
25290 break;
25291
25292 case 3: // 4n+3 base64 characters processed: require '='
25293 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
25294 *pfInvalid = true;
25295 break;
25296 }
25297
25298 return vchRet;
25299 }
25300
25301 string DecodeBase64(const string& str)
25302 {
25303 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
25304 return string((const char*)&vchRet[0], vchRet.size());
25305 }
25306
25307
25308 bool WildcardMatch(const char* psz, const char* mask)
25309 {
25310 loop
25311 {
25312 switch (*mask)
25313 {
25314 case '\0':
25315 return (*psz == '\0');
25316 case '*':
25317 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
25318 case '?':
25319 if (*psz == '\0')
25320 return false;
25321 break;
25322 default:
25323 if (*psz != *mask)
25324 return false;
25325 break;
25326 }
25327 psz++;
25328 mask++;
25329 }
25330 }
25331
25332 bool WildcardMatch(const string& str, const string& mask)
25333 {
25334 return WildcardMatch(str.c_str(), mask.c_str());
25335 }
25336
25337
25338
25339
25340
25341
25342
25343
25344 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
25345 {
25346 #ifdef WIN32
25347 char pszModule[MAX_PATH];
25348 pszModule[0] = '\0';
25349 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
25350 #else
25351 const char* pszModule = "bitcoin";
25352 #endif
25353 if (pex)
25354 snprintf(pszMessage, 1000,
25355 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
25356 else
25357 snprintf(pszMessage, 1000,
25358 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
25359 }
25360
25361 void LogException(std::exception* pex, const char* pszThread)
25362 {
25363 char pszMessage[10000];
25364 FormatException(pszMessage, pex, pszThread);
25365 printf("\n%s", pszMessage);
25366 }
25367
25368 void PrintException(std::exception* pex, const char* pszThread)
25369 {
25370 char pszMessage[10000];
25371 FormatException(pszMessage, pex, pszThread);
25372 printf("\n\n************************\n%s\n", pszMessage);
25373 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
25374 strMiscWarning = pszMessage;
25375 throw;
25376 }
25377
25378 void ThreadOneMessageBox(string strMessage)
25379 {
25380 // Skip message boxes if one is already open
25381 static bool fMessageBoxOpen;
25382 if (fMessageBoxOpen)
25383 return;
25384 fMessageBoxOpen = true;
25385 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
25386 fMessageBoxOpen = false;
25387 }
25388
25389 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
25390 {
25391 char pszMessage[10000];
25392 FormatException(pszMessage, pex, pszThread);
25393 printf("\n\n************************\n%s\n", pszMessage);
25394 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
25395 strMiscWarning = pszMessage;
25396 }
25397
25398
25399
25400
25401
25402
25403
25404
25405 #ifdef WIN32
25406 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
25407
25408 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
25409 {
25410 char pszPath[MAX_PATH+100] = "";
25411
25412 // SHGetSpecialFolderPath isn't always available on old Windows versions
25413 HMODULE hShell32 = LoadLibraryA("shell32.dll");
25414 if (hShell32)
25415 {
25416 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
25417 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
25418 bool fSuccess = false;
25419 if (pSHGetSpecialFolderPath)
25420 fSuccess =
25421 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
25422 FreeModule(hShell32);
25423 if (fSuccess)
25424 return pszPath;
25425 }
25426
25427 // Backup option
25428 std::string strPath;
25429 {
25430 const char *pszEnv;
25431 if (nFolder == CSIDL_STARTUP)
25432 {
25433 pszEnv = getenv("USERPROFILE");
25434 if (pszEnv)
25435 strPath = pszEnv;
25436 strPath += "\\Start Menu\\Programs\\Startup";
25437 }
25438 else if (nFolder == CSIDL_APPDATA)
25439 {
25440 pszEnv = getenv("APPDATA");
25441 if (pszEnv)
25442 strPath = pszEnv;
25443 }
25444 }
25445
25446 return strPath;
25447 }
25448 #endif
25449
25450 string GetDefaultDataDir()
25451 {
25452 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
25453 // Mac: ~/Library/Application Support/Bitcoin
25454 // Unix: ~/.bitcoin
25455 #ifdef WIN32
25456 // Windows
25457 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
25458 #else
25459 char* pszHome = getenv("HOME");
25460 if (pszHome == NULL || strlen(pszHome) == 0)
25461 pszHome = (char*)"/";
25462 string strHome = pszHome;
25463 if (strHome[strHome.size()-1] != '/')
25464 strHome += '/';
25465 #ifdef MAC_OSX
25466 // Mac
25467 strHome += "Library/Application Support/";
25468 filesystem::create_directory(strHome.c_str());
25469 return strHome + "Bitcoin";
25470 #else
25471 // Unix
25472 return strHome + ".bitcoin";
25473 #endif
25474 #endif
25475 }
25476
25477 void GetDataDir(char* pszDir)
25478 {
25479 // pszDir must be at least MAX_PATH length.
25480 int nVariation;
25481 if (pszSetDataDir[0] != 0)
25482 {
25483 strlcpy(pszDir, pszSetDataDir, MAX_PATH);
25484 nVariation = 0;
25485 }
25486 else
25487 {
25488 // This can be called during exceptions by printf, so we cache the
25489 // value so we don't have to do memory allocations after that.
25490 static char pszCachedDir[MAX_PATH];
25491 if (pszCachedDir[0] == 0)
25492 strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
25493 strlcpy(pszDir, pszCachedDir, MAX_PATH);
25494 nVariation = 1;
25495 }
25496 if (fTestNet)
25497 {
25498 char* p = pszDir + strlen(pszDir);
25499 if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
25500 *p++ = '/';
25501 strcpy(p, "testnet");
25502 nVariation += 2;
25503 }
25504 static bool pfMkdir[4];
25505 if (!pfMkdir[nVariation])
25506 {
25507 pfMkdir[nVariation] = true;
25508 boost::filesystem::create_directory(pszDir);
25509 }
25510 }
25511
25512 string GetDataDir()
25513 {
25514 char pszDir[MAX_PATH];
25515 GetDataDir(pszDir);
25516 return pszDir;
25517 }
25518
25519 string GetConfigFile()
25520 {
25521 namespace fs = boost::filesystem;
25522 fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
25523 if (!pathConfig.is_complete())
25524 pathConfig = fs::path(GetDataDir()) / pathConfig;
25525 return pathConfig.string();
25526 }
25527
25528 void ReadConfigFile(map<string, string>& mapSettingsRet,
25529 map<string, vector<string> >& mapMultiSettingsRet)
25530 {
25531 namespace fs = boost::filesystem;
25532 namespace pod = boost::program_options::detail;
25533
25534 fs::ifstream streamConfig(GetConfigFile());
25535 if (!streamConfig.good())
25536 return;
25537
25538 set<string> setOptions;
25539 setOptions.insert("*");
25540
25541 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
25542 {
25543 // Don't overwrite existing settings so command line settings override bitcoin.conf
25544 string strKey = string("-") + it->string_key;
25545 if (mapSettingsRet.count(strKey) == 0)
25546 mapSettingsRet[strKey] = it->value[0];
25547 mapMultiSettingsRet[strKey].push_back(it->value[0]);
25548 }
25549 }
25550
25551 string GetPidFile()
25552 {
25553 namespace fs = boost::filesystem;
25554 fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
25555 if (!pathConfig.is_complete())
25556 pathConfig = fs::path(GetDataDir()) / pathConfig;
25557 return pathConfig.string();
25558 }
25559
25560 void CreatePidFile(string pidFile, pid_t pid)
25561 {
25562 FILE* file = fopen(pidFile.c_str(), "w");
25563 if (file)
25564 {
25565 fprintf(file, "%d\n", pid);
25566 fclose(file);
25567 }
25568 }
25569
25570 int GetFilesize(FILE* file)
25571 {
25572 int nSavePos = ftell(file);
25573 int nFilesize = -1;
25574 if (fseek(file, 0, SEEK_END) == 0)
25575 nFilesize = ftell(file);
25576 fseek(file, nSavePos, SEEK_SET);
25577 return nFilesize;
25578 }
25579
25580 void ShrinkDebugFile()
25581 {
25582 // Scroll debug.log if it's getting too big
25583 string strFile = GetDataDir() + "/debug.log";
25584 FILE* file = fopen(strFile.c_str(), "r");
25585 if (file && GetFilesize(file) > 10 * 1000000)
25586 {
25587 // Restart the file with some of the end
25588 char pch[200000];
25589 fseek(file, -sizeof(pch), SEEK_END);
25590 int nBytes = fread(pch, 1, sizeof(pch), file);
25591 fclose(file);
25592
25593 file = fopen(strFile.c_str(), "w");
25594 if (file)
25595 {
25596 fwrite(pch, 1, nBytes, file);
25597 fclose(file);
25598 }
25599 }
25600 }
25601
25602
25603
25604
25605
25606
25607
25608
25609 //
25610 // "Never go to sea with two chronometers; take one or three."
25611 // Our three time sources are:
25612 // - System clock
25613 // - Median of other nodes's clocks
25614 // - The user (asking the user to fix the system clock if the first two disagree)
25615 //
25616 static int64 nMockTime = 0; // For unit testing
25617
25618 int64 GetTime()
25619 {
25620 if (nMockTime) return nMockTime;
25621
25622 return time(NULL);
25623 }
25624
25625 void SetMockTime(int64 nMockTimeIn)
25626 {
25627 nMockTime = nMockTimeIn;
25628 }
25629
25630 static int64 nTimeOffset = 0;
25631
25632 int64 GetAdjustedTime()
25633 {
25634 return GetTime() + nTimeOffset;
25635 }
25636
25637 void AddTimeData(unsigned int ip, int64 nTime)
25638 {
25639 int64 nOffsetSample = nTime - GetTime();
25640
25641 // Ignore duplicates
25642 static set<unsigned int> setKnown;
25643 if (!setKnown.insert(ip).second)
25644 return;
25645
25646 // Add data
25647 static vector<int64> vTimeOffsets;
25648 if (vTimeOffsets.empty())
25649 vTimeOffsets.push_back(0);
25650 vTimeOffsets.push_back(nOffsetSample);
25651 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
25652 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
25653 {
25654 sort(vTimeOffsets.begin(), vTimeOffsets.end());
25655 int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
25656 // Only let other nodes change our time by so much
25657 if (abs64(nMedian) < 70 * 60)
25658 {
25659 nTimeOffset = nMedian;
25660 }
25661 else
25662 {
25663 nTimeOffset = 0;
25664
25665 static bool fDone;
25666 if (!fDone)
25667 {
25668 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
25669 bool fMatch = false;
25670 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
25671 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
25672 fMatch = true;
25673
25674 if (!fMatch)
25675 {
25676 fDone = true;
25677 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
25678 strMiscWarning = strMessage;
25679 printf("*** %s\n", strMessage.c_str());
25680 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
25681 }
25682 }
25683 }
25684 BOOST_FOREACH(int64 n, vTimeOffsets)
25685 printf("%+"PRI64d" ", n);
25686 printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
25687 }
25688 }
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698 string FormatVersion(int nVersion)
25699 {
25700 if (nVersion%100 == 0)
25701 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
25702 else
25703 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
25704 }
25705
25706 string FormatFullVersion()
25707 {
25708 string s = FormatVersion(VERSION) + pszSubVer;
25709 if (VERSION_IS_BETA) {
25710 s += "-";
25711 s += _("beta");
25712 }
25713 return s;
25714 }
25715
25716
25717
25718
25719 #ifdef DEBUG_LOCKORDER
25720 //
25721 // Early deadlock detection.
25722 // Problem being solved:
25723 // Thread 1 locks A, then B, then C
25724 // Thread 2 locks D, then C, then A
25725 // --> may result in deadlock between the two threads, depending on when they run.
25726 // Solution implemented here:
25727 // Keep track of pairs of locks: (A before B), (A before C), etc.
25728 // Complain if any thread trys to lock in a different order.
25729 //
25730
25731 struct CLockLocation
25732 {
25733 CLockLocation(const char* pszName, const char* pszFile, int nLine)
25734 {
25735 mutexName = pszName;
25736 sourceFile = pszFile;
25737 sourceLine = nLine;
25738 }
25739
25740 std::string ToString() const
25741 {
25742 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
25743 }
25744
25745 private:
25746 std::string mutexName;
25747 std::string sourceFile;
25748 int sourceLine;
25749 };
25750
25751 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
25752
25753 static boost::interprocess::interprocess_mutex dd_mutex;
25754 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
25755 static boost::thread_specific_ptr<LockStack> lockstack;
25756
25757
25758 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
25759 {
25760 printf("POTENTIAL DEADLOCK DETECTED\n");
25761 printf("Previous lock order was:\n");
25762 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
25763 {
25764 if (i.first == mismatch.first) printf(" (1)");
25765 if (i.first == mismatch.second) printf(" (2)");
25766 printf(" %s\n", i.second.ToString().c_str());
25767 }
25768 printf("Current lock order is:\n");
25769 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
25770 {
25771 if (i.first == mismatch.first) printf(" (1)");
25772 if (i.first == mismatch.second) printf(" (2)");
25773 printf(" %s\n", i.second.ToString().c_str());
25774 }
25775 }
25776
25777 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
25778 {
25779 bool fOrderOK = true;
25780 if (lockstack.get() == NULL)
25781 lockstack.reset(new LockStack);
25782
25783 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
25784 dd_mutex.lock();
25785
25786 (*lockstack).push_back(std::make_pair(c, locklocation));
25787
25788 BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
25789 {
25790 if (i.first == c) break;
25791
25792 std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
25793 if (lockorders.count(p1))
25794 continue;
25795 lockorders[p1] = (*lockstack);
25796
25797 std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
25798 if (lockorders.count(p2))
25799 {
25800 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
25801 break;
25802 }
25803 }
25804 dd_mutex.unlock();
25805 }
25806
25807 static void pop_lock()
25808 {
25809 if (fDebug)
25810 {
25811 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
25812 printf("Unlocked: %s\n", locklocation.ToString().c_str());
25813 }
25814 dd_mutex.lock();
25815 (*lockstack).pop_back();
25816 dd_mutex.unlock();
25817 }
25818
25819 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
25820 {
25821 push_lock(this, CLockLocation(pszName, pszFile, nLine));
25822 mutex.lock();
25823 }
25824 void CCriticalSection::Leave()
25825 {
25826 mutex.unlock();
25827 pop_lock();
25828 }
25829 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
25830 {
25831 push_lock(this, CLockLocation(pszName, pszFile, nLine));
25832 bool result = mutex.try_lock();
25833 if (!result) pop_lock();
25834 return result;
25835 }
25836
25837 #else
25838
25839 void CCriticalSection::Enter(const char*, const char*, int)
25840 {
25841 mutex.lock();
25842 }
25843
25844 void CCriticalSection::Leave()
25845 {
25846 mutex.unlock();
25847 }
25848
25849 bool CCriticalSection::TryEnter(const char*, const char*, int)
25850 {
25851 bool result = mutex.try_lock();
25852 return result;
25853 }
25854
25855 #endif /* DEBUG_LOCKORDER */