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