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