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