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