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