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