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