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 #elif defined(__linux__)
23 #include <sys/prctl.h>
26 #if !defined(WIN32) && !defined(ANDROID)
32 namespace bt = boost::posix_time;
34 map<string, string> mapArgs;
35 map<string, vector<string> > mapMultiArgs;
37 bool fDebugNet = false;
38 bool fPrintToConsole = false;
39 bool fPrintToDebugger = false;
40 bool fRequestShutdown = false;
41 bool fShutdown = false;
44 bool fCommandLine = false;
45 string strMiscWarning;
46 bool fTestNet = false;
47 bool fNoListen = false;
48 bool fLogTimestamps = false;
49 bool fReopenDebugLog = false;
51 // Extended DecodeDumpTime implementation, see this page for details:
52 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
53 const std::locale formats[] = {
54 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
55 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
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("%d.%m.%Y %H:%M:%S")),
58 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
61 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
63 std::time_t pt_to_time_t(const bt::ptime& pt)
65 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
66 bt::time_duration diff = pt - timet_start;
67 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
70 // Init OpenSSL library multithreading support
71 static CCriticalSection** ppmutexOpenSSL;
72 void locking_callback(int mode, int i, const char* file, int line)
74 if (mode & CRYPTO_LOCK) {
75 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
77 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
81 LockedPageManager LockedPageManager::instance;
89 // Init OpenSSL library multithreading support
90 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
91 for (int i = 0; i < CRYPTO_num_locks(); i++)
92 ppmutexOpenSSL[i] = new CCriticalSection();
93 CRYPTO_set_locking_callback(locking_callback);
96 // Seed random number generator with screen scrape and other hardware sources
100 // Seed random number generator with performance counter
105 // Shutdown OpenSSL library multithreading support
106 CRYPTO_set_locking_callback(NULL);
107 for (int i = 0; i < CRYPTO_num_locks(); i++)
108 delete ppmutexOpenSSL[i];
109 OPENSSL_free(ppmutexOpenSSL);
115 static FILE* fileout = NULL;
117 inline int OutputDebugStringF(const char* pszFormat, ...)
124 va_start(arg_ptr, pszFormat);
125 ret = vprintf(pszFormat, arg_ptr);
128 else if (!fPrintToDebugger)
130 // print to debug.log
134 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
135 fileout = fopen(pathDebug.string().c_str(), "a");
136 if (fileout) setbuf(fileout, NULL); // unbuffered
140 static bool fStartedNewLine = true;
142 // This routine may be called by global destructors during shutdown.
143 // Since the order of destruction of static/global objects is undefined,
144 // allocate mutexDebugLog on the heap the first time this routine
145 // is called to avoid crashes during shutdown.
146 static std::mutex* mutexDebugLog = nullptr;
147 if (mutexDebugLog == nullptr) mutexDebugLog = new std::mutex();
148 std::scoped_lock scoped_lock(*mutexDebugLog);
150 // reopen the log file, if requested
151 if (fReopenDebugLog) {
152 fReopenDebugLog = false;
153 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
154 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
155 setbuf(fileout, NULL); // unbuffered
158 // Debug print useful for profiling
159 if (fLogTimestamps && fStartedNewLine)
160 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
161 if (pszFormat[strlen(pszFormat) - 1] == '\n')
162 fStartedNewLine = true;
164 fStartedNewLine = false;
167 va_start(arg_ptr, pszFormat);
168 ret = vfprintf(fileout, pszFormat, arg_ptr);
174 if (fPrintToDebugger)
176 static CCriticalSection cs_OutputDebugStringF;
178 // accumulate and output a line at a time
180 LOCK(cs_OutputDebugStringF);
181 static std::string buffer;
184 va_start(arg_ptr, pszFormat);
185 buffer += vstrprintf(pszFormat, arg_ptr);
188 size_t line_start = 0, line_end;
189 while((line_end = buffer.find('\n', line_start)) != -1)
191 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
192 line_start = line_end + 1;
194 buffer.erase(0, line_start);
201 string vstrprintf(const char *format, va_list ap)
205 int limit = sizeof(buffer);
211 va_copy(arg_ptr, ap);
213 va_list arg_ptr = ap;
216 ret = _vsnprintf(p, limit, format, arg_ptr);
218 ret = vsnprintf(p, limit, format, arg_ptr);
221 if (ret >= 0 && ret < limit)
226 p = new(nothrow) char[limit];
228 throw std::bad_alloc();
230 string str(p, p+ret);
236 string real_strprintf(const char *format, int dummy, ...)
239 va_start(arg_ptr, dummy);
240 string str = vstrprintf(format, arg_ptr);
245 string real_strprintf(const std::string &format, int dummy, ...)
248 va_start(arg_ptr, dummy);
249 string str = vstrprintf(format.c_str(), arg_ptr);
254 bool error(const char *format, ...)
257 va_start(arg_ptr, format);
258 std::string str = vstrprintf(format, arg_ptr);
260 printf("ERROR: %s\n", str.c_str());
265 void ParseString(const string& str, char c, vector<string>& v)
269 string::size_type i1 = 0;
270 string::size_type i2;
273 i2 = str.find(c, i1);
276 v.push_back(str.substr(i1));
279 v.push_back(str.substr(i1, i2-i1));
285 string FormatMoney(int64_t n, bool fPlus)
287 // Note: not using straight sprintf here because we do NOT want
288 // localized number formatting.
289 int64_t n_abs = (n > 0 ? n : -n);
290 int64_t quotient = n_abs/COIN;
291 int64_t remainder = n_abs%COIN;
292 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
294 // Right-trim excess zeros before the decimal point:
296 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
299 str.erase(str.size()-nTrim, nTrim);
302 str.insert(0u, 1, '-');
303 else if (fPlus && n > 0)
304 str.insert(0u, 1, '+');
309 bool ParseMoney(const string& str, int64_t& nRet)
311 return ParseMoney(str.c_str(), nRet);
314 bool ParseMoney(const char* pszIn, int64_t& nRet)
318 const char* p = pszIn;
326 int64_t nMult = CENT*10;
327 while (isdigit(*p) && (nMult > 0))
329 nUnits += nMult * (*p++ - '0');
338 strWhole.insert(strWhole.end(), *p);
343 if (strWhole.size() > 10) // guard against 63 bit overflow
345 if (nUnits < 0 || nUnits > COIN)
347 int64_t nWhole = atoi64(strWhole);
348 int64_t nValue = nWhole*COIN + nUnits;
355 static const signed char phexdigit[256] =
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 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
359 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
360 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
361 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
362 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,
371 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
373 bool IsHex(const string& str)
375 for (unsigned char c : str)
377 if (phexdigit[c] < 0)
380 return (str.size() > 0) && (str.size()%2 == 0);
383 vector<unsigned char> ParseHex(const char* psz)
385 // convert hex dump to vector
386 vector<unsigned char> vch;
389 while (isspace(*psz))
391 signed char c = phexdigit[(unsigned char)*psz++];
392 if (c == (signed char)-1)
394 unsigned char n = (c << 4);
395 c = phexdigit[(unsigned char)*psz++];
396 if (c == (signed char)-1)
404 vector<unsigned char> ParseHex(const string& str)
406 return ParseHex(str.c_str());
409 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
411 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
412 if (name.find("-no") == 0)
414 std::string positive("-");
415 positive.append(name.begin()+3, name.end());
416 if (mapSettingsRet.count(positive) == 0)
418 bool value = !GetBoolArg(name);
419 mapSettingsRet[positive] = (value ? "1" : "0");
424 void ParseParameters(int argc, const char* const argv[])
427 mapMultiArgs.clear();
428 for (int i = 1; i < argc; i++)
430 std::string str(argv[i]);
431 std::string strValue;
432 size_t is_index = str.find('=');
433 if (is_index != std::string::npos)
435 strValue = str.substr(is_index+1);
436 str = str.substr(0, is_index);
439 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
440 if (str.compare(0,1, "/") == 0)
441 str = "-" + str.substr(1);
446 mapArgs[str] = strValue;
447 mapMultiArgs[str].push_back(strValue);
451 for (const auto& entry : mapArgs)
453 string name = entry.first;
455 // interpret --foo as -foo (as long as both are not set)
456 if (name.find("--") == 0)
458 std::string singleDash(name.begin()+1, name.end());
459 if (mapArgs.count(singleDash) == 0)
460 mapArgs[singleDash] = entry.second;
464 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
465 InterpretNegativeSetting(name, mapArgs);
469 std::string GetArg(const std::string& strArg, const std::string& strDefault)
471 if (mapArgs.count(strArg))
472 return mapArgs[strArg];
476 int64_t GetArg(const std::string& strArg, int64_t nDefault)
478 if (mapArgs.count(strArg))
479 return atoi64(mapArgs[strArg]);
483 int32_t GetArgInt(const std::string& strArg, int32_t nDefault)
485 if (mapArgs.count(strArg))
486 return strtol(mapArgs[strArg]);
490 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault)
492 if (mapArgs.count(strArg))
493 return strtoul(mapArgs[strArg]);
497 bool GetBoolArg(const std::string& strArg, bool fDefault)
499 if (mapArgs.count(strArg))
501 if (mapArgs[strArg].empty())
503 return (atoi(mapArgs[strArg]) != 0);
508 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
510 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
512 mapArgs[strArg] = strValue;
513 mapMultiArgs[strArg].push_back(strValue);
518 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
521 return SoftSetArg(strArg, std::string("1"));
523 return SoftSetArg(strArg, std::string("0"));
527 string EncodeBase64(const unsigned char* pch, size_t len)
529 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
532 strRet.reserve((len+2)/3*4);
535 const unsigned char *pchEnd = pch+len;
542 case 0: // we have no bits
543 strRet += pbase64[enc >> 2];
544 left = (enc & 3) << 4;
548 case 1: // we have two bits
549 strRet += pbase64[left | (enc >> 4)];
550 left = (enc & 15) << 2;
554 case 2: // we have four bits
555 strRet += pbase64[left | (enc >> 6)];
556 strRet += pbase64[enc & 63];
564 strRet += pbase64[left];
573 string EncodeBase64(const string& str)
575 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
578 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
580 static const int decode64_table[256] =
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
584 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
585 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
586 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
587 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
588 49, 50, 51, -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, -1, -1, -1, -1,
594 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
600 vector<unsigned char> vchRet;
601 vchRet.reserve(strlen(p)*3/4);
608 int dec = decode64_table[(unsigned char)*p];
609 if (dec == -1) break;
613 case 0: // we have no bits and get 6
618 case 1: // we have 6 bits and keep 4
619 vchRet.push_back((left<<2) | (dec>>4));
624 case 2: // we have 4 bits and get 6, we keep 2
625 vchRet.push_back((left<<4) | (dec>>2));
630 case 3: // we have 2 bits and get 6
631 vchRet.push_back((left<<6) | dec);
640 case 0: // 4n base64 characters processed: ok
643 case 1: // 4n+1 base64 character processed: impossible
647 case 2: // 4n+2 base64 characters processed: require '=='
648 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
652 case 3: // 4n+3 base64 characters processed: require '='
653 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
661 string DecodeBase64(const string& str)
663 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
664 return string((const char*)&vchRet[0], vchRet.size());
667 string EncodeBase32(const unsigned char* pch, size_t len)
669 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
672 strRet.reserve((len+4)/5*8);
675 const unsigned char *pchEnd = pch+len;
682 case 0: // we have no bits
683 strRet += pbase32[enc >> 3];
684 left = (enc & 7) << 2;
688 case 1: // we have three bits
689 strRet += pbase32[left | (enc >> 6)];
690 strRet += pbase32[(enc >> 1) & 31];
691 left = (enc & 1) << 4;
695 case 2: // we have one bit
696 strRet += pbase32[left | (enc >> 4)];
697 left = (enc & 15) << 1;
701 case 3: // we have four bits
702 strRet += pbase32[left | (enc >> 7)];
703 strRet += pbase32[(enc >> 2) & 31];
704 left = (enc & 3) << 3;
708 case 4: // we have two bits
709 strRet += pbase32[left | (enc >> 5)];
710 strRet += pbase32[enc & 31];
715 static const int nPadding[5] = {0, 6, 4, 3, 1};
718 strRet += pbase32[left];
719 for (int n=0; n<nPadding[mode]; n++)
726 string EncodeBase32(const string& str)
728 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
731 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
733 static const int decode32_table[256] =
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
737 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
738 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
739 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
740 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
741 23, 24, 25, -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, -1, -1, -1, -1,
747 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
753 vector<unsigned char> vchRet;
754 vchRet.reserve((strlen(p))*5/8);
761 int dec = decode32_table[(unsigned char)*p];
762 if (dec == -1) break;
766 case 0: // we have no bits and get 5
771 case 1: // we have 5 bits and keep 2
772 vchRet.push_back((left<<3) | (dec>>2));
777 case 2: // we have 2 bits and keep 7
778 left = left << 5 | dec;
782 case 3: // we have 7 bits and keep 4
783 vchRet.push_back((left<<1) | (dec>>4));
788 case 4: // we have 4 bits, and keep 1
789 vchRet.push_back((left<<4) | (dec>>1));
794 case 5: // we have 1 bit, and keep 6
795 left = left << 5 | dec;
799 case 6: // we have 6 bits, and keep 3
800 vchRet.push_back((left<<2) | (dec>>3));
805 case 7: // we have 3 bits, and keep 0
806 vchRet.push_back((left<<5) | dec);
815 case 0: // 8n base32 characters processed: ok
818 case 1: // 8n+1 base32 characters processed: impossible
824 case 2: // 8n+2 base32 characters processed: require '======'
825 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
829 case 4: // 8n+4 base32 characters processed: require '===='
830 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
834 case 5: // 8n+5 base32 characters processed: require '==='
835 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
839 case 7: // 8n+7 base32 characters processed: require '='
840 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
848 string DecodeBase32(const string& str)
850 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
851 return string((const char*)&vchRet[0], vchRet.size());
855 int64_t DecodeDumpTime(const std::string& s)
859 for(size_t i=0; i<formats_n; ++i)
861 std::istringstream is(s);
862 is.imbue(formats[i]);
864 if(pt != bt::ptime()) break;
867 return pt_to_time_t(pt);
870 std::string EncodeDumpTime(int64_t nTime) {
871 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
874 std::string EncodeDumpString(const std::string &str) {
875 std::stringstream ret;
876 for (unsigned char c : str) {
877 if (c <= 32 || c >= 128 || c == '%') {
878 ret << '%' << HexStr(&c, &c + 1);
886 std::string DecodeDumpString(const std::string &str) {
887 std::stringstream ret;
888 for (unsigned int pos = 0; pos < str.length(); pos++) {
889 unsigned char c = str[pos];
890 if (c == '%' && pos+2 < str.length()) {
891 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
892 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
900 bool WildcardMatch(const char* psz, const char* mask)
907 return (*psz == '\0');
909 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
924 bool WildcardMatch(const string& str, const string& mask)
926 return WildcardMatch(str.c_str(), mask.c_str());
936 static std::string FormatException(std::exception* pex, const char* pszThread)
939 char pszModule[MAX_PATH] = "";
940 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
942 const char* pszModule = "novacoin";
946 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
949 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
952 void LogException(std::exception* pex, const char* pszThread)
954 std::string message = FormatException(pex, pszThread);
955 printf("\n%s", message.c_str());
958 void PrintException(std::exception* pex, const char* pszThread)
960 std::string message = FormatException(pex, pszThread);
961 printf("\n\n************************\n%s\n", message.c_str());
962 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
963 strMiscWarning = message;
967 void LogStackTrace() {
968 printf("\n\n******* exception encountered *******\n");
971 #if !defined(WIN32) && !defined(ANDROID)
974 size = backtrace(pszBuffer, 32);
975 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
980 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
982 std::string message = FormatException(pex, pszThread);
983 printf("\n\n************************\n%s\n", message.c_str());
984 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
985 strMiscWarning = message;
988 boost::filesystem::path GetDefaultDataDir()
990 namespace fs = boost::filesystem;
991 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
992 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
993 // Mac: ~/Library/Application Support/NovaCoin
997 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1000 char* pszHome = getenv("HOME");
1001 if (pszHome == NULL || strlen(pszHome) == 0)
1002 pathRet = fs::path("/");
1004 pathRet = fs::path(pszHome);
1007 pathRet /= "Library/Application Support";
1008 fs::create_directory(pathRet);
1009 return pathRet / "NovaCoin";
1012 return pathRet / ".novacoin";
1017 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1019 namespace fs = boost::filesystem;
1021 static fs::path pathCached[2];
1022 static CCriticalSection csPathCached;
1023 static bool cachedPath[2] = {false, false};
1025 fs::path &path = pathCached[fNetSpecific];
1027 // This can be called during exceptions by printf, so we cache the
1028 // value so we don't have to do memory allocations after that.
1029 if (cachedPath[fNetSpecific])
1034 if (mapArgs.count("-datadir")) {
1035 path = fs::system_complete(mapArgs["-datadir"]);
1036 if (!fs::is_directory(path)) {
1041 path = GetDefaultDataDir();
1043 if (fNetSpecific && GetBoolArg("-testnet", false))
1046 fs::create_directory(path);
1048 cachedPath[fNetSpecific]=true;
1052 string randomStrGen(int length) {
1053 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1055 result.resize(length);
1056 for (int32_t i = 0; i < length; i++)
1057 result[i] = charset[rand() % charset.length()];
1064 srand(static_cast<unsigned int>(time(NULL)));
1067 #if BOOST_FILESYSTEM_VERSION >= 3
1068 pConf.open(GetConfigFile().generic_string().c_str());
1070 pConf.open(GetConfigFile().string().c_str());
1072 pConf << "rpcuser=user\nrpcpassword="
1075 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1077 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1079 + "\nrpcallowip=127.0.0.1";
1083 boost::filesystem::path GetConfigFile()
1085 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1086 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1087 return pathConfigFile;
1090 void ReadConfigFile(map<string, string>& mapSettingsRet,
1091 map<string, vector<string> >& mapMultiSettingsRet)
1093 boost::filesystem::ifstream streamConfig(GetConfigFile());
1094 if (!streamConfig.good())
1097 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1098 if(!streamConfig.good())
1102 set<string> setOptions;
1103 setOptions.insert("*");
1105 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1107 // Don't overwrite existing settings so command line settings override bitcoin.conf
1108 string strKey = string("-") + it->string_key;
1109 if (mapSettingsRet.count(strKey) == 0)
1111 mapSettingsRet[strKey] = it->value[0];
1112 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1113 InterpretNegativeSetting(strKey, mapSettingsRet);
1115 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1119 boost::filesystem::path GetPidFile()
1121 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1122 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1127 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1129 FILE* file = fopen(path.string().c_str(), "w");
1132 fprintf(file, "%d\n", pid);
1138 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1141 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1142 MOVEFILE_REPLACE_EXISTING) != 0;
1144 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1149 void FileCommit(FILE *fileout)
1151 fflush(fileout); // harmless if redundantly called
1153 _commit(_fileno(fileout));
1155 fsync(fileno(fileout));
1159 int GetFilesize(FILE* file)
1161 int nSavePos = ftell(file);
1163 if (fseek(file, 0, SEEK_END) == 0)
1164 nFilesize = ftell(file);
1165 fseek(file, nSavePos, SEEK_SET);
1169 void ShrinkDebugFile()
1171 // Scroll debug.log if it's getting too big
1172 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1173 FILE* file = fopen(pathLog.string().c_str(), "r");
1174 if (file && GetFilesize(file) > 10 * 1000000)
1176 // Restart the file with some of the end
1178 vector<char>* vBuf = new vector <char>(200000, 0);
1179 fseek(file, -((long)(vBuf->size())), SEEK_END);
1180 size_t nBytes = fread(&vBuf->operator[](0), 1, vBuf->size(), file);
1182 file = fopen(pathLog.string().c_str(), "w");
1185 fwrite(&vBuf->operator[](0), 1, nBytes, file);
1190 catch (const bad_alloc& e) {
1191 // Bad things happen - no free memory in heap at program startup
1193 printf("Warning: %s in %s:%d\n ShrinkDebugFile failed - debug.log expands further", e.what(), __FILE__, __LINE__);
1204 int64_t now = time(NULL);
1209 string FormatVersion(int nVersion)
1211 if (nVersion%100 == 0)
1212 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1214 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1217 string FormatFullVersion()
1219 return CLIENT_BUILD;
1222 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1223 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1225 std::ostringstream ss;
1227 ss << name << ":" << FormatVersion(nClientVersion);
1228 if (!comments.empty())
1231 for (const auto& st : comments)
1234 if (st == comments.back()) break;
1244 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1246 namespace fs = boost::filesystem;
1248 char pszPath[MAX_PATH] = "";
1250 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1252 return fs::path(pszPath);
1255 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1256 return fs::path("");
1260 void runCommand(std::string strCommand)
1262 int nErr = ::system(strCommand.c_str());
1264 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1267 void RenameThread(const char* name)
1269 #if defined(PR_SET_NAME)
1270 // Only the first 15 characters are used (16 - NUL terminator)
1271 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1272 #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
1273 pthread_set_name_np(pthread_self(), name);
1274 #elif defined(__APPLE__)
1275 pthread_setname_np(name);
1277 // Prevent warnings for unused parameters...
1282 bool NewThread(void(*pfn)(void*), void* parg)
1286 boost::thread(pfn, parg); // thread detaches when out of scope
1287 } catch(boost::thread_resource_error &e) {
1288 printf("Error creating thread: %s\n", e.what());
1294 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1296 // std::locale takes ownership of the pointer
1297 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1298 std::stringstream ss;
1300 ss << boost::posix_time::from_time_t(nTime);