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