Merge bitcoin v0.4.0 into ppcoin
[novacoin.git] / src / util.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 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 using namespace std;
17 using namespace boost;
18
19 map<string, string> mapArgs;
20 map<string, vector<string> > mapMultiArgs;
21 bool fDebug = false;
22 bool fPrintToConsole = false;
23 bool fPrintToDebugger = false;
24 char pszSetDataDir[MAX_PATH] = "";
25 bool fRequestShutdown = false;
26 bool fShutdown = false;
27 bool fDaemon = false;
28 bool fServer = false;
29 bool fCommandLine = false;
30 string strMiscWarning;
31 bool fTestNet = false;
32 bool fNoListen = false;
33 bool fLogTimestamps = false;
34
35
36
37
38 // Workaround for "multiple definition of `_tls_used'"
39 // http://svn.boost.org/trac/boost/ticket/4258
40 extern "C" void tss_cleanup_implemented() { }
41
42
43
44
45
46 // Init openssl library multithreading support
47 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
48 void locking_callback(int mode, int i, const char* file, int line)
49 {
50     if (mode & CRYPTO_LOCK)
51         ppmutexOpenSSL[i]->lock();
52     else
53         ppmutexOpenSSL[i]->unlock();
54 }
55
56 // Init
57 class CInit
58 {
59 public:
60     CInit()
61     {
62         // Init openssl library multithreading support
63         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
64         for (int i = 0; i < CRYPTO_num_locks(); i++)
65             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
66         CRYPTO_set_locking_callback(locking_callback);
67
68 #ifdef __WXMSW__
69         // Seed random number generator with screen scrape and other hardware sources
70         RAND_screen();
71 #endif
72
73         // Seed random number generator with performance counter
74         RandAddSeed();
75     }
76     ~CInit()
77     {
78         // Shutdown openssl library multithreading support
79         CRYPTO_set_locking_callback(NULL);
80         for (int i = 0; i < CRYPTO_num_locks(); i++)
81             delete ppmutexOpenSSL[i];
82         OPENSSL_free(ppmutexOpenSSL);
83     }
84 }
85 instance_of_cinit;
86
87
88
89
90
91
92
93
94 void RandAddSeed()
95 {
96     // Seed with CPU performance counter
97     int64 nCounter = GetPerformanceCounter();
98     RAND_add(&nCounter, sizeof(nCounter), 1.5);
99     memset(&nCounter, 0, sizeof(nCounter));
100 }
101
102 void RandAddSeedPerfmon()
103 {
104     RandAddSeed();
105
106     // This can take up to 2 seconds, so only do it every 10 minutes
107     static int64 nLastPerfmon;
108     if (GetTime() < nLastPerfmon + 10 * 60)
109         return;
110     nLastPerfmon = GetTime();
111
112 #ifdef __WXMSW__
113     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
114     // Seed with the entire set of perfmon data
115     unsigned char pdata[250000];
116     memset(pdata, 0, sizeof(pdata));
117     unsigned long nSize = sizeof(pdata);
118     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
119     RegCloseKey(HKEY_PERFORMANCE_DATA);
120     if (ret == ERROR_SUCCESS)
121     {
122         RAND_add(pdata, nSize, nSize/100.0);
123         memset(pdata, 0, nSize);
124         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
125     }
126 #endif
127 }
128
129 uint64 GetRand(uint64 nMax)
130 {
131     if (nMax == 0)
132         return 0;
133
134     // The range of the random source must be a multiple of the modulus
135     // to give every possible output value an equal possibility
136     uint64 nRange = (UINT64_MAX / nMax) * nMax;
137     uint64 nRand = 0;
138     do
139         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
140     while (nRand >= nRange);
141     return (nRand % nMax);
142 }
143
144 int GetRandInt(int nMax)
145 {
146     return GetRand(nMax);
147 }
148
149
150
151
152
153
154
155
156
157
158
159 inline int OutputDebugStringF(const char* pszFormat, ...)
160 {
161     int ret = 0;
162     if (fPrintToConsole)
163     {
164         // print to console
165         va_list arg_ptr;
166         va_start(arg_ptr, pszFormat);
167         ret = vprintf(pszFormat, arg_ptr);
168         va_end(arg_ptr);
169     }
170     else
171     {
172         // print to debug.log
173         static FILE* fileout = NULL;
174
175         if (!fileout)
176         {
177             char pszFile[MAX_PATH+100];
178             GetDataDir(pszFile);
179             strlcat(pszFile, "/debug.log", sizeof(pszFile));
180             fileout = fopen(pszFile, "a");
181             if (fileout) setbuf(fileout, NULL); // unbuffered
182         }
183         if (fileout)
184         {
185             static bool fStartedNewLine = true;
186
187             // Debug print useful for profiling
188             if (fLogTimestamps && fStartedNewLine)
189                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
190             if (pszFormat[strlen(pszFormat) - 1] == '\n')
191                 fStartedNewLine = true;
192             else
193                 fStartedNewLine = false;
194
195             va_list arg_ptr;
196             va_start(arg_ptr, pszFormat);
197             ret = vfprintf(fileout, pszFormat, arg_ptr);
198             va_end(arg_ptr);
199         }
200     }
201
202 #ifdef __WXMSW__
203     if (fPrintToDebugger)
204     {
205         static CCriticalSection cs_OutputDebugStringF;
206
207         // accumulate a line at a time
208         CRITICAL_BLOCK(cs_OutputDebugStringF)
209         {
210             static char pszBuffer[50000];
211             static char* pend;
212             if (pend == NULL)
213                 pend = pszBuffer;
214             va_list arg_ptr;
215             va_start(arg_ptr, pszFormat);
216             int limit = END(pszBuffer) - pend - 2;
217             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
218             va_end(arg_ptr);
219             if (ret < 0 || ret >= limit)
220             {
221                 pend = END(pszBuffer) - 2;
222                 *pend++ = '\n';
223             }
224             else
225                 pend += ret;
226             *pend = '\0';
227             char* p1 = pszBuffer;
228             char* p2;
229             while (p2 = strchr(p1, '\n'))
230             {
231                 p2++;
232                 char c = *p2;
233                 *p2 = '\0';
234                 OutputDebugStringA(p1);
235                 *p2 = c;
236                 p1 = p2;
237             }
238             if (p1 != pszBuffer)
239                 memmove(pszBuffer, p1, pend - p1 + 1);
240             pend -= (p1 - pszBuffer);
241         }
242     }
243 #endif
244     return ret;
245 }
246
247
248 // Safer snprintf
249 //  - prints up to limit-1 characters
250 //  - output string is always null terminated even if limit reached
251 //  - return value is the number of characters actually printed
252 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
253 {
254     if (limit == 0)
255         return 0;
256     va_list arg_ptr;
257     va_start(arg_ptr, format);
258     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
259     va_end(arg_ptr);
260     if (ret < 0 || ret >= limit)
261     {
262         ret = limit - 1;
263         buffer[limit-1] = 0;
264     }
265     return ret;
266 }
267
268
269 string strprintf(const char* format, ...)
270 {
271     char buffer[50000];
272     char* p = buffer;
273     int limit = sizeof(buffer);
274     int ret;
275     loop
276     {
277         va_list arg_ptr;
278         va_start(arg_ptr, format);
279         ret = _vsnprintf(p, limit, format, arg_ptr);
280         va_end(arg_ptr);
281         if (ret >= 0 && ret < limit)
282             break;
283         if (p != buffer)
284             delete[] p;
285         limit *= 2;
286         p = new char[limit];
287         if (p == NULL)
288             throw std::bad_alloc();
289     }
290     string str(p, p+ret);
291     if (p != buffer)
292         delete[] p;
293     return str;
294 }
295
296
297 bool error(const char* 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, 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".%04"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() > 14)
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
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 __WXMSW__
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
477 const char* wxGetTranslation(const char* pszEnglish)
478 {
479 #ifdef GUI
480     // Wrapper of wxGetTranslation returning the same const char* type as was passed in
481     static CCriticalSection cs;
482     CRITICAL_BLOCK(cs)
483     {
484         // Look in cache
485         static map<string, char*> mapCache;
486         map<string, char*>::iterator mi = mapCache.find(pszEnglish);
487         if (mi != mapCache.end())
488             return (*mi).second;
489
490         // wxWidgets translation
491         wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
492
493         // We don't cache unknown strings because caller might be passing in a
494         // dynamic string and we would keep allocating memory for each variation.
495         if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
496             return pszEnglish;
497
498         // Add to cache, memory doesn't need to be freed.  We only cache because
499         // we must pass back a pointer to permanently allocated memory.
500         char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
501         strcpy(pszCached, strTranslated.utf8_str());
502         mapCache[pszEnglish] = pszCached;
503         return pszCached;
504     }
505     return NULL;
506 #else
507     return pszEnglish;
508 #endif
509 }
510
511
512 bool WildcardMatch(const char* psz, const char* mask)
513 {
514     loop
515     {
516         switch (*mask)
517         {
518         case '\0':
519             return (*psz == '\0');
520         case '*':
521             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
522         case '?':
523             if (*psz == '\0')
524                 return false;
525             break;
526         default:
527             if (*psz != *mask)
528                 return false;
529             break;
530         }
531         psz++;
532         mask++;
533     }
534 }
535
536 bool WildcardMatch(const string& str, const string& mask)
537 {
538     return WildcardMatch(str.c_str(), mask.c_str());
539 }
540
541
542
543
544
545
546
547
548 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
549 {
550 #ifdef __WXMSW__
551     char pszModule[MAX_PATH];
552     pszModule[0] = '\0';
553     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
554 #else
555     const char* pszModule = "bitcoin";
556 #endif
557     if (pex)
558         snprintf(pszMessage, 1000,
559             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
560     else
561         snprintf(pszMessage, 1000,
562             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
563 }
564
565 void LogException(std::exception* pex, const char* pszThread)
566 {
567     char pszMessage[10000];
568     FormatException(pszMessage, pex, pszThread);
569     printf("\n%s", pszMessage);
570 }
571
572 void PrintException(std::exception* pex, const char* pszThread)
573 {
574     char pszMessage[10000];
575     FormatException(pszMessage, pex, pszThread);
576     printf("\n\n************************\n%s\n", pszMessage);
577     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
578     strMiscWarning = pszMessage;
579 #ifdef GUI
580     if (wxTheApp && !fDaemon)
581         MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
582 #endif
583     throw;
584 }
585
586 void ThreadOneMessageBox(string strMessage)
587 {
588     // Skip message boxes if one is already open
589     static bool fMessageBoxOpen;
590     if (fMessageBoxOpen)
591         return;
592     fMessageBoxOpen = true;
593     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
594     fMessageBoxOpen = false;
595 }
596
597 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
598 {
599     char pszMessage[10000];
600     FormatException(pszMessage, pex, pszThread);
601     printf("\n\n************************\n%s\n", pszMessage);
602     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
603     strMiscWarning = pszMessage;
604 #ifdef GUI
605     if (wxTheApp && !fDaemon)
606         boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
607 #endif
608 }
609
610
611
612
613
614
615
616
617 #ifdef __WXMSW__
618 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
619
620 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
621 {
622     char pszPath[MAX_PATH+100] = "";
623
624     // SHGetSpecialFolderPath isn't always available on old Windows versions
625     HMODULE hShell32 = LoadLibraryA("shell32.dll");
626     if (hShell32)
627     {
628         PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
629             (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
630         if (pSHGetSpecialFolderPath)
631             (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
632         FreeModule(hShell32);
633     }
634
635     // Backup option
636     if (pszPath[0] == '\0')
637     {
638         if (nFolder == CSIDL_STARTUP)
639         {
640             strcpy(pszPath, getenv("USERPROFILE"));
641             strcat(pszPath, "\\Start Menu\\Programs\\Startup");
642         }
643         else if (nFolder == CSIDL_APPDATA)
644         {
645             strcpy(pszPath, getenv("APPDATA"));
646         }
647     }
648
649     return pszPath;
650 }
651 #endif
652
653 string GetDefaultDataDir()
654 {
655     // Windows: C:\Documents and Settings\username\Application Data\PPCoin
656     // Mac: ~/Library/Application Support/PPCoin
657     // Unix: ~/.ppcoin
658 #ifdef __WXMSW__
659     // Windows
660     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\PPCoin";
661 #else
662     char* pszHome = getenv("HOME");
663     if (pszHome == NULL || strlen(pszHome) == 0)
664         pszHome = (char*)"/";
665     string strHome = pszHome;
666     if (strHome[strHome.size()-1] != '/')
667         strHome += '/';
668 #ifdef __WXMAC_OSX__
669     // Mac
670     strHome += "Library/Application Support/";
671     filesystem::create_directory(strHome.c_str());
672     return strHome + "PPCoin";
673 #else
674     // Unix
675     return strHome + ".ppcoin";
676 #endif
677 #endif
678 }
679
680 void GetDataDir(char* pszDir)
681 {
682     // pszDir must be at least MAX_PATH length.
683     int nVariation;
684     if (pszSetDataDir[0] != 0)
685     {
686         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
687         nVariation = 0;
688     }
689     else
690     {
691         // This can be called during exceptions by printf, so we cache the
692         // value so we don't have to do memory allocations after that.
693         static char pszCachedDir[MAX_PATH];
694         if (pszCachedDir[0] == 0)
695             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
696         strlcpy(pszDir, pszCachedDir, MAX_PATH);
697         nVariation = 1;
698     }
699     if (fTestNet)
700     {
701         char* p = pszDir + strlen(pszDir);
702         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
703             *p++ = '/';
704         strcpy(p, "testnet");
705         nVariation += 2;
706     }
707     static bool pfMkdir[4];
708     if (!pfMkdir[nVariation])
709     {
710         pfMkdir[nVariation] = true;
711         boost::filesystem::create_directory(pszDir);
712     }
713 }
714
715 string GetDataDir()
716 {
717     char pszDir[MAX_PATH];
718     GetDataDir(pszDir);
719     return pszDir;
720 }
721
722 string GetConfigFile()
723 {
724     namespace fs = boost::filesystem;
725     fs::path pathConfig(GetArg("-conf", "ppcoin.conf"));
726     if (!pathConfig.is_complete())
727         pathConfig = fs::path(GetDataDir()) / pathConfig;
728     return pathConfig.string();
729 }
730
731 void ReadConfigFile(map<string, string>& mapSettingsRet,
732                     map<string, vector<string> >& mapMultiSettingsRet)
733 {
734     namespace fs = boost::filesystem;
735     namespace pod = boost::program_options::detail;
736
737     fs::ifstream streamConfig(GetConfigFile());
738     if (!streamConfig.good())
739         return;
740
741     set<string> setOptions;
742     setOptions.insert("*");
743     
744     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
745     {
746         // Don't overwrite existing settings so command line settings override bitcoin.conf
747         string strKey = string("-") + it->string_key;
748         if (mapSettingsRet.count(strKey) == 0)
749             mapSettingsRet[strKey] = it->value[0];
750         mapMultiSettingsRet[strKey].push_back(it->value[0]);
751     }
752 }
753
754 string GetPidFile()
755 {
756     namespace fs = boost::filesystem;
757     fs::path pathConfig(GetArg("-pid", "ppcoind.pid"));
758     if (!pathConfig.is_complete())
759         pathConfig = fs::path(GetDataDir()) / pathConfig;
760     return pathConfig.string();
761 }
762
763 void CreatePidFile(string pidFile, pid_t pid)
764 {
765     FILE* file = fopen(pidFile.c_str(), "w");
766     if (file)
767     {
768         fprintf(file, "%d\n", pid);
769         fclose(file);
770     }
771 }
772
773 int GetFilesize(FILE* file)
774 {
775     int nSavePos = ftell(file);
776     int nFilesize = -1;
777     if (fseek(file, 0, SEEK_END) == 0)
778         nFilesize = ftell(file);
779     fseek(file, nSavePos, SEEK_SET);
780     return nFilesize;
781 }
782
783 void ShrinkDebugFile()
784 {
785     // Scroll debug.log if it's getting too big
786     string strFile = GetDataDir() + "/debug.log";
787     FILE* file = fopen(strFile.c_str(), "r");
788     if (file && GetFilesize(file) > 10 * 1000000)
789     {
790         // Restart the file with some of the end
791         char pch[200000];
792         fseek(file, -sizeof(pch), SEEK_END);
793         int nBytes = fread(pch, 1, sizeof(pch), file);
794         fclose(file);
795
796         file = fopen(strFile.c_str(), "w");
797         if (file)
798         {
799             fwrite(pch, 1, nBytes, file);
800             fclose(file);
801         }
802     }
803 }
804
805
806
807
808
809
810
811
812 //
813 // "Never go to sea with two chronometers; take one or three."
814 // Our three time sources are:
815 //  - System clock
816 //  - Median of other nodes's clocks
817 //  - The user (asking the user to fix the system clock if the first two disagree)
818 //
819 int64 GetTime()
820 {
821     return time(NULL);
822 }
823
824 static int64 nTimeOffset = 0;
825
826 int64 GetAdjustedTime()
827 {
828     return GetTime() + nTimeOffset;
829 }
830
831 void AddTimeData(unsigned int ip, int64 nTime)
832 {
833     int64 nOffsetSample = nTime - GetTime();
834
835     // Ignore duplicates
836     static set<unsigned int> setKnown;
837     if (!setKnown.insert(ip).second)
838         return;
839
840     // Add data
841     static vector<int64> vTimeOffsets;
842     if (vTimeOffsets.empty())
843         vTimeOffsets.push_back(0);
844     vTimeOffsets.push_back(nOffsetSample);
845     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
846     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
847     {
848         sort(vTimeOffsets.begin(), vTimeOffsets.end());
849         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
850         // Only let other nodes change our time by so much
851         if (abs64(nMedian) < 70 * 60)
852         {
853             nTimeOffset = nMedian;
854         }
855         else
856         {
857             nTimeOffset = 0;
858
859             static bool fDone;
860             if (!fDone)
861             {
862                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
863                 bool fMatch = false;
864                 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
865                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
866                         fMatch = true;
867
868                 if (!fMatch)
869                 {
870                     fDone = true;
871                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
872                     strMiscWarning = strMessage;
873                     printf("*** %s\n", strMessage.c_str());
874                     boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
875                 }
876             }
877         }
878         BOOST_FOREACH(int64 n, vTimeOffsets)
879             printf("%+"PRI64d"  ", n);
880         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
881     }
882 }
883
884
885
886
887
888
889
890
891
892 string FormatVersion(int nVersion)
893 {
894     if (nVersion%100 == 0)
895         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
896     else
897         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
898 }
899
900 string FormatFullVersion()
901 {
902     string s = FormatVersion(VERSION) + pszSubVer;
903     if (VERSION_IS_BETA) {
904         s += "-";
905         s += _("beta");
906     }
907     return s;
908 }
909
910
911
912
913 #ifdef DEBUG_LOCKORDER
914 //
915 // Early deadlock detection.
916 // Problem being solved:
917 //    Thread 1 locks  A, then B, then C
918 //    Thread 2 locks  D, then C, then A
919 //     --> may result in deadlock between the two threads, depending on when they run.
920 // Solution implemented here:
921 // Keep track of pairs of locks: (A before B), (A before C), etc.
922 // Complain if any thread trys to lock in a different order.
923 //
924
925 struct CLockLocation
926 {
927     CLockLocation(const char* pszName, const char* pszFile, int nLine)
928     {
929         mutexName = pszName;
930         sourceFile = pszFile;
931         sourceLine = nLine;
932     }
933
934     std::string ToString() const
935     {
936         return mutexName+"  "+sourceFile+":"+itostr(sourceLine);
937     }
938
939 private:
940     std::string mutexName;
941     std::string sourceFile;
942     int sourceLine;
943 };
944
945 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
946
947 static boost::interprocess::interprocess_mutex dd_mutex;
948 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
949 static boost::thread_specific_ptr<LockStack> lockstack;
950
951
952 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
953 {
954     printf("POTENTIAL DEADLOCK DETECTED\n");
955     printf("Previous lock order was:\n");
956     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
957     {
958         if (i.first == mismatch.first) printf(" (1)");
959         if (i.first == mismatch.second) printf(" (2)");
960         printf(" %s\n", i.second.ToString().c_str());
961     }
962     printf("Current lock order is:\n");
963     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
964     {
965         if (i.first == mismatch.first) printf(" (1)");
966         if (i.first == mismatch.second) printf(" (2)");
967         printf(" %s\n", i.second.ToString().c_str());
968     }
969 }
970
971 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
972 {
973     bool fOrderOK = true;
974     if (lockstack.get() == NULL)
975         lockstack.reset(new LockStack);
976
977     if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
978     dd_mutex.lock();
979
980     (*lockstack).push_back(std::make_pair(c, locklocation));
981
982     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
983     {
984         if (i.first == c) break;
985
986         std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
987         if (lockorders.count(p1))
988             continue;
989         lockorders[p1] = (*lockstack);
990
991         std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
992         if (lockorders.count(p2))
993         {
994             potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
995             break;
996         }
997     }
998     dd_mutex.unlock();
999 }
1000
1001 static void pop_lock()
1002 {
1003     if (fDebug) 
1004     {
1005         const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1006         printf("Unlocked: %s\n", locklocation.ToString().c_str());
1007     }
1008     dd_mutex.lock();
1009     (*lockstack).pop_back();
1010     dd_mutex.unlock();
1011 }
1012
1013 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1014 {
1015     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1016     mutex.lock();
1017 }
1018 void CCriticalSection::Leave()
1019 {
1020     mutex.unlock();
1021     pop_lock();
1022 }
1023 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1024 {
1025     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1026     bool result = mutex.try_lock();
1027     if (!result) pop_lock();
1028     return result;
1029 }
1030
1031 #else
1032
1033 void CCriticalSection::Enter(const char*, const char*, int)
1034 {
1035     mutex.lock();
1036 }
1037
1038 void CCriticalSection::Leave()
1039 {
1040     mutex.unlock();
1041 }
1042
1043 bool CCriticalSection::TryEnter(const char*, const char*, int)
1044 {
1045     bool result = mutex.try_lock();
1046     return result;
1047 }
1048
1049 #endif /* DEBUG_LOCKORDER */