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