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