Move importwallet and dumpwallet implementations to walletdb.cpp;
[novacoin.git] / src / util.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "util.h"
7 #include "sync.h"
8 #include "strlcpy.h"
9 #include "version.h"
10 #include "ui_interface.h"
11 #include <boost/algorithm/string/join.hpp>
12
13 // Work around clang compilation problem in Boost 1.46:
14 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
15 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
16 //           http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
17 namespace boost {
18     namespace program_options {
19         std::string to_internal(const std::string&);
20     }
21 }
22
23 #include <boost/program_options/detail/config_file.hpp>
24 #include <boost/program_options/parsers.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/filesystem/fstream.hpp>
27
28 #include <boost/date_time/posix_time/posix_time.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/thread.hpp>
31 #include <openssl/crypto.h>
32 #include <openssl/rand.h>
33 #include <stdarg.h>
34
35 #ifdef WIN32
36 #ifdef _MSC_VER
37 #pragma warning(disable:4786)
38 #pragma warning(disable:4804)
39 #pragma warning(disable:4805)
40 #pragma warning(disable:4717)
41 #endif
42 #ifdef _WIN32_WINNT
43 #undef _WIN32_WINNT
44 #endif
45 #define _WIN32_WINNT 0x0501
46 #ifdef _WIN32_IE
47 #undef _WIN32_IE
48 #endif
49 #define _WIN32_IE 0x0501
50 #define WIN32_LEAN_AND_MEAN 1
51 #ifndef NOMINMAX
52 #define NOMINMAX
53 #endif
54 #include <io.h> /* for _commit */
55 #include "shlobj.h"
56 #elif defined(__linux__)
57 # include <sys/prctl.h>
58 #endif
59
60 #ifndef WIN32
61 #include <execinfo.h>
62 #endif
63
64
65 using namespace std;
66 namespace bt = boost::posix_time;
67
68 map<string, string> mapArgs;
69 map<string, vector<string> > mapMultiArgs;
70 bool fDebug = false;
71 bool fDebugNet = false;
72 bool fPrintToConsole = false;
73 bool fPrintToDebugger = false;
74 bool fRequestShutdown = false;
75 bool fShutdown = false;
76 bool fDaemon = false;
77 bool fServer = false;
78 bool fCommandLine = false;
79 string strMiscWarning;
80 bool fTestNet = false;
81 bool fNoListen = false;
82 bool fLogTimestamps = false;
83 CMedianFilter<int64> vTimeOffsets(200,0);
84 bool fReopenDebugLog = false;
85
86 // Extended DecodeDumpTime implementation, see this page for details:
87 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
88 const std::locale formats[] = {
89     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
90     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
91     std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
92     std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
93     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
94 };
95
96 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
97
98 std::time_t pt_to_time_t(const bt::ptime& pt)
99 {
100     bt::ptime timet_start(boost::gregorian::date(1970,1,1));
101     bt::time_duration diff = pt - timet_start;
102     return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
103 }
104
105 // Init OpenSSL library multithreading support
106 static CCriticalSection** ppmutexOpenSSL;
107 void locking_callback(int mode, int i, const char* file, int line)
108 {
109     if (mode & CRYPTO_LOCK) {
110         ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
111     } else {
112         LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
113     }
114 }
115
116 LockedPageManager LockedPageManager::instance;
117
118 // Init
119 class CInit
120 {
121 public:
122     CInit()
123     {
124         // Init OpenSSL library multithreading support
125         ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
126         for (int i = 0; i < CRYPTO_num_locks(); i++)
127             ppmutexOpenSSL[i] = new CCriticalSection();
128         CRYPTO_set_locking_callback(locking_callback);
129
130 #ifdef WIN32
131         // Seed random number generator with screen scrape and other hardware sources
132         RAND_screen();
133 #endif
134
135         // Seed random number generator with performance counter
136         RandAddSeed();
137     }
138     ~CInit()
139     {
140         // Shutdown OpenSSL library multithreading support
141         CRYPTO_set_locking_callback(NULL);
142         for (int i = 0; i < CRYPTO_num_locks(); i++)
143             delete ppmutexOpenSSL[i];
144         OPENSSL_free(ppmutexOpenSSL);
145     }
146 }
147 instance_of_cinit;
148
149
150
151
152
153
154
155
156 void RandAddSeed()
157 {
158     // Seed with CPU performance counter
159     int64 nCounter = GetPerformanceCounter();
160     RAND_add(&nCounter, sizeof(nCounter), 1.5);
161     memset(&nCounter, 0, sizeof(nCounter));
162 }
163
164 void RandAddSeedPerfmon()
165 {
166     RandAddSeed();
167
168     // This can take up to 2 seconds, so only do it every 10 minutes
169     static int64 nLastPerfmon;
170     if (GetTime() < nLastPerfmon + 10 * 60)
171         return;
172     nLastPerfmon = GetTime();
173
174 #ifdef WIN32
175     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
176     // Seed with the entire set of perfmon data
177     unsigned char pdata[250000];
178     memset(pdata, 0, sizeof(pdata));
179     unsigned long nSize = sizeof(pdata);
180     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
181     RegCloseKey(HKEY_PERFORMANCE_DATA);
182     if (ret == ERROR_SUCCESS)
183     {
184         RAND_add(pdata, nSize, nSize/100.0);
185         memset(pdata, 0, nSize);
186         printf("RandAddSeed() %lu bytes\n", nSize);
187     }
188 #endif
189 }
190
191 uint64 GetRand(uint64 nMax)
192 {
193     if (nMax == 0)
194         return 0;
195
196     // The range of the random source must be a multiple of the modulus
197     // to give every possible output value an equal possibility
198     uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
199     uint64 nRand = 0;
200     do
201         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
202     while (nRand >= nRange);
203     return (nRand % nMax);
204 }
205
206 int GetRandInt(int nMax)
207 {
208     return GetRand(nMax);
209 }
210
211 uint256 GetRandHash()
212 {
213     uint256 hash;
214     RAND_bytes((unsigned char*)&hash, sizeof(hash));
215     return hash;
216 }
217
218
219
220
221
222
223 static FILE* fileout = NULL;
224
225 inline int OutputDebugStringF(const char* pszFormat, ...)
226 {
227     int ret = 0;
228     if (fPrintToConsole)
229     {
230         // print to console
231         va_list arg_ptr;
232         va_start(arg_ptr, pszFormat);
233         ret = vprintf(pszFormat, arg_ptr);
234         va_end(arg_ptr);
235     }
236     else if (!fPrintToDebugger)
237     {
238         // print to debug.log
239
240         if (!fileout)
241         {
242             boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
243             fileout = fopen(pathDebug.string().c_str(), "a");
244             if (fileout) setbuf(fileout, NULL); // unbuffered
245         }
246         if (fileout)
247         {
248             static bool fStartedNewLine = true;
249
250             // This routine may be called by global destructors during shutdown.
251             // Since the order of destruction of static/global objects is undefined,
252             // allocate mutexDebugLog on the heap the first time this routine
253             // is called to avoid crashes during shutdown.
254             static boost::mutex* mutexDebugLog = NULL;
255             if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
256             boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
257
258             // reopen the log file, if requested
259             if (fReopenDebugLog) {
260                 fReopenDebugLog = false;
261                 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
262                 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
263                     setbuf(fileout, NULL); // unbuffered
264             }
265
266             // Debug print useful for profiling
267             if (fLogTimestamps && fStartedNewLine)
268                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
269             if (pszFormat[strlen(pszFormat) - 1] == '\n')
270                 fStartedNewLine = true;
271             else
272                 fStartedNewLine = false;
273
274             va_list arg_ptr;
275             va_start(arg_ptr, pszFormat);
276             ret = vfprintf(fileout, pszFormat, arg_ptr);
277             va_end(arg_ptr);
278         }
279     }
280
281 #ifdef WIN32
282     if (fPrintToDebugger)
283     {
284         static CCriticalSection cs_OutputDebugStringF;
285
286         // accumulate and output a line at a time
287         {
288             LOCK(cs_OutputDebugStringF);
289             static std::string buffer;
290
291             va_list arg_ptr;
292             va_start(arg_ptr, pszFormat);
293             buffer += vstrprintf(pszFormat, arg_ptr);
294             va_end(arg_ptr);
295
296             int line_start = 0, line_end;
297             while((line_end = buffer.find('\n', line_start)) != -1)
298             {
299                 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
300                 line_start = line_end + 1;
301             }
302             buffer.erase(0, line_start);
303         }
304     }
305 #endif
306     return ret;
307 }
308
309 string vstrprintf(const char *format, va_list ap)
310 {
311     char buffer[50000];
312     char* p = buffer;
313     int limit = sizeof(buffer);
314     int ret;
315     while (true)
316     {
317         va_list arg_ptr;
318         va_copy(arg_ptr, ap);
319 #ifdef WIN32
320         ret = _vsnprintf(p, limit, format, arg_ptr);
321 #else
322         ret = vsnprintf(p, limit, format, arg_ptr);
323 #endif
324         va_end(arg_ptr);
325         if (ret >= 0 && ret < limit)
326             break;
327         if (p != buffer)
328             delete[] p;
329         limit *= 2;
330         p = new char[limit];
331         if (p == NULL)
332             throw std::bad_alloc();
333     }
334     string str(p, p+ret);
335     if (p != buffer)
336         delete[] p;
337     return str;
338 }
339
340 string real_strprintf(const char *format, int dummy, ...)
341 {
342     va_list arg_ptr;
343     va_start(arg_ptr, dummy);
344     string str = vstrprintf(format, arg_ptr);
345     va_end(arg_ptr);
346     return str;
347 }
348
349 string real_strprintf(const std::string &format, int dummy, ...)
350 {
351     va_list arg_ptr;
352     va_start(arg_ptr, dummy);
353     string str = vstrprintf(format.c_str(), arg_ptr);
354     va_end(arg_ptr);
355     return str;
356 }
357
358 bool error(const char *format, ...)
359 {
360     va_list arg_ptr;
361     va_start(arg_ptr, format);
362     std::string str = vstrprintf(format, arg_ptr);
363     va_end(arg_ptr);
364     printf("ERROR: %s\n", str.c_str());
365     return false;
366 }
367
368
369 void ParseString(const string& str, char c, vector<string>& v)
370 {
371     if (str.empty())
372         return;
373     string::size_type i1 = 0;
374     string::size_type i2;
375     while (true)
376     {
377         i2 = str.find(c, i1);
378         if (i2 == str.npos)
379         {
380             v.push_back(str.substr(i1));
381             return;
382         }
383         v.push_back(str.substr(i1, i2-i1));
384         i1 = i2+1;
385     }
386 }
387
388
389 string FormatMoney(int64 n, bool fPlus)
390 {
391     // Note: not using straight sprintf here because we do NOT want
392     // localized number formatting.
393     int64 n_abs = (n > 0 ? n : -n);
394     int64 quotient = n_abs/COIN;
395     int64 remainder = n_abs%COIN;
396     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
397
398     // Right-trim excess zeros before the decimal point:
399     int nTrim = 0;
400     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
401         ++nTrim;
402     if (nTrim)
403         str.erase(str.size()-nTrim, nTrim);
404
405     if (n < 0)
406         str.insert((unsigned int)0, 1, '-');
407     else if (fPlus && n > 0)
408         str.insert((unsigned int)0, 1, '+');
409     return str;
410 }
411
412
413 bool ParseMoney(const string& str, int64& nRet)
414 {
415     return ParseMoney(str.c_str(), nRet);
416 }
417
418 bool ParseMoney(const char* pszIn, int64& nRet)
419 {
420     string strWhole;
421     int64 nUnits = 0;
422     const char* p = pszIn;
423     while (isspace(*p))
424         p++;
425     for (; *p; p++)
426     {
427         if (*p == '.')
428         {
429             p++;
430             int64 nMult = CENT*10;
431             while (isdigit(*p) && (nMult > 0))
432             {
433                 nUnits += nMult * (*p++ - '0');
434                 nMult /= 10;
435             }
436             break;
437         }
438         if (isspace(*p))
439             break;
440         if (!isdigit(*p))
441             return false;
442         strWhole.insert(strWhole.end(), *p);
443     }
444     for (; *p; p++)
445         if (!isspace(*p))
446             return false;
447     if (strWhole.size() > 10) // guard against 63 bit overflow
448         return false;
449     if (nUnits < 0 || nUnits > COIN)
450         return false;
451     int64 nWhole = atoi64(strWhole);
452     int64 nValue = nWhole*COIN + nUnits;
453
454     nRet = nValue;
455     return true;
456 }
457
458
459 static const signed char phexdigit[256] =
460 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
461   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
462   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
463   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
464   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
465   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
466   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
467   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
468   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
469   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
470   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
471   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
472   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
473   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
474   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
475   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
476
477 bool IsHex(const string& str)
478 {
479     BOOST_FOREACH(unsigned char c, str)
480     {
481         if (phexdigit[c] < 0)
482             return false;
483     }
484     return (str.size() > 0) && (str.size()%2 == 0);
485 }
486
487 vector<unsigned char> ParseHex(const char* psz)
488 {
489     // convert hex dump to vector
490     vector<unsigned char> vch;
491     while (true)
492     {
493         while (isspace(*psz))
494             psz++;
495         signed char c = phexdigit[(unsigned char)*psz++];
496         if (c == (signed char)-1)
497             break;
498         unsigned char n = (c << 4);
499         c = phexdigit[(unsigned char)*psz++];
500         if (c == (signed char)-1)
501             break;
502         n |= c;
503         vch.push_back(n);
504     }
505     return vch;
506 }
507
508 vector<unsigned char> ParseHex(const string& str)
509 {
510     return ParseHex(str.c_str());
511 }
512
513 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
514 {
515     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
516     if (name.find("-no") == 0)
517     {
518         std::string positive("-");
519         positive.append(name.begin()+3, name.end());
520         if (mapSettingsRet.count(positive) == 0)
521         {
522             bool value = !GetBoolArg(name);
523             mapSettingsRet[positive] = (value ? "1" : "0");
524         }
525     }
526 }
527
528 void ParseParameters(int argc, const char* const argv[])
529 {
530     mapArgs.clear();
531     mapMultiArgs.clear();
532     for (int i = 1; i < argc; i++)
533     {
534         char psz[10000];
535         strlcpy(psz, argv[i], sizeof(psz));
536         char* pszValue = (char*)"";
537         if (strchr(psz, '='))
538         {
539             pszValue = strchr(psz, '=');
540             *pszValue++ = '\0';
541         }
542         #ifdef WIN32
543         _strlwr(psz);
544         if (psz[0] == '/')
545             psz[0] = '-';
546         #endif
547         if (psz[0] != '-')
548             break;
549
550         mapArgs[psz] = pszValue;
551         mapMultiArgs[psz].push_back(pszValue);
552     }
553
554     // New 0.6 features:
555     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
556     {
557         string name = entry.first;
558
559         //  interpret --foo as -foo (as long as both are not set)
560         if (name.find("--") == 0)
561         {
562             std::string singleDash(name.begin()+1, name.end());
563             if (mapArgs.count(singleDash) == 0)
564                 mapArgs[singleDash] = entry.second;
565             name = singleDash;
566         }
567
568         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
569         InterpretNegativeSetting(name, mapArgs);
570     }
571 }
572
573 std::string GetArg(const std::string& strArg, const std::string& strDefault)
574 {
575     if (mapArgs.count(strArg))
576         return mapArgs[strArg];
577     return strDefault;
578 }
579
580 int64 GetArg(const std::string& strArg, int64 nDefault)
581 {
582     if (mapArgs.count(strArg))
583         return atoi64(mapArgs[strArg]);
584     return nDefault;
585 }
586
587 bool GetBoolArg(const std::string& strArg, bool fDefault)
588 {
589     if (mapArgs.count(strArg))
590     {
591         if (mapArgs[strArg].empty())
592             return true;
593         return (atoi(mapArgs[strArg]) != 0);
594     }
595     return fDefault;
596 }
597
598 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
599 {
600     if (mapArgs.count(strArg))
601         return false;
602     mapArgs[strArg] = strValue;
603     return true;
604 }
605
606 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
607 {
608     if (fValue)
609         return SoftSetArg(strArg, std::string("1"));
610     else
611         return SoftSetArg(strArg, std::string("0"));
612 }
613
614
615 string EncodeBase64(const unsigned char* pch, size_t len)
616 {
617     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
618
619     string strRet="";
620     strRet.reserve((len+2)/3*4);
621
622     int mode=0, left=0;
623     const unsigned char *pchEnd = pch+len;
624
625     while (pch<pchEnd)
626     {
627         int enc = *(pch++);
628         switch (mode)
629         {
630             case 0: // we have no bits
631                 strRet += pbase64[enc >> 2];
632                 left = (enc & 3) << 4;
633                 mode = 1;
634                 break;
635
636             case 1: // we have two bits
637                 strRet += pbase64[left | (enc >> 4)];
638                 left = (enc & 15) << 2;
639                 mode = 2;
640                 break;
641
642             case 2: // we have four bits
643                 strRet += pbase64[left | (enc >> 6)];
644                 strRet += pbase64[enc & 63];
645                 mode = 0;
646                 break;
647         }
648     }
649
650     if (mode)
651     {
652         strRet += pbase64[left];
653         strRet += '=';
654         if (mode == 1)
655             strRet += '=';
656     }
657
658     return strRet;
659 }
660
661 string EncodeBase64(const string& str)
662 {
663     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
664 }
665
666 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
667 {
668     static const int decode64_table[256] =
669     {
670         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
671         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
672         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
673         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
674         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
675         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
676         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
677         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
678         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
679         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
680         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
681         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
682         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
683     };
684
685     if (pfInvalid)
686         *pfInvalid = false;
687
688     vector<unsigned char> vchRet;
689     vchRet.reserve(strlen(p)*3/4);
690
691     int mode = 0;
692     int left = 0;
693
694     while (1)
695     {
696          int dec = decode64_table[(unsigned char)*p];
697          if (dec == -1) break;
698          p++;
699          switch (mode)
700          {
701              case 0: // we have no bits and get 6
702                  left = dec;
703                  mode = 1;
704                  break;
705
706               case 1: // we have 6 bits and keep 4
707                   vchRet.push_back((left<<2) | (dec>>4));
708                   left = dec & 15;
709                   mode = 2;
710                   break;
711
712              case 2: // we have 4 bits and get 6, we keep 2
713                  vchRet.push_back((left<<4) | (dec>>2));
714                  left = dec & 3;
715                  mode = 3;
716                  break;
717
718              case 3: // we have 2 bits and get 6
719                  vchRet.push_back((left<<6) | dec);
720                  mode = 0;
721                  break;
722          }
723     }
724
725     if (pfInvalid)
726         switch (mode)
727         {
728             case 0: // 4n base64 characters processed: ok
729                 break;
730
731             case 1: // 4n+1 base64 character processed: impossible
732                 *pfInvalid = true;
733                 break;
734
735             case 2: // 4n+2 base64 characters processed: require '=='
736                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
737                     *pfInvalid = true;
738                 break;
739
740             case 3: // 4n+3 base64 characters processed: require '='
741                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
742                     *pfInvalid = true;
743                 break;
744         }
745
746     return vchRet;
747 }
748
749 string DecodeBase64(const string& str)
750 {
751     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
752     return string((const char*)&vchRet[0], vchRet.size());
753 }
754
755 string EncodeBase32(const unsigned char* pch, size_t len)
756 {
757     static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
758
759     string strRet="";
760     strRet.reserve((len+4)/5*8);
761
762     int mode=0, left=0;
763     const unsigned char *pchEnd = pch+len;
764
765     while (pch<pchEnd)
766     {
767         int enc = *(pch++);
768         switch (mode)
769         {
770             case 0: // we have no bits
771                 strRet += pbase32[enc >> 3];
772                 left = (enc & 7) << 2;
773                 mode = 1;
774                 break;
775
776             case 1: // we have three bits
777                 strRet += pbase32[left | (enc >> 6)];
778                 strRet += pbase32[(enc >> 1) & 31];
779                 left = (enc & 1) << 4;
780                 mode = 2;
781                 break;
782
783             case 2: // we have one bit
784                 strRet += pbase32[left | (enc >> 4)];
785                 left = (enc & 15) << 1;
786                 mode = 3;
787                 break;
788
789             case 3: // we have four bits
790                 strRet += pbase32[left | (enc >> 7)];
791                 strRet += pbase32[(enc >> 2) & 31];
792                 left = (enc & 3) << 3;
793                 mode = 4;
794                 break;
795
796             case 4: // we have two bits
797                 strRet += pbase32[left | (enc >> 5)];
798                 strRet += pbase32[enc & 31];
799                 mode = 0;
800         }
801     }
802
803     static const int nPadding[5] = {0, 6, 4, 3, 1};
804     if (mode)
805     {
806         strRet += pbase32[left];
807         for (int n=0; n<nPadding[mode]; n++)
808              strRet += '=';
809     }
810
811     return strRet;
812 }
813
814 string EncodeBase32(const string& str)
815 {
816     return EncodeBase32((const unsigned char*)str.c_str(), str.size());
817 }
818
819 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
820 {
821     static const int decode32_table[256] =
822     {
823         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
824         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
825         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
826         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
827         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,  0,  1,  2,
828          3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
829         23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
830         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
831         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
832         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
833         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
834         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
835         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
836     };
837
838     if (pfInvalid)
839         *pfInvalid = false;
840
841     vector<unsigned char> vchRet;
842     vchRet.reserve((strlen(p))*5/8);
843
844     int mode = 0;
845     int left = 0;
846
847     while (1)
848     {
849          int dec = decode32_table[(unsigned char)*p];
850          if (dec == -1) break;
851          p++;
852          switch (mode)
853          {
854              case 0: // we have no bits and get 5
855                  left = dec;
856                  mode = 1;
857                  break;
858
859               case 1: // we have 5 bits and keep 2
860                   vchRet.push_back((left<<3) | (dec>>2));
861                   left = dec & 3;
862                   mode = 2;
863                   break;
864
865              case 2: // we have 2 bits and keep 7
866                  left = left << 5 | dec;
867                  mode = 3;
868                  break;
869
870              case 3: // we have 7 bits and keep 4
871                  vchRet.push_back((left<<1) | (dec>>4));
872                  left = dec & 15;
873                  mode = 4;
874                  break;
875
876              case 4: // we have 4 bits, and keep 1
877                  vchRet.push_back((left<<4) | (dec>>1));
878                  left = dec & 1;
879                  mode = 5;
880                  break;
881
882              case 5: // we have 1 bit, and keep 6
883                  left = left << 5 | dec;
884                  mode = 6;
885                  break;
886
887              case 6: // we have 6 bits, and keep 3
888                  vchRet.push_back((left<<2) | (dec>>3));
889                  left = dec & 7;
890                  mode = 7;
891                  break;
892
893              case 7: // we have 3 bits, and keep 0
894                  vchRet.push_back((left<<5) | dec);
895                  mode = 0;
896                  break;
897          }
898     }
899
900     if (pfInvalid)
901         switch (mode)
902         {
903             case 0: // 8n base32 characters processed: ok
904                 break;
905
906             case 1: // 8n+1 base32 characters processed: impossible
907             case 3: //   +3
908             case 6: //   +6
909                 *pfInvalid = true;
910                 break;
911
912             case 2: // 8n+2 base32 characters processed: require '======'
913                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
914                     *pfInvalid = true;
915                 break;
916
917             case 4: // 8n+4 base32 characters processed: require '===='
918                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
919                     *pfInvalid = true;
920                 break;
921
922             case 5: // 8n+5 base32 characters processed: require '==='
923                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
924                     *pfInvalid = true;
925                 break;
926
927             case 7: // 8n+7 base32 characters processed: require '='
928                 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
929                     *pfInvalid = true;
930                 break;
931         }
932
933     return vchRet;
934 }
935
936 string DecodeBase32(const string& str)
937 {
938     vector<unsigned char> vchRet = DecodeBase32(str.c_str());
939     return string((const char*)&vchRet[0], vchRet.size());
940 }
941
942
943 int64 DecodeDumpTime(const std::string& s)
944 {
945     bt::ptime pt;
946
947     for(size_t i=0; i<formats_n; ++i)
948     {
949         std::istringstream is(s);
950         is.imbue(formats[i]);
951         is >> pt;
952         if(pt != bt::ptime()) break;
953     }
954
955     return pt_to_time_t(pt);
956 }
957
958 std::string EncodeDumpTime(int64 nTime) {
959     return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
960 }
961
962 std::string EncodeDumpString(const std::string &str) {
963     std::stringstream ret;
964     BOOST_FOREACH(unsigned char c, str) {
965         if (c <= 32 || c >= 128 || c == '%') {
966             ret << '%' << HexStr(&c, &c + 1);
967         } else {
968             ret << c;
969         }
970     }
971     return ret.str();
972 }
973
974 std::string DecodeDumpString(const std::string &str) {
975     std::stringstream ret;
976     for (unsigned int pos = 0; pos < str.length(); pos++) {
977         unsigned char c = str[pos];
978         if (c == '%' && pos+2 < str.length()) {
979             c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | 
980                 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
981             pos += 2;
982         }
983         ret << c;
984     }
985     return ret.str();
986 }
987
988 bool WildcardMatch(const char* psz, const char* mask)
989 {
990     while (true)
991     {
992         switch (*mask)
993         {
994         case '\0':
995             return (*psz == '\0');
996         case '*':
997             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
998         case '?':
999             if (*psz == '\0')
1000                 return false;
1001             break;
1002         default:
1003             if (*psz != *mask)
1004                 return false;
1005             break;
1006         }
1007         psz++;
1008         mask++;
1009     }
1010 }
1011
1012 bool WildcardMatch(const string& str, const string& mask)
1013 {
1014     return WildcardMatch(str.c_str(), mask.c_str());
1015 }
1016
1017
1018
1019
1020
1021
1022
1023
1024 static std::string FormatException(std::exception* pex, const char* pszThread)
1025 {
1026 #ifdef WIN32
1027     char pszModule[MAX_PATH] = "";
1028     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1029 #else
1030     const char* pszModule = "novacoin";
1031 #endif
1032     if (pex)
1033         return strprintf(
1034             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1035     else
1036         return strprintf(
1037             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
1038 }
1039
1040 void LogException(std::exception* pex, const char* pszThread)
1041 {
1042     std::string message = FormatException(pex, pszThread);
1043     printf("\n%s", message.c_str());
1044 }
1045
1046 void PrintException(std::exception* pex, const char* pszThread)
1047 {
1048     std::string message = FormatException(pex, pszThread);
1049     printf("\n\n************************\n%s\n", message.c_str());
1050     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1051     strMiscWarning = message;
1052     throw;
1053 }
1054
1055 void LogStackTrace() {
1056     printf("\n\n******* exception encountered *******\n");
1057     if (fileout)
1058     {
1059 #ifndef WIN32
1060         void* pszBuffer[32];
1061         size_t size;
1062         size = backtrace(pszBuffer, 32);
1063         backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1064 #endif
1065     }
1066 }
1067
1068 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1069 {
1070     std::string message = FormatException(pex, pszThread);
1071     printf("\n\n************************\n%s\n", message.c_str());
1072     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1073     strMiscWarning = message;
1074 }
1075
1076 boost::filesystem::path GetDefaultDataDir()
1077 {
1078     namespace fs = boost::filesystem;
1079     // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1080     // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1081     // Mac: ~/Library/Application Support/NovaCoin
1082     // Unix: ~/.novacoin
1083 #ifdef WIN32
1084     // Windows
1085     return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1086 #else
1087     fs::path pathRet;
1088     char* pszHome = getenv("HOME");
1089     if (pszHome == NULL || strlen(pszHome) == 0)
1090         pathRet = fs::path("/");
1091     else
1092         pathRet = fs::path(pszHome);
1093 #ifdef MAC_OSX
1094     // Mac
1095     pathRet /= "Library/Application Support";
1096     fs::create_directory(pathRet);
1097     return pathRet / "NovaCoin";
1098 #else
1099     // Unix
1100     return pathRet / ".novacoin";
1101 #endif
1102 #endif
1103 }
1104
1105 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1106 {
1107     namespace fs = boost::filesystem;
1108
1109     static fs::path pathCached[2];
1110     static CCriticalSection csPathCached;
1111     static bool cachedPath[2] = {false, false};
1112
1113     fs::path &path = pathCached[fNetSpecific];
1114
1115     // This can be called during exceptions by printf, so we cache the
1116     // value so we don't have to do memory allocations after that.
1117     if (cachedPath[fNetSpecific])
1118         return path;
1119
1120     LOCK(csPathCached);
1121
1122     if (mapArgs.count("-datadir")) {
1123         path = fs::system_complete(mapArgs["-datadir"]);
1124         if (!fs::is_directory(path)) {
1125             path = "";
1126             return path;
1127         }
1128     } else {
1129         path = GetDefaultDataDir();
1130     }
1131     if (fNetSpecific && GetBoolArg("-testnet", false))
1132         path /= "testnet2";
1133
1134     fs::create_directory(path);
1135
1136     cachedPath[fNetSpecific]=true;
1137     return path;
1138 }
1139
1140 boost::filesystem::path GetConfigFile()
1141 {
1142     boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1143     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1144     return pathConfigFile;
1145 }
1146
1147 void ReadConfigFile(map<string, string>& mapSettingsRet,
1148                     map<string, vector<string> >& mapMultiSettingsRet)
1149 {
1150     boost::filesystem::ifstream streamConfig(GetConfigFile());
1151     if (!streamConfig.good())
1152         return; // No bitcoin.conf file is OK
1153
1154     set<string> setOptions;
1155     setOptions.insert("*");
1156
1157     for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1158     {
1159         // Don't overwrite existing settings so command line settings override bitcoin.conf
1160         string strKey = string("-") + it->string_key;
1161         if (mapSettingsRet.count(strKey) == 0)
1162         {
1163             mapSettingsRet[strKey] = it->value[0];
1164             // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1165             InterpretNegativeSetting(strKey, mapSettingsRet);
1166         }
1167         mapMultiSettingsRet[strKey].push_back(it->value[0]);
1168     }
1169 }
1170
1171 boost::filesystem::path GetPidFile()
1172 {
1173     boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1174     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1175     return pathPidFile;
1176 }
1177
1178 #ifndef WIN32
1179 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1180 {
1181     FILE* file = fopen(path.string().c_str(), "w");
1182     if (file)
1183     {
1184         fprintf(file, "%d\n", pid);
1185         fclose(file);
1186     }
1187 }
1188 #endif
1189
1190 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1191 {
1192 #ifdef WIN32
1193     return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1194                       MOVEFILE_REPLACE_EXISTING);
1195 #else
1196     int rc = std::rename(src.string().c_str(), dest.string().c_str());
1197     return (rc == 0);
1198 #endif /* WIN32 */
1199 }
1200
1201 void FileCommit(FILE *fileout)
1202 {
1203     fflush(fileout);                // harmless if redundantly called
1204 #ifdef WIN32
1205     _commit(_fileno(fileout));
1206 #else
1207     fsync(fileno(fileout));
1208 #endif
1209 }
1210
1211 int GetFilesize(FILE* file)
1212 {
1213     int nSavePos = ftell(file);
1214     int nFilesize = -1;
1215     if (fseek(file, 0, SEEK_END) == 0)
1216         nFilesize = ftell(file);
1217     fseek(file, nSavePos, SEEK_SET);
1218     return nFilesize;
1219 }
1220
1221 void ShrinkDebugFile()
1222 {
1223     // Scroll debug.log if it's getting too big
1224     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1225     FILE* file = fopen(pathLog.string().c_str(), "r");
1226     if (file && GetFilesize(file) > 10 * 1000000)
1227     {
1228         // Restart the file with some of the end
1229         char pch[200000];
1230         fseek(file, -sizeof(pch), SEEK_END);
1231         int nBytes = fread(pch, 1, sizeof(pch), file);
1232         fclose(file);
1233
1234         file = fopen(pathLog.string().c_str(), "w");
1235         if (file)
1236         {
1237             fwrite(pch, 1, nBytes, file);
1238             fclose(file);
1239         }
1240     }
1241 }
1242
1243
1244
1245
1246
1247
1248
1249
1250 //
1251 // "Never go to sea with two chronometers; take one or three."
1252 // Our three time sources are:
1253 //  - System clock
1254 //  - Median of other nodes clocks
1255 //  - The user (asking the user to fix the system clock if the first two disagree)
1256 //
1257 static int64 nMockTime = 0;  // For unit testing
1258
1259 int64 GetTime()
1260 {
1261     if (nMockTime) return nMockTime;
1262
1263     return time(NULL);
1264 }
1265
1266 void SetMockTime(int64 nMockTimeIn)
1267 {
1268     nMockTime = nMockTimeIn;
1269 }
1270
1271 static int64 nTimeOffset = 0;
1272
1273 int64 GetTimeOffset()
1274 {
1275     return nTimeOffset;
1276 }
1277
1278 int64 GetAdjustedTime()
1279 {
1280     return GetTime() + GetTimeOffset();
1281 }
1282
1283 void AddTimeData(const CNetAddr& ip, int64 nTime)
1284 {
1285     int64 nOffsetSample = nTime - GetTime();
1286
1287     // Ignore duplicates
1288     static set<CNetAddr> setKnown;
1289     if (!setKnown.insert(ip).second)
1290         return;
1291
1292     // Add data
1293     vTimeOffsets.input(nOffsetSample);
1294     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1295     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1296     {
1297         int64 nMedian = vTimeOffsets.median();
1298         std::vector<int64> vSorted = vTimeOffsets.sorted();
1299         // Only let other nodes change our time by so much
1300         if (abs64(nMedian) < 70 * 60)
1301         {
1302             nTimeOffset = nMedian;
1303         }
1304         else
1305         {
1306             nTimeOffset = 0;
1307
1308             static bool fDone;
1309             if (!fDone)
1310             {
1311                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1312                 bool fMatch = false;
1313                 BOOST_FOREACH(int64 nOffset, vSorted)
1314                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1315                         fMatch = true;
1316
1317                 if (!fMatch)
1318                 {
1319                     fDone = true;
1320                     string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1321                     strMiscWarning = strMessage;
1322                     printf("*** %s\n", strMessage.c_str());
1323                     uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1324                 }
1325             }
1326         }
1327         if (fDebug) {
1328             BOOST_FOREACH(int64 n, vSorted)
1329                 printf("%+"PRI64d"  ", n);
1330             printf("|  ");
1331         }
1332         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1333     }
1334 }
1335
1336
1337
1338
1339
1340
1341
1342
1343 string FormatVersion(int nVersion)
1344 {
1345     if (nVersion%100 == 0)
1346         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1347     else
1348         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1349 }
1350
1351 string FormatFullVersion()
1352 {
1353     return CLIENT_BUILD;
1354 }
1355
1356 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1357 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1358 {
1359     std::ostringstream ss;
1360     ss << "/";
1361     ss << name << ":" << FormatVersion(nClientVersion);
1362     if (!comments.empty())
1363         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1364     ss << "/";
1365     return ss.str();
1366 }
1367
1368 #ifdef WIN32
1369 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1370 {
1371     namespace fs = boost::filesystem;
1372
1373     char pszPath[MAX_PATH] = "";
1374
1375     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1376     {
1377         return fs::path(pszPath);
1378     }
1379
1380     printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1381     return fs::path("");
1382 }
1383 #endif
1384
1385 void runCommand(std::string strCommand)
1386 {
1387     int nErr = ::system(strCommand.c_str());
1388     if (nErr)
1389         printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1390 }
1391
1392 void RenameThread(const char* name)
1393 {
1394 #if defined(PR_SET_NAME)
1395     // Only the first 15 characters are used (16 - NUL terminator)
1396     ::prctl(PR_SET_NAME, name, 0, 0, 0);
1397 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1398     // TODO: This is currently disabled because it needs to be verified to work
1399     //       on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1400     //       removed.
1401     pthread_set_name_np(pthread_self(), name);
1402
1403 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1404 // #elif defined(MAC_OSX)
1405 //    pthread_setname_np(name);
1406
1407 #else
1408     // Prevent warnings for unused parameters...
1409     (void)name;
1410 #endif
1411 }
1412
1413 bool NewThread(void(*pfn)(void*), void* parg)
1414 {
1415     try
1416     {
1417         boost::thread(pfn, parg); // thread detaches when out of scope
1418     } catch(boost::thread_resource_error &e) {
1419         printf("Error creating thread: %s\n", e.what());
1420         return false;
1421     }
1422     return true;
1423 }