Remove unused and unreachable code
[novacoin.git] / src / util.cpp
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.
5
6 #include "headers.h"
7 #include "strlcpy.h"
8 #include <boost/algorithm/string/join.hpp>
9
10 // Work around clang compilation problem in Boost 1.46:
11 // /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
12 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
13 //           http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
14 namespace boost {
15     namespace program_options {
16         std::string to_internal(const std::string&);
17     }
18 }
19
20 #include <boost/program_options/detail/config_file.hpp>
21 #include <boost/program_options/parsers.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/fstream.hpp>
24 #include <boost/interprocess/sync/interprocess_mutex.hpp>
25 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
26 #include <boost/foreach.hpp>
27
28 using namespace std;
29 using namespace boost;
30
31 map<string, string> mapArgs;
32 map<string, vector<string> > mapMultiArgs;
33 bool fDebug = false;
34 bool fPrintToConsole = false;
35 bool fPrintToDebugger = false;
36 bool fRequestShutdown = false;
37 bool fShutdown = false;
38 bool fDaemon = false;
39 bool fServer = false;
40 bool fCommandLine = false;
41 string strMiscWarning;
42 bool fTestNet = false;
43 bool fNoListen = false;
44 bool fLogTimestamps = false;
45 CMedianFilter<int64> vTimeOffsets(200,0);
46
47 // Init openssl library multithreading support
48 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
49 void locking_callback(int mode, int i, const char* file, int line)
50 {
51     if (mode & CRYPTO_LOCK)
52         ppmutexOpenSSL[i]->lock();
53     else
54         ppmutexOpenSSL[i]->unlock();
55 }
56
57 // Init
58 class CInit
59 {
60 public:
61     CInit()
62     {
63         // Init openssl library multithreading support
64         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
65         for (int i = 0; i < CRYPTO_num_locks(); i++)
66             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
67         CRYPTO_set_locking_callback(locking_callback);
68
69 #ifdef WIN32
70         // Seed random number generator with screen scrape and other hardware sources
71         RAND_screen();
72 #endif
73
74         // Seed random number generator with performance counter
75         RandAddSeed();
76     }
77     ~CInit()
78     {
79         // Shutdown openssl library multithreading support
80         CRYPTO_set_locking_callback(NULL);
81         for (int i = 0; i < CRYPTO_num_locks(); i++)
82             delete ppmutexOpenSSL[i];
83         OPENSSL_free(ppmutexOpenSSL);
84     }
85 }
86 instance_of_cinit;
87
88
89
90
91
92
93
94
95 void RandAddSeed()
96 {
97     // Seed with CPU performance counter
98     int64 nCounter = GetPerformanceCounter();
99     RAND_add(&nCounter, sizeof(nCounter), 1.5);
100     memset(&nCounter, 0, sizeof(nCounter));
101 }
102
103 void RandAddSeedPerfmon()
104 {
105     RandAddSeed();
106
107     // This can take up to 2 seconds, so only do it every 10 minutes
108     static int64 nLastPerfmon;
109     if (GetTime() < nLastPerfmon + 10 * 60)
110         return;
111     nLastPerfmon = GetTime();
112
113 #ifdef WIN32
114     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
115     // Seed with the entire set of perfmon data
116     unsigned char pdata[250000];
117     memset(pdata, 0, sizeof(pdata));
118     unsigned long nSize = sizeof(pdata);
119     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
120     RegCloseKey(HKEY_PERFORMANCE_DATA);
121     if (ret == ERROR_SUCCESS)
122     {
123         RAND_add(pdata, nSize, nSize/100.0);
124         memset(pdata, 0, nSize);
125         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
126     }
127 #endif
128 }
129
130 uint64 GetRand(uint64 nMax)
131 {
132     if (nMax == 0)
133         return 0;
134
135     // The range of the random source must be a multiple of the modulus
136     // to give every possible output value an equal possibility
137     uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
138     uint64 nRand = 0;
139     do
140         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
141     while (nRand >= nRange);
142     return (nRand % nMax);
143 }
144
145 int GetRandInt(int nMax)
146 {
147     return GetRand(nMax);
148 }
149
150
151
152
153
154
155
156
157
158
159
160 inline int OutputDebugStringF(const char* pszFormat, ...)
161 {
162     int ret = 0;
163     if (fPrintToConsole)
164     {
165         // print to console
166         va_list arg_ptr;
167         va_start(arg_ptr, pszFormat);
168         ret = vprintf(pszFormat, arg_ptr);
169         va_end(arg_ptr);
170     }
171     else
172     {
173         // print to debug.log
174         static FILE* fileout = NULL;
175
176         if (!fileout)
177         {
178             boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
179             fileout = fopen(pathDebug.string().c_str(), "a");
180             if (fileout) setbuf(fileout, NULL); // unbuffered
181         }
182         if (fileout)
183         {
184             static bool fStartedNewLine = true;
185
186             // Debug print useful for profiling
187             if (fLogTimestamps && fStartedNewLine)
188                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
189             if (pszFormat[strlen(pszFormat) - 1] == '\n')
190                 fStartedNewLine = true;
191             else
192                 fStartedNewLine = false;
193
194             va_list arg_ptr;
195             va_start(arg_ptr, pszFormat);
196             ret = vfprintf(fileout, pszFormat, arg_ptr);
197             va_end(arg_ptr);
198         }
199     }
200
201 #ifdef WIN32
202     if (fPrintToDebugger)
203     {
204         static CCriticalSection cs_OutputDebugStringF;
205
206         // accumulate a line at a time
207         {
208             LOCK(cs_OutputDebugStringF);
209             static char pszBuffer[50000];
210             static char* pend;
211             if (pend == NULL)
212                 pend = pszBuffer;
213             va_list arg_ptr;
214             va_start(arg_ptr, pszFormat);
215             int limit = END(pszBuffer) - pend - 2;
216             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
217             va_end(arg_ptr);
218             if (ret < 0 || ret >= limit)
219             {
220                 pend = END(pszBuffer) - 2;
221                 *pend++ = '\n';
222             }
223             else
224                 pend += ret;
225             *pend = '\0';
226             char* p1 = pszBuffer;
227             char* p2;
228             while (p2 = strchr(p1, '\n'))
229             {
230                 p2++;
231                 char c = *p2;
232                 *p2 = '\0';
233                 OutputDebugStringA(p1);
234                 *p2 = c;
235                 p1 = p2;
236             }
237             if (p1 != pszBuffer)
238                 memmove(pszBuffer, p1, pend - p1 + 1);
239             pend -= (p1 - pszBuffer);
240         }
241     }
242 #endif
243     return ret;
244 }
245
246
247 // Safer snprintf
248 //  - prints up to limit-1 characters
249 //  - output string is always null terminated even if limit reached
250 //  - return value is the number of characters actually printed
251 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
252 {
253     if (limit == 0)
254         return 0;
255     va_list arg_ptr;
256     va_start(arg_ptr, format);
257     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
258     va_end(arg_ptr);
259     if (ret < 0 || ret >= limit)
260     {
261         ret = limit - 1;
262         buffer[limit-1] = 0;
263     }
264     return ret;
265 }
266
267 string real_strprintf(const std::string &format, int dummy, ...)
268 {
269     char buffer[50000];
270     char* p = buffer;
271     int limit = sizeof(buffer);
272     int ret;
273     loop
274     {
275         va_list arg_ptr;
276         va_start(arg_ptr, dummy);
277         ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
278         va_end(arg_ptr);
279         if (ret >= 0 && ret < limit)
280             break;
281         if (p != buffer)
282             delete[] p;
283         limit *= 2;
284         p = new char[limit];
285         if (p == NULL)
286             throw std::bad_alloc();
287     }
288     string str(p, p+ret);
289     if (p != buffer)
290         delete[] p;
291     return str;
292 }
293
294 bool error(const char *format, ...)
295 {
296     char buffer[50000];
297     int limit = sizeof(buffer);
298     va_list arg_ptr;
299     va_start(arg_ptr, format);
300     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
301     va_end(arg_ptr);
302     if (ret < 0 || ret >= limit)
303     {
304         buffer[limit-1] = 0;
305     }
306     printf("ERROR: %s\n", buffer);
307     return false;
308 }
309
310
311 void ParseString(const string& str, char c, vector<string>& v)
312 {
313     if (str.empty())
314         return;
315     string::size_type i1 = 0;
316     string::size_type i2;
317     loop
318     {
319         i2 = str.find(c, i1);
320         if (i2 == str.npos)
321         {
322             v.push_back(str.substr(i1));
323             return;
324         }
325         v.push_back(str.substr(i1, i2-i1));
326         i1 = i2+1;
327     }
328 }
329
330
331 string FormatMoney(int64 n, bool fPlus)
332 {
333     // Note: not using straight sprintf here because we do NOT want
334     // localized number formatting.
335     int64 n_abs = (n > 0 ? n : -n);
336     int64 quotient = n_abs/COIN;
337     int64 remainder = n_abs%COIN;
338     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
339
340     // Right-trim excess 0's before the decimal point:
341     int nTrim = 0;
342     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
343         ++nTrim;
344     if (nTrim)
345         str.erase(str.size()-nTrim, nTrim);
346
347     if (n < 0)
348         str.insert((unsigned int)0, 1, '-');
349     else if (fPlus && n > 0)
350         str.insert((unsigned int)0, 1, '+');
351     return str;
352 }
353
354
355 bool ParseMoney(const string& str, int64& nRet)
356 {
357     return ParseMoney(str.c_str(), nRet);
358 }
359
360 bool ParseMoney(const char* pszIn, int64& nRet)
361 {
362     string strWhole;
363     int64 nUnits = 0;
364     const char* p = pszIn;
365     while (isspace(*p))
366         p++;
367     for (; *p; p++)
368     {
369         if (*p == '.')
370         {
371             p++;
372             int64 nMult = CENT*10;
373             while (isdigit(*p) && (nMult > 0))
374             {
375                 nUnits += nMult * (*p++ - '0');
376                 nMult /= 10;
377             }
378             break;
379         }
380         if (isspace(*p))
381             break;
382         if (!isdigit(*p))
383             return false;
384         strWhole.insert(strWhole.end(), *p);
385     }
386     for (; *p; p++)
387         if (!isspace(*p))
388             return false;
389     if (strWhole.size() > 10) // guard against 63 bit overflow
390         return false;
391     if (nUnits < 0 || nUnits > COIN)
392         return false;
393     int64 nWhole = atoi64(strWhole);
394     int64 nValue = nWhole*COIN + nUnits;
395
396     nRet = nValue;
397     return true;
398 }
399
400
401 static char phexdigit[256] =
402 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
403   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
404   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
405   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
406   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
407   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
408   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
409   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
410   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
412   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
413   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
414   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
415   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
416   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
417   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
418
419 bool IsHex(const string& str)
420 {
421     BOOST_FOREACH(unsigned char c, str)
422     {
423         if (phexdigit[c] < 0)
424             return false;
425     }
426     return (str.size() > 0) && (str.size()%2 == 0);
427 }
428
429 vector<unsigned char> ParseHex(const char* psz)
430 {
431     // convert hex dump to vector
432     vector<unsigned char> vch;
433     loop
434     {
435         while (isspace(*psz))
436             psz++;
437         char c = phexdigit[(unsigned char)*psz++];
438         if (c == (char)-1)
439             break;
440         unsigned char n = (c << 4);
441         c = phexdigit[(unsigned char)*psz++];
442         if (c == (char)-1)
443             break;
444         n |= c;
445         vch.push_back(n);
446     }
447     return vch;
448 }
449
450 vector<unsigned char> ParseHex(const string& str)
451 {
452     return ParseHex(str.c_str());
453 }
454
455 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
456 {
457     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
458     if (name.find("-no") == 0)
459     {
460         std::string positive("-");
461         positive.append(name.begin()+3, name.end());
462         if (mapSettingsRet.count(positive) == 0)
463         {
464             bool value = !GetBoolArg(name);
465             mapSettingsRet[positive] = (value ? "1" : "0");
466         }
467     }
468 }
469
470 void ParseParameters(int argc, const char*const argv[])
471 {
472     mapArgs.clear();
473     mapMultiArgs.clear();
474     for (int i = 1; i < argc; i++)
475     {
476         char psz[10000];
477         strlcpy(psz, argv[i], sizeof(psz));
478         char* pszValue = (char*)"";
479         if (strchr(psz, '='))
480         {
481             pszValue = strchr(psz, '=');
482             *pszValue++ = '\0';
483         }
484         #ifdef WIN32
485         _strlwr(psz);
486         if (psz[0] == '/')
487             psz[0] = '-';
488         #endif
489         if (psz[0] != '-')
490             break;
491
492         mapArgs[psz] = pszValue;
493         mapMultiArgs[psz].push_back(pszValue);
494     }
495
496     // New 0.6 features:
497     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
498     {
499         string name = entry.first;
500
501         //  interpret --foo as -foo (as long as both are not set)
502         if (name.find("--") == 0)
503         {
504             std::string singleDash(name.begin()+1, name.end());
505             if (mapArgs.count(singleDash) == 0)
506                 mapArgs[singleDash] = entry.second;
507             name = singleDash;
508         }
509
510         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
511         InterpretNegativeSetting(name, mapArgs);
512     }
513 }
514
515 std::string GetArg(const std::string& strArg, const std::string& strDefault)
516 {
517     if (mapArgs.count(strArg))
518         return mapArgs[strArg];
519     return strDefault;
520 }
521
522 int64 GetArg(const std::string& strArg, int64 nDefault)
523 {
524     if (mapArgs.count(strArg))
525         return atoi64(mapArgs[strArg]);
526     return nDefault;
527 }
528
529 bool GetBoolArg(const std::string& strArg, bool fDefault)
530 {
531     if (mapArgs.count(strArg))
532     {
533         if (mapArgs[strArg].empty())
534             return true;
535         return (atoi(mapArgs[strArg]) != 0);
536     }
537     return fDefault;
538 }
539
540 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
541 {
542     if (mapArgs.count(strArg))
543         return false;
544     mapArgs[strArg] = strValue;
545     return true;
546 }
547
548 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
549 {
550     if (fValue)
551         return SoftSetArg(strArg, std::string("1"));
552     else
553         return SoftSetArg(strArg, std::string("0"));
554 }
555
556
557 string EncodeBase64(const unsigned char* pch, size_t len)
558 {
559     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
560
561     string strRet="";
562     strRet.reserve((len+2)/3*4);
563
564     int mode=0, left=0;
565     const unsigned char *pchEnd = pch+len;
566
567     while (pch<pchEnd)
568     {
569         int enc = *(pch++);
570         switch (mode)
571         {
572             case 0: // we have no bits
573                 strRet += pbase64[enc >> 2];
574                 left = (enc & 3) << 4;
575                 mode = 1;
576                 break;
577
578             case 1: // we have two bits
579                 strRet += pbase64[left | (enc >> 4)];
580                 left = (enc & 15) << 2;
581                 mode = 2;
582                 break;
583
584             case 2: // we have four bits
585                 strRet += pbase64[left | (enc >> 6)];
586                 strRet += pbase64[enc & 63];
587                 mode = 0;
588                 break;
589         }
590     }
591
592     if (mode)
593     {
594         strRet += pbase64[left];
595         strRet += '=';
596         if (mode == 1)
597             strRet += '=';
598     }
599
600     return strRet;
601 }
602
603 string EncodeBase64(const string& str)
604 {
605     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
606 }
607
608 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
609 {
610     static const int decode64_table[256] =
611     {
612         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
613         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
614         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
615         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
616         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
617         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
618         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
619         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
620         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
621         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
622         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
623         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
624         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
625     };
626
627     if (pfInvalid)
628         *pfInvalid = false;
629
630     vector<unsigned char> vchRet;
631     vchRet.reserve(strlen(p)*3/4);
632
633     int mode = 0;
634     int left = 0;
635
636     while (1)
637     {
638          int dec = decode64_table[(unsigned char)*p];
639          if (dec == -1) break;
640          p++;
641          switch (mode)
642          {
643              case 0: // we have no bits and get 6
644                  left = dec;
645                  mode = 1;
646                  break;
647
648               case 1: // we have 6 bits and keep 4
649                   vchRet.push_back((left<<2) | (dec>>4));
650                   left = dec & 15;
651                   mode = 2;
652                   break;
653
654              case 2: // we have 4 bits and get 6, we keep 2
655                  vchRet.push_back((left<<4) | (dec>>2));
656                  left = dec & 3;
657                  mode = 3;
658                  break;
659
660              case 3: // we have 2 bits and get 6
661                  vchRet.push_back((left<<6) | dec);
662                  mode = 0;
663                  break;
664          }
665     }
666
667     if (pfInvalid)
668         switch (mode)
669         {
670             case 0: // 4n base64 characters processed: ok
671                 break;
672
673             case 1: // 4n+1 base64 character processed: impossible
674                 *pfInvalid = true;
675                 break;
676
677             case 2: // 4n+2 base64 characters processed: require '=='
678                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
679                     *pfInvalid = true;
680                 break;
681
682             case 3: // 4n+3 base64 characters processed: require '='
683                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
684                     *pfInvalid = true;
685                 break;
686         }
687
688     return vchRet;
689 }
690
691 string DecodeBase64(const string& str)
692 {
693     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
694     return string((const char*)&vchRet[0], vchRet.size());
695 }
696
697
698 bool WildcardMatch(const char* psz, const char* mask)
699 {
700     loop
701     {
702         switch (*mask)
703         {
704         case '\0':
705             return (*psz == '\0');
706         case '*':
707             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
708         case '?':
709             if (*psz == '\0')
710                 return false;
711             break;
712         default:
713             if (*psz != *mask)
714                 return false;
715             break;
716         }
717         psz++;
718         mask++;
719     }
720 }
721
722 bool WildcardMatch(const string& str, const string& mask)
723 {
724     return WildcardMatch(str.c_str(), mask.c_str());
725 }
726
727
728
729
730
731
732
733
734 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
735 {
736 #ifdef WIN32
737     char pszModule[MAX_PATH];
738     pszModule[0] = '\0';
739     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
740 #else
741     const char* pszModule = "bitcoin";
742 #endif
743     if (pex)
744         snprintf(pszMessage, 1000,
745             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
746     else
747         snprintf(pszMessage, 1000,
748             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
749 }
750
751 void LogException(std::exception* pex, const char* pszThread)
752 {
753     char pszMessage[10000];
754     FormatException(pszMessage, pex, pszThread);
755     printf("\n%s", pszMessage);
756 }
757
758 void PrintException(std::exception* pex, const char* pszThread)
759 {
760     char pszMessage[10000];
761     FormatException(pszMessage, pex, pszThread);
762     printf("\n\n************************\n%s\n", pszMessage);
763     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
764     strMiscWarning = pszMessage;
765     throw;
766 }
767
768 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
769 {
770     char pszMessage[10000];
771     FormatException(pszMessage, pex, pszThread);
772     printf("\n\n************************\n%s\n", pszMessage);
773     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
774     strMiscWarning = pszMessage;
775 }
776
777 #ifdef WIN32
778 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
779 {
780     namespace fs = boost::filesystem;
781
782     char pszPath[MAX_PATH] = "";
783     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
784     {
785         return fs::path(pszPath);
786     }
787     else if (nFolder == CSIDL_STARTUP)
788     {
789         return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
790     }
791     else if (nFolder == CSIDL_APPDATA)
792     {
793         return fs::path(getenv("APPDATA"));
794     }
795     return fs::path("");
796 }
797 #endif
798
799 boost::filesystem::path GetDefaultDataDir()
800 {
801     namespace fs = boost::filesystem;
802
803     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
804     // Mac: ~/Library/Application Support/Bitcoin
805     // Unix: ~/.bitcoin
806 #ifdef WIN32
807     // Windows
808     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
809 #else
810     fs::path pathRet;
811     char* pszHome = getenv("HOME");
812     if (pszHome == NULL || strlen(pszHome) == 0)
813         pathRet = fs::path("/");
814     else
815         pathRet = fs::path(pszHome);
816 #ifdef MAC_OSX
817     // Mac
818     pathRet /= "Library/Application Support";
819     filesystem::create_directory(pathRet);
820     return pathRet / "Bitcoin";
821 #else
822     // Unix
823     return pathRet / ".bitcoin";
824 #endif
825 #endif
826 }
827
828 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
829 {
830     namespace fs = boost::filesystem;
831
832     static fs::path pathCached[2];
833     static CCriticalSection csPathCached;
834     static bool cachedPath[2] = {false, false};
835
836     fs::path &path = pathCached[fNetSpecific];
837
838     // This can be called during exceptions by printf, so we cache the
839     // value so we don't have to do memory allocations after that.
840     if (cachedPath[fNetSpecific])
841         return path;
842
843     LOCK(csPathCached);
844
845     if (mapArgs.count("-datadir")) {
846         path = mapArgs["-datadir"];
847     } else {
848         path = GetDefaultDataDir();
849     }
850     if (fNetSpecific && GetBoolArg("-testnet", false))
851         path /= "testnet";
852
853     fs::create_directory(path);
854
855     cachedPath[fNetSpecific]=true;
856     return path;
857 }
858
859 boost::filesystem::path GetConfigFile()
860 {
861     namespace fs = boost::filesystem;
862
863     fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
864     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
865     return pathConfigFile;
866 }
867
868 bool ReadConfigFile(map<string, string>& mapSettingsRet,
869                     map<string, vector<string> >& mapMultiSettingsRet)
870 {
871     namespace fs = boost::filesystem;
872     namespace pod = boost::program_options::detail;
873
874     fs::ifstream streamConfig(GetConfigFile());
875     if (!streamConfig.good())
876         return true; // No bitcoin.conf file is OK
877
878     set<string> setOptions;
879     setOptions.insert("*");
880
881     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
882     {
883         // Don't overwrite existing settings so command line settings override bitcoin.conf
884         string strKey = string("-") + it->string_key;
885         if (mapSettingsRet.count(strKey) == 0)
886         {
887             mapSettingsRet[strKey] = it->value[0];
888             //  interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
889             InterpretNegativeSetting(strKey, mapSettingsRet);
890         }
891         mapMultiSettingsRet[strKey].push_back(it->value[0]);
892     }
893     return true;
894 }
895
896 boost::filesystem::path GetPidFile()
897 {
898     namespace fs = boost::filesystem;
899
900     fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
901     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
902     return pathPidFile;
903 }
904
905 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
906 {
907     FILE* file = fopen(path.string().c_str(), "w");
908     if (file)
909     {
910         fprintf(file, "%d\n", pid);
911         fclose(file);
912     }
913 }
914
915 int GetFilesize(FILE* file)
916 {
917     int nSavePos = ftell(file);
918     int nFilesize = -1;
919     if (fseek(file, 0, SEEK_END) == 0)
920         nFilesize = ftell(file);
921     fseek(file, nSavePos, SEEK_SET);
922     return nFilesize;
923 }
924
925 void ShrinkDebugFile()
926 {
927     // Scroll debug.log if it's getting too big
928     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
929     FILE* file = fopen(pathLog.string().c_str(), "r");
930     if (file && GetFilesize(file) > 10 * 1000000)
931     {
932         // Restart the file with some of the end
933         char pch[200000];
934         fseek(file, -sizeof(pch), SEEK_END);
935         int nBytes = fread(pch, 1, sizeof(pch), file);
936         fclose(file);
937
938         file = fopen(pathLog.string().c_str(), "w");
939         if (file)
940         {
941             fwrite(pch, 1, nBytes, file);
942             fclose(file);
943         }
944     }
945 }
946
947
948
949
950
951
952
953
954 //
955 // "Never go to sea with two chronometers; take one or three."
956 // Our three time sources are:
957 //  - System clock
958 //  - Median of other nodes's clocks
959 //  - The user (asking the user to fix the system clock if the first two disagree)
960 //
961 static int64 nMockTime = 0;  // For unit testing
962
963 int64 GetTime()
964 {
965     if (nMockTime) return nMockTime;
966
967     return time(NULL);
968 }
969
970 void SetMockTime(int64 nMockTimeIn)
971 {
972     nMockTime = nMockTimeIn;
973 }
974
975 static int64 nTimeOffset = 0;
976
977 int64 GetAdjustedTime()
978 {
979     return GetTime() + nTimeOffset;
980 }
981
982 void AddTimeData(const CNetAddr& ip, int64 nTime)
983 {
984     int64 nOffsetSample = nTime - GetTime();
985
986     // Ignore duplicates
987     static set<CNetAddr> setKnown;
988     if (!setKnown.insert(ip).second)
989         return;
990
991     // Add data
992     vTimeOffsets.input(nOffsetSample);
993     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
994     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
995     {
996         int64 nMedian = vTimeOffsets.median();
997         std::vector<int64> vSorted = vTimeOffsets.sorted();
998         // Only let other nodes change our time by so much
999         if (abs64(nMedian) < 70 * 60)
1000         {
1001             nTimeOffset = nMedian;
1002         }
1003         else
1004         {
1005             nTimeOffset = 0;
1006
1007             static bool fDone;
1008             if (!fDone)
1009             {
1010                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1011                 bool fMatch = false;
1012                 BOOST_FOREACH(int64 nOffset, vSorted)
1013                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1014                         fMatch = true;
1015
1016                 if (!fMatch)
1017                 {
1018                     fDone = true;
1019                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
1020                     strMiscWarning = strMessage;
1021                     printf("*** %s\n", strMessage.c_str());
1022                     ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1023                 }
1024             }
1025         }
1026         if (fDebug) {
1027             BOOST_FOREACH(int64 n, vSorted)
1028                 printf("%+"PRI64d"  ", n);
1029             printf("|  ");
1030         }
1031         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1032     }
1033 }
1034
1035
1036
1037
1038
1039
1040
1041
1042 string FormatVersion(int nVersion)
1043 {
1044     if (nVersion%100 == 0)
1045         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1046     else
1047         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1048 }
1049
1050 string FormatFullVersion()
1051 {
1052     return CLIENT_BUILD;
1053 }
1054
1055 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1056 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1057 {
1058     std::ostringstream ss;
1059     ss << "/";
1060     ss << name << ":" << FormatVersion(nClientVersion);
1061     if (!comments.empty())
1062         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1063     ss << "/";
1064     return ss.str();
1065 }
1066
1067
1068
1069 #ifdef DEBUG_LOCKORDER
1070 //
1071 // Early deadlock detection.
1072 // Problem being solved:
1073 //    Thread 1 locks  A, then B, then C
1074 //    Thread 2 locks  D, then C, then A
1075 //     --> may result in deadlock between the two threads, depending on when they run.
1076 // Solution implemented here:
1077 // Keep track of pairs of locks: (A before B), (A before C), etc.
1078 // Complain if any thread trys to lock in a different order.
1079 //
1080
1081 struct CLockLocation
1082 {
1083     CLockLocation(const char* pszName, const char* pszFile, int nLine)
1084     {
1085         mutexName = pszName;
1086         sourceFile = pszFile;
1087         sourceLine = nLine;
1088     }
1089
1090     std::string ToString() const
1091     {
1092         return mutexName+"  "+sourceFile+":"+itostr(sourceLine);
1093     }
1094
1095 private:
1096     std::string mutexName;
1097     std::string sourceFile;
1098     int sourceLine;
1099 };
1100
1101 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1102
1103 static boost::interprocess::interprocess_mutex dd_mutex;
1104 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1105 static boost::thread_specific_ptr<LockStack> lockstack;
1106
1107
1108 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1109 {
1110     printf("POTENTIAL DEADLOCK DETECTED\n");
1111     printf("Previous lock order was:\n");
1112     BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1113     {
1114         if (i.first == mismatch.first) printf(" (1)");
1115         if (i.first == mismatch.second) printf(" (2)");
1116         printf(" %s\n", i.second.ToString().c_str());
1117     }
1118     printf("Current lock order is:\n");
1119     BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1120     {
1121         if (i.first == mismatch.first) printf(" (1)");
1122         if (i.first == mismatch.second) printf(" (2)");
1123         printf(" %s\n", i.second.ToString().c_str());
1124     }
1125 }
1126
1127 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1128 {
1129     bool fOrderOK = true;
1130     if (lockstack.get() == NULL)
1131         lockstack.reset(new LockStack);
1132
1133     if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1134     dd_mutex.lock();
1135
1136     (*lockstack).push_back(std::make_pair(c, locklocation));
1137
1138     if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1139     {
1140         if (i.first == c) break;
1141
1142         std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1143         if (lockorders.count(p1))
1144             continue;
1145         lockorders[p1] = (*lockstack);
1146
1147         std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1148         if (lockorders.count(p2))
1149         {
1150             potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1151             break;
1152         }
1153     }
1154     dd_mutex.unlock();
1155 }
1156
1157 static void pop_lock()
1158 {
1159     if (fDebug) 
1160     {
1161         const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1162         printf("Unlocked: %s\n", locklocation.ToString().c_str());
1163     }
1164     dd_mutex.lock();
1165     (*lockstack).pop_back();
1166     dd_mutex.unlock();
1167 }
1168
1169 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1170 {
1171     push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1172 }
1173
1174 void LeaveCritical()
1175 {
1176     pop_lock();
1177 }
1178
1179 #endif /* DEBUG_LOCKORDER */