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