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.
7 #include "allocators.h"
13 #include <boost/program_options/detail/config_file.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/date_time/posix_time/posix_time.hpp>
17 #include <boost/thread.hpp>
20 #include <io.h> /* for _commit */
22 #include <openssl/rand.h> // RAND_screen
23 #elif defined(__linux__)
24 #include <sys/prctl.h>
27 #if !defined(WIN32) && !defined(ANDROID)
33 namespace bt = boost::posix_time;
35 map<string, string> mapArgs;
36 map<string, vector<string> > mapMultiArgs;
38 bool fDebugNet = false;
39 bool fPrintToConsole = false;
40 bool fPrintToDebugger = false;
41 bool fRequestShutdown = false;
42 bool fShutdown = false;
45 bool fCommandLine = false;
46 string strMiscWarning;
47 bool fTestNet = false;
48 bool fNoListen = false;
49 bool fLogTimestamps = false;
50 bool fReopenDebugLog = false;
52 // Extended DecodeDumpTime implementation, see this page for details:
53 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
54 const std::locale formats[] = {
55 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
56 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
57 std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
58 std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
59 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
62 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
64 std::time_t pt_to_time_t(const bt::ptime& pt)
66 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
67 bt::time_duration diff = pt - timet_start;
68 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
71 // Init OpenSSL library multithreading support
72 static CCriticalSection** ppmutexOpenSSL;
73 void locking_callback(int mode, int i, const char* file, int line)
75 if (mode & CRYPTO_LOCK) {
76 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
78 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
88 // Init OpenSSL library multithreading support
89 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
90 for (int i = 0; i < CRYPTO_num_locks(); i++)
91 ppmutexOpenSSL[i] = new CCriticalSection();
92 CRYPTO_set_locking_callback(locking_callback);
95 // Seed random number generator with screen scrape and other hardware sources
99 // Seed random number generator with performance counter
104 // Shutdown OpenSSL library multithreading support
105 CRYPTO_set_locking_callback(NULL);
106 for (int i = 0; i < CRYPTO_num_locks(); i++)
107 delete ppmutexOpenSSL[i];
108 OPENSSL_free(ppmutexOpenSSL);
114 static FILE* fileout = NULL;
116 inline int OutputDebugStringF(const char* pszFormat, ...)
123 va_start(arg_ptr, pszFormat);
124 ret = vprintf(pszFormat, arg_ptr);
127 else if (!fPrintToDebugger)
129 // print to debug.log
133 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
134 fileout = fopen(pathDebug.string().c_str(), "a");
135 if (fileout) setbuf(fileout, NULL); // unbuffered
139 static bool fStartedNewLine = true;
141 // This routine may be called by global destructors during shutdown.
142 // Since the order of destruction of static/global objects is undefined,
143 // allocate mutexDebugLog on the heap the first time this routine
144 // is called to avoid crashes during shutdown.
145 static std::mutex* mutexDebugLog = nullptr;
146 if (mutexDebugLog == nullptr) mutexDebugLog = new std::mutex();
147 std::scoped_lock scoped_lock(*mutexDebugLog);
149 // reopen the log file, if requested
150 if (fReopenDebugLog) {
151 fReopenDebugLog = false;
152 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
153 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
154 setbuf(fileout, NULL); // unbuffered
157 // Debug print useful for profiling
158 if (fLogTimestamps && fStartedNewLine)
159 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
160 if (pszFormat[strlen(pszFormat) - 1] == '\n')
161 fStartedNewLine = true;
163 fStartedNewLine = false;
166 va_start(arg_ptr, pszFormat);
167 ret = vfprintf(fileout, pszFormat, arg_ptr);
173 if (fPrintToDebugger)
175 static CCriticalSection cs_OutputDebugStringF;
177 // accumulate and output a line at a time
179 LOCK(cs_OutputDebugStringF);
180 static std::string buffer;
183 va_start(arg_ptr, pszFormat);
184 buffer += vstrprintf(pszFormat, arg_ptr);
187 size_t line_start = 0, line_end;
188 while((line_end = buffer.find('\n', line_start)) != -1)
190 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
191 line_start = line_end + 1;
193 buffer.erase(0, line_start);
200 string vstrprintf(const char *format, va_list ap)
204 int limit = sizeof(buffer);
210 va_copy(arg_ptr, ap);
212 va_list arg_ptr = ap;
215 ret = _vsnprintf(p, limit, format, arg_ptr);
217 ret = vsnprintf(p, limit, format, arg_ptr);
220 if (ret >= 0 && ret < limit)
225 p = new(nothrow) char[limit];
227 throw std::bad_alloc();
229 string str(p, p+ret);
235 string real_strprintf(const char *format, int dummy, ...)
238 va_start(arg_ptr, dummy);
239 string str = vstrprintf(format, arg_ptr);
244 string real_strprintf(const std::string &format, int dummy, ...)
247 va_start(arg_ptr, dummy);
248 string str = vstrprintf(format.c_str(), arg_ptr);
253 bool error(const char *format, ...)
256 va_start(arg_ptr, format);
257 std::string str = vstrprintf(format, arg_ptr);
259 printf("ERROR: %s\n", str.c_str());
264 void ParseString(const string& str, char c, vector<string>& v)
268 string::size_type i1 = 0;
269 string::size_type i2;
272 i2 = str.find(c, i1);
275 v.push_back(str.substr(i1));
278 v.push_back(str.substr(i1, i2-i1));
284 string FormatMoney(int64_t n, bool fPlus)
286 // Note: not using straight sprintf here because we do NOT want
287 // localized number formatting.
288 int64_t n_abs = (n > 0 ? n : -n);
289 int64_t quotient = n_abs/COIN;
290 int64_t remainder = n_abs%COIN;
291 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
293 // Right-trim excess zeros before the decimal point:
295 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
298 str.erase(str.size()-nTrim, nTrim);
301 str.insert(0u, 1, '-');
302 else if (fPlus && n > 0)
303 str.insert(0u, 1, '+');
308 bool ParseMoney(const string& str, int64_t& nRet)
310 return ParseMoney(str.c_str(), nRet);
313 bool ParseMoney(const char* pszIn, int64_t& nRet)
317 const char* p = pszIn;
325 int64_t nMult = CENT*10;
326 while (isdigit(*p) && (nMult > 0))
328 nUnits += nMult * (*p++ - '0');
337 strWhole.insert(strWhole.end(), *p);
342 if (strWhole.size() > 10) // guard against 63 bit overflow
344 if (nUnits < 0 || nUnits > COIN)
346 int64_t nWhole = atoi64(strWhole);
347 int64_t nValue = nWhole*COIN + nUnits;
354 static const signed char phexdigit[256] =
355 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
356 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
357 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
358 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
359 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
360 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
361 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
362 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
363 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
364 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
365 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
366 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
367 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
368 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
369 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
370 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
372 bool IsHex(const string& str)
374 for (unsigned char c : str)
376 if (phexdigit[c] < 0)
379 return (str.size() > 0) && (str.size()%2 == 0);
382 vector<unsigned char> ParseHex(const char* psz)
384 // convert hex dump to vector
385 vector<unsigned char> vch;
388 while (isspace(*psz))
390 signed char c = phexdigit[(unsigned char)*psz++];
391 if (c == (signed char)-1)
393 unsigned char n = (c << 4);
394 c = phexdigit[(unsigned char)*psz++];
395 if (c == (signed char)-1)
403 vector<unsigned char> ParseHex(const string& str)
405 return ParseHex(str.c_str());
408 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
410 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
411 if (name.find("-no") == 0)
413 std::string positive("-");
414 positive.append(name.begin()+3, name.end());
415 if (mapSettingsRet.count(positive) == 0)
417 bool value = !GetBoolArg(name);
418 mapSettingsRet[positive] = (value ? "1" : "0");
423 void ParseParameters(int argc, const char* const argv[])
426 mapMultiArgs.clear();
427 for (int i = 1; i < argc; i++)
429 std::string str(argv[i]);
430 std::string strValue;
431 size_t is_index = str.find('=');
432 if (is_index != std::string::npos)
434 strValue = str.substr(is_index+1);
435 str = str.substr(0, is_index);
438 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
439 if (str.compare(0,1, "/") == 0)
440 str = "-" + str.substr(1);
445 mapArgs[str] = strValue;
446 mapMultiArgs[str].push_back(strValue);
450 for (const auto& entry : mapArgs)
452 string name = entry.first;
454 // interpret --foo as -foo (as long as both are not set)
455 if (name.find("--") == 0)
457 std::string singleDash(name.begin()+1, name.end());
458 if (mapArgs.count(singleDash) == 0)
459 mapArgs[singleDash] = entry.second;
463 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
464 InterpretNegativeSetting(name, mapArgs);
468 std::string GetArg(const std::string& strArg, const std::string& strDefault)
470 if (mapArgs.count(strArg))
471 return mapArgs[strArg];
475 int64_t GetArg(const std::string& strArg, int64_t nDefault)
477 if (mapArgs.count(strArg))
478 return atoi64(mapArgs[strArg]);
482 int32_t GetArgInt(const std::string& strArg, int32_t nDefault)
484 if (mapArgs.count(strArg))
485 return strtol(mapArgs[strArg]);
489 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault)
491 if (mapArgs.count(strArg))
492 return strtoul(mapArgs[strArg]);
496 bool GetBoolArg(const std::string& strArg, bool fDefault)
498 if (mapArgs.count(strArg))
500 if (mapArgs[strArg].empty())
502 return (atoi(mapArgs[strArg]) != 0);
507 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
509 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
511 mapArgs[strArg] = strValue;
512 mapMultiArgs[strArg].push_back(strValue);
517 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
520 return SoftSetArg(strArg, std::string("1"));
522 return SoftSetArg(strArg, std::string("0"));
526 string EncodeBase64(const unsigned char* pch, size_t len)
528 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
531 strRet.reserve((len+2)/3*4);
534 const unsigned char *pchEnd = pch+len;
541 case 0: // we have no bits
542 strRet += pbase64[enc >> 2];
543 left = (enc & 3) << 4;
547 case 1: // we have two bits
548 strRet += pbase64[left | (enc >> 4)];
549 left = (enc & 15) << 2;
553 case 2: // we have four bits
554 strRet += pbase64[left | (enc >> 6)];
555 strRet += pbase64[enc & 63];
563 strRet += pbase64[left];
572 string EncodeBase64(const string& str)
574 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
577 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
579 static const int decode64_table[256] =
581 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
582 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
583 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
584 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
585 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
586 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
587 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
588 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
589 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
590 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
591 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
592 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
593 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
599 vector<unsigned char> vchRet;
600 vchRet.reserve(strlen(p)*3/4);
607 int dec = decode64_table[(unsigned char)*p];
608 if (dec == -1) break;
612 case 0: // we have no bits and get 6
617 case 1: // we have 6 bits and keep 4
618 vchRet.push_back((left<<2) | (dec>>4));
623 case 2: // we have 4 bits and get 6, we keep 2
624 vchRet.push_back((left<<4) | (dec>>2));
629 case 3: // we have 2 bits and get 6
630 vchRet.push_back((left<<6) | dec);
639 case 0: // 4n base64 characters processed: ok
642 case 1: // 4n+1 base64 character processed: impossible
646 case 2: // 4n+2 base64 characters processed: require '=='
647 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
651 case 3: // 4n+3 base64 characters processed: require '='
652 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
660 string DecodeBase64(const string& str)
662 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
663 return string((const char*)&vchRet[0], vchRet.size());
666 string EncodeBase32(const unsigned char* pch, size_t len)
668 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
671 strRet.reserve((len+4)/5*8);
674 const unsigned char *pchEnd = pch+len;
681 case 0: // we have no bits
682 strRet += pbase32[enc >> 3];
683 left = (enc & 7) << 2;
687 case 1: // we have three bits
688 strRet += pbase32[left | (enc >> 6)];
689 strRet += pbase32[(enc >> 1) & 31];
690 left = (enc & 1) << 4;
694 case 2: // we have one bit
695 strRet += pbase32[left | (enc >> 4)];
696 left = (enc & 15) << 1;
700 case 3: // we have four bits
701 strRet += pbase32[left | (enc >> 7)];
702 strRet += pbase32[(enc >> 2) & 31];
703 left = (enc & 3) << 3;
707 case 4: // we have two bits
708 strRet += pbase32[left | (enc >> 5)];
709 strRet += pbase32[enc & 31];
714 static const int nPadding[5] = {0, 6, 4, 3, 1};
717 strRet += pbase32[left];
718 for (int n=0; n<nPadding[mode]; n++)
725 string EncodeBase32(const string& str)
727 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
730 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
732 static const int decode32_table[256] =
734 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
735 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
736 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
737 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
738 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
739 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
740 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
741 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
742 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
743 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
744 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
745 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
746 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
752 vector<unsigned char> vchRet;
753 vchRet.reserve((strlen(p))*5/8);
760 int dec = decode32_table[(unsigned char)*p];
761 if (dec == -1) break;
765 case 0: // we have no bits and get 5
770 case 1: // we have 5 bits and keep 2
771 vchRet.push_back((left<<3) | (dec>>2));
776 case 2: // we have 2 bits and keep 7
777 left = left << 5 | dec;
781 case 3: // we have 7 bits and keep 4
782 vchRet.push_back((left<<1) | (dec>>4));
787 case 4: // we have 4 bits, and keep 1
788 vchRet.push_back((left<<4) | (dec>>1));
793 case 5: // we have 1 bit, and keep 6
794 left = left << 5 | dec;
798 case 6: // we have 6 bits, and keep 3
799 vchRet.push_back((left<<2) | (dec>>3));
804 case 7: // we have 3 bits, and keep 0
805 vchRet.push_back((left<<5) | dec);
814 case 0: // 8n base32 characters processed: ok
817 case 1: // 8n+1 base32 characters processed: impossible
823 case 2: // 8n+2 base32 characters processed: require '======'
824 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
828 case 4: // 8n+4 base32 characters processed: require '===='
829 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
833 case 5: // 8n+5 base32 characters processed: require '==='
834 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
838 case 7: // 8n+7 base32 characters processed: require '='
839 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
847 string DecodeBase32(const string& str)
849 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
850 return string((const char*)&vchRet[0], vchRet.size());
854 int64_t DecodeDumpTime(const std::string& s)
858 for(size_t i=0; i<formats_n; ++i)
860 std::istringstream is(s);
861 is.imbue(formats[i]);
863 if(pt != bt::ptime()) break;
866 return pt_to_time_t(pt);
869 std::string EncodeDumpTime(int64_t nTime) {
870 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
873 std::string EncodeDumpString(const std::string &str) {
874 std::stringstream ret;
875 for (unsigned char c : str) {
876 if (c <= 32 || c >= 128 || c == '%') {
877 ret << '%' << HexStr(&c, &c + 1);
885 std::string DecodeDumpString(const std::string &str) {
886 std::stringstream ret;
887 for (unsigned int pos = 0; pos < str.length(); pos++) {
888 unsigned char c = str[pos];
889 if (c == '%' && pos+2 < str.length()) {
890 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
891 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
899 bool WildcardMatch(const char* psz, const char* mask)
906 return (*psz == '\0');
908 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
923 bool WildcardMatch(const string& str, const string& mask)
925 return WildcardMatch(str.c_str(), mask.c_str());
935 static std::string FormatException(std::exception* pex, const char* pszThread)
938 char pszModule[MAX_PATH] = "";
939 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
941 const char* pszModule = "novacoin";
945 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
948 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
951 void LogException(std::exception* pex, const char* pszThread)
953 std::string message = FormatException(pex, pszThread);
954 printf("\n%s", message.c_str());
957 void PrintException(std::exception* pex, const char* pszThread)
959 std::string message = FormatException(pex, pszThread);
960 printf("\n\n************************\n%s\n", message.c_str());
961 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
962 strMiscWarning = message;
966 void LogStackTrace() {
967 printf("\n\n******* exception encountered *******\n");
970 #if !defined(WIN32) && !defined(ANDROID)
973 size = backtrace(pszBuffer, 32);
974 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
979 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
981 std::string message = FormatException(pex, pszThread);
982 printf("\n\n************************\n%s\n", message.c_str());
983 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
984 strMiscWarning = message;
987 boost::filesystem::path GetDefaultDataDir()
989 namespace fs = boost::filesystem;
990 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
991 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
992 // Mac: ~/Library/Application Support/NovaCoin
996 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
999 char* pszHome = getenv("HOME");
1000 if (pszHome == NULL || strlen(pszHome) == 0)
1001 pathRet = fs::path("/");
1003 pathRet = fs::path(pszHome);
1006 pathRet /= "Library/Application Support";
1007 fs::create_directory(pathRet);
1008 return pathRet / "NovaCoin";
1011 return pathRet / ".novacoin";
1016 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1018 namespace fs = boost::filesystem;
1020 static fs::path pathCached[2];
1021 static CCriticalSection csPathCached;
1022 static bool cachedPath[2] = {false, false};
1024 fs::path &path = pathCached[fNetSpecific];
1026 // This can be called during exceptions by printf, so we cache the
1027 // value so we don't have to do memory allocations after that.
1028 if (cachedPath[fNetSpecific])
1033 if (mapArgs.count("-datadir")) {
1034 path = fs::system_complete(mapArgs["-datadir"]);
1035 if (!fs::is_directory(path)) {
1040 path = GetDefaultDataDir();
1042 if (fNetSpecific && GetBoolArg("-testnet", false))
1045 fs::create_directory(path);
1047 cachedPath[fNetSpecific]=true;
1051 string randomStrGen(int length) {
1052 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1054 result.resize(length);
1055 for (int32_t i = 0; i < length; i++)
1056 result[i] = charset[rand() % charset.length()];
1063 srand(static_cast<unsigned int>(time(NULL)));
1066 #if BOOST_FILESYSTEM_VERSION >= 3
1067 pConf.open(GetConfigFile().generic_string().c_str());
1069 pConf.open(GetConfigFile().string().c_str());
1071 pConf << "rpcuser=user\nrpcpassword="
1074 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1076 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1078 + "\nrpcallowip=127.0.0.1";
1082 boost::filesystem::path GetConfigFile()
1084 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1085 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1086 return pathConfigFile;
1089 void ReadConfigFile(map<string, string>& mapSettingsRet,
1090 map<string, vector<string> >& mapMultiSettingsRet)
1092 boost::filesystem::ifstream streamConfig(GetConfigFile());
1093 if (!streamConfig.good())
1096 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1097 if(!streamConfig.good())
1101 set<string> setOptions;
1102 setOptions.insert("*");
1104 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1106 // Don't overwrite existing settings so command line settings override bitcoin.conf
1107 string strKey = string("-") + it->string_key;
1108 if (mapSettingsRet.count(strKey) == 0)
1110 mapSettingsRet[strKey] = it->value[0];
1111 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1112 InterpretNegativeSetting(strKey, mapSettingsRet);
1114 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1118 boost::filesystem::path GetPidFile()
1120 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1121 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1126 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1128 FILE* file = fopen(path.string().c_str(), "w");
1131 fprintf(file, "%d\n", pid);
1137 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1140 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1141 MOVEFILE_REPLACE_EXISTING) != 0;
1143 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1148 void FileCommit(FILE *fileout)
1150 fflush(fileout); // harmless if redundantly called
1152 _commit(_fileno(fileout));
1154 fsync(fileno(fileout));
1158 int GetFilesize(FILE* file)
1160 int nSavePos = ftell(file);
1162 if (fseek(file, 0, SEEK_END) == 0)
1163 nFilesize = ftell(file);
1164 fseek(file, nSavePos, SEEK_SET);
1168 void ShrinkDebugFile()
1170 // Scroll debug.log if it's getting too big
1171 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1172 FILE* file = fopen(pathLog.string().c_str(), "r");
1173 if (file && GetFilesize(file) > 10 * 1000000)
1175 // Restart the file with some of the end
1177 vector<char>* vBuf = new vector <char>(200000, 0);
1178 fseek(file, -((long)(vBuf->size())), SEEK_END);
1179 size_t nBytes = fread(&vBuf->operator[](0), 1, vBuf->size(), file);
1181 file = fopen(pathLog.string().c_str(), "w");
1184 fwrite(&vBuf->operator[](0), 1, nBytes, file);
1189 catch (const bad_alloc& e) {
1190 // Bad things happen - no free memory in heap at program startup
1192 printf("Warning: %s in %s:%d\n ShrinkDebugFile failed - debug.log expands further", e.what(), __FILE__, __LINE__);
1203 int64_t now = time(NULL);
1208 string FormatVersion(int nVersion)
1210 if (nVersion%100 == 0)
1211 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1213 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1216 string FormatFullVersion()
1218 return CLIENT_BUILD;
1221 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1222 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1224 std::ostringstream ss;
1226 ss << name << ":" << FormatVersion(nClientVersion);
1227 if (!comments.empty())
1230 for (const auto& st : comments)
1233 if (st == comments.back()) break;
1243 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1245 namespace fs = boost::filesystem;
1247 char pszPath[MAX_PATH] = "";
1249 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1251 return fs::path(pszPath);
1254 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1255 return fs::path("");
1259 void runCommand(std::string strCommand)
1261 int nErr = ::system(strCommand.c_str());
1263 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1266 void RenameThread(const char* name)
1268 #if defined(PR_SET_NAME)
1269 // Only the first 15 characters are used (16 - NUL terminator)
1270 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1271 #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
1272 pthread_set_name_np(pthread_self(), name);
1273 #elif defined(__APPLE__)
1274 pthread_setname_np(name);
1276 // Prevent warnings for unused parameters...
1281 bool NewThread(void(*pfn)(void*), void* parg)
1285 boost::thread(pfn, parg); // thread detaches when out of scope
1286 } catch(boost::thread_resource_error &e) {
1287 printf("Error creating thread: %s\n", e.what());
1293 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1295 // std::locale takes ownership of the pointer
1296 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1297 std::stringstream ss;
1299 ss << boost::posix_time::from_time_t(nTime);