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