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