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