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.
9 #define _POSIX_C_SOURCE 200112L
13 #include <sys/resource.h>
16 #include "chainparams.h"
20 #include "ui_interface.h"
21 #include <boost/algorithm/string/join.hpp>
22 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
23 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
25 // Work around clang compilation problem in Boost 1.46:
26 // /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
27 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
28 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
30 namespace program_options {
31 std::string to_internal(const std::string&);
35 #include <boost/program_options/detail/config_file.hpp>
36 #include <boost/program_options/parsers.hpp>
37 #include <boost/filesystem.hpp>
38 #include <boost/filesystem/fstream.hpp>
39 #include <boost/foreach.hpp>
40 #include <boost/thread.hpp>
41 #include <openssl/crypto.h>
42 #include <openssl/rand.h>
47 #pragma warning(disable:4786)
48 #pragma warning(disable:4804)
49 #pragma warning(disable:4805)
50 #pragma warning(disable:4717)
55 #define _WIN32_WINNT 0x0501
59 #define _WIN32_IE 0x0501
60 #define WIN32_LEAN_AND_MEAN 1
64 #include <io.h> /* for _commit */
66 #elif defined(__linux__)
67 # include <sys/prctl.h>
72 map<string, string> mapArgs;
73 map<string, vector<string> > mapMultiArgs;
75 bool fDebugNet = false;
76 bool fPrintToConsole = false;
77 bool fPrintToDebugger = false;
80 bool fCommandLine = false;
81 string strMiscWarning;
82 bool fNoListen = false;
83 bool fLogTimestamps = false;
84 CMedianFilter<int64> vTimeOffsets(200,0);
85 volatile bool fReopenDebugLog = false;
86 bool fCachedPath[2] = {false, false};
88 // Init OpenSSL library multithreading support
89 static CCriticalSection** ppmutexOpenSSL;
90 void locking_callback(int mode, int i, const char* file, int line)
92 if (mode & CRYPTO_LOCK) {
93 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
95 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
99 LockedPageManager LockedPageManager::instance;
107 // Init OpenSSL library multithreading support
108 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
109 for (int i = 0; i < CRYPTO_num_locks(); i++)
110 ppmutexOpenSSL[i] = new CCriticalSection();
111 CRYPTO_set_locking_callback(locking_callback);
114 // Seed random number generator with screen scrape and other hardware sources
118 // Seed random number generator with performance counter
123 // Shutdown OpenSSL library multithreading support
124 CRYPTO_set_locking_callback(NULL);
125 for (int i = 0; i < CRYPTO_num_locks(); i++)
126 delete ppmutexOpenSSL[i];
127 OPENSSL_free(ppmutexOpenSSL);
141 // Seed with CPU performance counter
142 int64 nCounter = GetPerformanceCounter();
143 RAND_add(&nCounter, sizeof(nCounter), 1.5);
144 memset(&nCounter, 0, sizeof(nCounter));
147 void RandAddSeedPerfmon()
151 // This can take up to 2 seconds, so only do it every 10 minutes
152 static int64 nLastPerfmon;
153 if (GetTime() < nLastPerfmon + 10 * 60)
155 nLastPerfmon = GetTime();
158 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
159 // Seed with the entire set of perfmon data
160 unsigned char pdata[250000];
161 memset(pdata, 0, sizeof(pdata));
162 unsigned long nSize = sizeof(pdata);
163 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
164 RegCloseKey(HKEY_PERFORMANCE_DATA);
165 if (ret == ERROR_SUCCESS)
167 RAND_add(pdata, nSize, nSize/100.0);
168 OPENSSL_cleanse(pdata, nSize);
169 printf("RandAddSeed() %lu bytes\n", nSize);
174 uint64 GetRand(uint64 nMax)
179 // The range of the random source must be a multiple of the modulus
180 // to give every possible output value an equal possibility
181 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
184 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
185 while (nRand >= nRange);
186 return (nRand % nMax);
189 int GetRandInt(int nMax)
191 return GetRand(nMax);
194 uint256 GetRandHash()
197 RAND_bytes((unsigned char*)&hash, sizeof(hash));
208 // OutputDebugStringF (aka printf -- there is a #define that we really
209 // should get rid of one day) has been broken a couple of times now
210 // by well-meaning people adding mutexes in the most straightforward way.
211 // It breaks because it may be called by global destructors during shutdown.
212 // Since the order of destruction of static/global objects is undefined,
213 // defining a mutex as a global object doesn't work (the mutex gets
214 // destroyed, and then some later destructor calls OutputDebugStringF,
215 // maybe indirectly, and you get a core dump at shutdown trying to lock
218 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
219 // We use boost::call_once() to make sure these are initialized in
220 // in a thread-safe manner the first time it is called:
221 static FILE* fileout = NULL;
222 static boost::mutex* mutexDebugLog = NULL;
224 static void DebugPrintInit()
226 assert(fileout == NULL);
227 assert(mutexDebugLog == NULL);
229 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
230 fileout = fopen(pathDebug.string().c_str(), "a");
231 if (fileout) setbuf(fileout, NULL); // unbuffered
233 mutexDebugLog = new boost::mutex();
236 int OutputDebugStringF(const char* pszFormat, ...)
238 int ret = 0; // Returns total number of characters written
243 va_start(arg_ptr, pszFormat);
244 ret += vprintf(pszFormat, arg_ptr);
247 else if (!fPrintToDebugger)
249 static bool fStartedNewLine = true;
250 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
255 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
257 // reopen the log file, if requested
258 if (fReopenDebugLog) {
259 fReopenDebugLog = false;
260 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
261 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
262 setbuf(fileout, NULL); // unbuffered
265 // Debug print useful for profiling
266 if (fLogTimestamps && fStartedNewLine)
267 ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
268 if (pszFormat[strlen(pszFormat) - 1] == '\n')
269 fStartedNewLine = true;
271 fStartedNewLine = false;
274 va_start(arg_ptr, pszFormat);
275 ret += vfprintf(fileout, pszFormat, arg_ptr);
280 if (fPrintToDebugger)
282 static CCriticalSection cs_OutputDebugStringF;
284 // accumulate and output a line at a time
286 LOCK(cs_OutputDebugStringF);
287 static std::string buffer;
290 va_start(arg_ptr, pszFormat);
291 buffer += vstrprintf(pszFormat, arg_ptr);
294 int line_start = 0, line_end;
295 while((line_end = buffer.find('\n', line_start)) != -1)
297 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
298 line_start = line_end + 1;
299 ret += line_end-line_start;
301 buffer.erase(0, line_start);
308 string vstrprintf(const char *format, va_list ap)
312 int limit = sizeof(buffer);
317 va_copy(arg_ptr, ap);
319 ret = _vsnprintf(p, limit, format, arg_ptr);
321 ret = vsnprintf(p, limit, format, arg_ptr);
324 if (ret >= 0 && ret < limit)
331 throw std::bad_alloc();
333 string str(p, p+ret);
339 string real_strprintf(const char *format, int dummy, ...)
342 va_start(arg_ptr, dummy);
343 string str = vstrprintf(format, arg_ptr);
348 string real_strprintf(const std::string &format, int dummy, ...)
351 va_start(arg_ptr, dummy);
352 string str = vstrprintf(format.c_str(), arg_ptr);
357 bool error(const char *format, ...)
360 va_start(arg_ptr, format);
361 std::string str = vstrprintf(format, arg_ptr);
363 printf("ERROR: %s\n", str.c_str());
368 void ParseString(const string& str, char c, vector<string>& v)
372 string::size_type i1 = 0;
373 string::size_type i2;
376 i2 = str.find(c, i1);
379 v.push_back(str.substr(i1));
382 v.push_back(str.substr(i1, i2-i1));
388 string FormatMoney(int64 n, bool fPlus)
390 // Note: not using straight sprintf here because we do NOT want
391 // localized number formatting.
392 int64 n_abs = (n > 0 ? n : -n);
393 int64 quotient = n_abs/COIN;
394 int64 remainder = n_abs%COIN;
395 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
397 // Right-trim excess zeros before the decimal point:
399 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
402 str.erase(str.size()-nTrim, nTrim);
405 str.insert((unsigned int)0, 1, '-');
406 else if (fPlus && n > 0)
407 str.insert((unsigned int)0, 1, '+');
412 bool ParseMoney(const string& str, int64& nRet)
414 return ParseMoney(str.c_str(), nRet);
417 bool ParseMoney(const char* pszIn, int64& nRet)
421 const char* p = pszIn;
429 int64 nMult = CENT*10;
430 while (isdigit(*p) && (nMult > 0))
432 nUnits += nMult * (*p++ - '0');
441 strWhole.insert(strWhole.end(), *p);
446 if (strWhole.size() > 10) // guard against 63 bit overflow
448 if (nUnits < 0 || nUnits > COIN)
450 int64 nWhole = atoi64(strWhole);
451 int64 nValue = nWhole*COIN + nUnits;
458 static const signed char phexdigit[256] =
459 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
463 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
464 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
465 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
466 -1,-1,-1,-1,-1,-1,-1,-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, };
476 bool IsHex(const string& str)
478 BOOST_FOREACH(unsigned char c, str)
480 if (phexdigit[c] < 0)
483 return (str.size() > 0) && (str.size()%2 == 0);
486 vector<unsigned char> ParseHex(const char* psz)
488 // convert hex dump to vector
489 vector<unsigned char> vch;
492 while (isspace(*psz))
494 signed char c = phexdigit[(unsigned char)*psz++];
495 if (c == (signed char)-1)
497 unsigned char n = (c << 4);
498 c = phexdigit[(unsigned char)*psz++];
499 if (c == (signed char)-1)
507 vector<unsigned char> ParseHex(const string& str)
509 return ParseHex(str.c_str());
512 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
514 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
515 if (name.find("-no") == 0)
517 std::string positive("-");
518 positive.append(name.begin()+3, name.end());
519 if (mapSettingsRet.count(positive) == 0)
521 bool value = !GetBoolArg(name, false);
522 mapSettingsRet[positive] = (value ? "1" : "0");
527 void ParseParameters(int argc, const char* const argv[])
530 mapMultiArgs.clear();
531 for (int i = 1; i < argc; i++)
533 std::string str(argv[i]);
534 std::string strValue;
535 size_t is_index = str.find('=');
536 if (is_index != std::string::npos)
538 strValue = str.substr(is_index+1);
539 str = str.substr(0, is_index);
542 boost::to_lower(str);
543 if (boost::algorithm::starts_with(str, "/"))
544 str = "-" + str.substr(1);
549 mapArgs[str] = strValue;
550 mapMultiArgs[str].push_back(strValue);
554 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
556 string name = entry.first;
558 // interpret --foo as -foo (as long as both are not set)
559 if (name.find("--") == 0)
561 std::string singleDash(name.begin()+1, name.end());
562 if (mapArgs.count(singleDash) == 0)
563 mapArgs[singleDash] = entry.second;
567 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
568 InterpretNegativeSetting(name, mapArgs);
572 std::string GetArg(const std::string& strArg, const std::string& strDefault)
574 if (mapArgs.count(strArg))
575 return mapArgs[strArg];
579 int64 GetArg(const std::string& strArg, int64 nDefault)
581 if (mapArgs.count(strArg))
582 return atoi64(mapArgs[strArg]);
586 bool GetBoolArg(const std::string& strArg, bool fDefault)
588 if (mapArgs.count(strArg))
590 if (mapArgs[strArg].empty())
592 return (atoi(mapArgs[strArg]) != 0);
597 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
599 if (mapArgs.count(strArg))
601 mapArgs[strArg] = strValue;
605 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
608 return SoftSetArg(strArg, std::string("1"));
610 return SoftSetArg(strArg, std::string("0"));
614 string EncodeBase64(const unsigned char* pch, size_t len)
616 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
619 strRet.reserve((len+2)/3*4);
622 const unsigned char *pchEnd = pch+len;
629 case 0: // we have no bits
630 strRet += pbase64[enc >> 2];
631 left = (enc & 3) << 4;
635 case 1: // we have two bits
636 strRet += pbase64[left | (enc >> 4)];
637 left = (enc & 15) << 2;
641 case 2: // we have four bits
642 strRet += pbase64[left | (enc >> 6)];
643 strRet += pbase64[enc & 63];
651 strRet += pbase64[left];
660 string EncodeBase64(const string& str)
662 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
665 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
667 static const int decode64_table[256] =
669 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
672 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
673 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
674 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
675 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
676 -1, -1, -1, -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
687 vector<unsigned char> vchRet;
688 vchRet.reserve(strlen(p)*3/4);
695 int dec = decode64_table[(unsigned char)*p];
696 if (dec == -1) break;
700 case 0: // we have no bits and get 6
705 case 1: // we have 6 bits and keep 4
706 vchRet.push_back((left<<2) | (dec>>4));
711 case 2: // we have 4 bits and get 6, we keep 2
712 vchRet.push_back((left<<4) | (dec>>2));
717 case 3: // we have 2 bits and get 6
718 vchRet.push_back((left<<6) | dec);
727 case 0: // 4n base64 characters processed: ok
730 case 1: // 4n+1 base64 character processed: impossible
734 case 2: // 4n+2 base64 characters processed: require '=='
735 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
739 case 3: // 4n+3 base64 characters processed: require '='
740 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
748 string DecodeBase64(const string& str)
750 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
751 return string((const char*)&vchRet[0], vchRet.size());
754 string EncodeBase32(const unsigned char* pch, size_t len)
756 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
759 strRet.reserve((len+4)/5*8);
762 const unsigned char *pchEnd = pch+len;
769 case 0: // we have no bits
770 strRet += pbase32[enc >> 3];
771 left = (enc & 7) << 2;
775 case 1: // we have three bits
776 strRet += pbase32[left | (enc >> 6)];
777 strRet += pbase32[(enc >> 1) & 31];
778 left = (enc & 1) << 4;
782 case 2: // we have one bit
783 strRet += pbase32[left | (enc >> 4)];
784 left = (enc & 15) << 1;
788 case 3: // we have four bits
789 strRet += pbase32[left | (enc >> 7)];
790 strRet += pbase32[(enc >> 2) & 31];
791 left = (enc & 3) << 3;
795 case 4: // we have two bits
796 strRet += pbase32[left | (enc >> 5)];
797 strRet += pbase32[enc & 31];
802 static const int nPadding[5] = {0, 6, 4, 3, 1};
805 strRet += pbase32[left];
806 for (int n=0; n<nPadding[mode]; n++)
813 string EncodeBase32(const string& str)
815 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
818 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
820 static const int decode32_table[256] =
822 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
825 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
826 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
827 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
828 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
829 -1, -1, -1, -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
840 vector<unsigned char> vchRet;
841 vchRet.reserve((strlen(p))*5/8);
848 int dec = decode32_table[(unsigned char)*p];
849 if (dec == -1) break;
853 case 0: // we have no bits and get 5
858 case 1: // we have 5 bits and keep 2
859 vchRet.push_back((left<<3) | (dec>>2));
864 case 2: // we have 2 bits and keep 7
865 left = left << 5 | dec;
869 case 3: // we have 7 bits and keep 4
870 vchRet.push_back((left<<1) | (dec>>4));
875 case 4: // we have 4 bits, and keep 1
876 vchRet.push_back((left<<4) | (dec>>1));
881 case 5: // we have 1 bit, and keep 6
882 left = left << 5 | dec;
886 case 6: // we have 6 bits, and keep 3
887 vchRet.push_back((left<<2) | (dec>>3));
892 case 7: // we have 3 bits, and keep 0
893 vchRet.push_back((left<<5) | dec);
902 case 0: // 8n base32 characters processed: ok
905 case 1: // 8n+1 base32 characters processed: impossible
911 case 2: // 8n+2 base32 characters processed: require '======'
912 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
916 case 4: // 8n+4 base32 characters processed: require '===='
917 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
921 case 5: // 8n+5 base32 characters processed: require '==='
922 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
926 case 7: // 8n+7 base32 characters processed: require '='
927 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
935 string DecodeBase32(const string& str)
937 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
938 return string((const char*)&vchRet[0], vchRet.size());
942 bool WildcardMatch(const char* psz, const char* mask)
949 return (*psz == '\0');
951 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
966 bool WildcardMatch(const string& str, const string& mask)
968 return WildcardMatch(str.c_str(), mask.c_str());
978 static std::string FormatException(std::exception* pex, const char* pszThread)
981 char pszModule[MAX_PATH] = "";
982 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
984 const char* pszModule = "bitcoin";
988 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
991 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
994 void LogException(std::exception* pex, const char* pszThread)
996 std::string message = FormatException(pex, pszThread);
997 printf("\n%s", message.c_str());
1000 void PrintException(std::exception* pex, const char* pszThread)
1002 std::string message = FormatException(pex, pszThread);
1003 printf("\n\n************************\n%s\n", message.c_str());
1004 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1005 strMiscWarning = message;
1009 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1011 std::string message = FormatException(pex, pszThread);
1012 printf("\n\n************************\n%s\n", message.c_str());
1013 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1014 strMiscWarning = message;
1017 boost::filesystem::path GetDefaultDataDir()
1019 namespace fs = boost::filesystem;
1020 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
1021 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
1022 // Mac: ~/Library/Application Support/Bitcoin
1026 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
1029 char* pszHome = getenv("HOME");
1030 if (pszHome == NULL || strlen(pszHome) == 0)
1031 pathRet = fs::path("/");
1033 pathRet = fs::path(pszHome);
1036 pathRet /= "Library/Application Support";
1037 fs::create_directory(pathRet);
1038 return pathRet / "Bitcoin";
1041 return pathRet / ".bitcoin";
1046 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1048 namespace fs = boost::filesystem;
1050 static fs::path pathCached[2];
1051 static CCriticalSection csPathCached;
1053 fs::path &path = pathCached[fNetSpecific];
1055 // This can be called during exceptions by printf, so we cache the
1056 // value so we don't have to do memory allocations after that.
1057 if (fCachedPath[fNetSpecific])
1062 if (mapArgs.count("-datadir")) {
1063 path = fs::system_complete(mapArgs["-datadir"]);
1064 if (!fs::is_directory(path)) {
1069 path = GetDefaultDataDir();
1072 path /= Params().DataDir();
1074 fs::create_directories(path);
1076 fCachedPath[fNetSpecific] = true;
1080 boost::filesystem::path GetConfigFile()
1082 boost::filesystem::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
1083 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1084 return pathConfigFile;
1087 void ReadConfigFile(map<string, string>& mapSettingsRet,
1088 map<string, vector<string> >& mapMultiSettingsRet)
1090 boost::filesystem::ifstream streamConfig(GetConfigFile());
1091 if (!streamConfig.good())
1092 return; // No bitcoin.conf file is OK
1094 // clear path cache after loading config file
1095 fCachedPath[0] = fCachedPath[1] = false;
1097 set<string> setOptions;
1098 setOptions.insert("*");
1100 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1102 // Don't overwrite existing settings so command line settings override bitcoin.conf
1103 string strKey = string("-") + it->string_key;
1104 if (mapSettingsRet.count(strKey) == 0)
1106 mapSettingsRet[strKey] = it->value[0];
1107 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1108 InterpretNegativeSetting(strKey, mapSettingsRet);
1110 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1114 boost::filesystem::path GetPidFile()
1116 boost::filesystem::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
1117 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1122 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1124 FILE* file = fopen(path.string().c_str(), "w");
1127 fprintf(file, "%d\n", pid);
1133 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1136 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1137 MOVEFILE_REPLACE_EXISTING);
1139 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1144 void FileCommit(FILE *fileout)
1146 fflush(fileout); // harmless if redundantly called
1148 _commit(_fileno(fileout));
1150 #if defined(__linux__) || defined(__NetBSD__)
1151 fdatasync(fileno(fileout));
1153 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 bool TruncateFile(FILE *file, unsigned int length) {
1170 return _chsize(_fileno(file), length) == 0;
1172 return ftruncate(fileno(file), length) == 0;
1176 // this function tries to raise the file descriptor limit to the requested number.
1177 // It returns the actual file descriptor limit (which may be more or less than nMinFD)
1178 int RaiseFileDescriptorLimit(int nMinFD) {
1182 struct rlimit limitFD;
1183 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1184 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1185 limitFD.rlim_cur = nMinFD;
1186 if (limitFD.rlim_cur > limitFD.rlim_max)
1187 limitFD.rlim_cur = limitFD.rlim_max;
1188 setrlimit(RLIMIT_NOFILE, &limitFD);
1189 getrlimit(RLIMIT_NOFILE, &limitFD);
1191 return limitFD.rlim_cur;
1193 return nMinFD; // getrlimit failed, assume it's fine
1197 // this function tries to make a particular range of a file allocated (corresponding to disk space)
1198 // it is advisory, and the range specified in the arguments will never contain live data
1199 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1201 // Windows-specific version
1202 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1203 LARGE_INTEGER nFileSize;
1204 int64 nEndPos = (int64)offset + length;
1205 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1206 nFileSize.u.HighPart = nEndPos >> 32;
1207 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1208 SetEndOfFile(hFile);
1209 #elif defined(MAC_OSX)
1210 // OSX specific version
1212 fst.fst_flags = F_ALLOCATECONTIG;
1213 fst.fst_posmode = F_PEOFPOSMODE;
1215 fst.fst_length = (off_t)offset + length;
1216 fst.fst_bytesalloc = 0;
1217 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1218 fst.fst_flags = F_ALLOCATEALL;
1219 fcntl(fileno(file), F_PREALLOCATE, &fst);
1221 ftruncate(fileno(file), fst.fst_length);
1222 #elif defined(__linux__)
1223 // Version using posix_fallocate
1224 off_t nEndPos = (off_t)offset + length;
1225 posix_fallocate(fileno(file), 0, nEndPos);
1228 // TODO: just write one byte per block
1229 static const char buf[65536] = {};
1230 fseek(file, offset, SEEK_SET);
1231 while (length > 0) {
1232 unsigned int now = 65536;
1235 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1241 void ShrinkDebugFile()
1243 // Scroll debug.log if it's getting too big
1244 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1245 FILE* file = fopen(pathLog.string().c_str(), "r");
1246 if (file && GetFilesize(file) > 10 * 1000000)
1248 // Restart the file with some of the end
1250 fseek(file, -sizeof(pch), SEEK_END);
1251 int nBytes = fread(pch, 1, sizeof(pch), file);
1254 file = fopen(pathLog.string().c_str(), "w");
1257 fwrite(pch, 1, nBytes, file);
1261 else if (file != NULL)
1273 // "Never go to sea with two chronometers; take one or three."
1274 // Our three time sources are:
1276 // - Median of other nodes clocks
1277 // - The user (asking the user to fix the system clock if the first two disagree)
1279 static int64 nMockTime = 0; // For unit testing
1283 if (nMockTime) return nMockTime;
1288 void SetMockTime(int64 nMockTimeIn)
1290 nMockTime = nMockTimeIn;
1293 static int64 nTimeOffset = 0;
1295 int64 GetTimeOffset()
1300 int64 GetAdjustedTime()
1302 return GetTime() + GetTimeOffset();
1305 void AddTimeData(const CNetAddr& ip, int64 nTime)
1307 int64 nOffsetSample = nTime - GetTime();
1309 // Ignore duplicates
1310 static set<CNetAddr> setKnown;
1311 if (!setKnown.insert(ip).second)
1315 vTimeOffsets.input(nOffsetSample);
1316 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1317 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1319 int64 nMedian = vTimeOffsets.median();
1320 std::vector<int64> vSorted = vTimeOffsets.sorted();
1321 // Only let other nodes change our time by so much
1322 if (abs64(nMedian) < 70 * 60)
1324 nTimeOffset = nMedian;
1333 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1334 bool fMatch = false;
1335 BOOST_FOREACH(int64 nOffset, vSorted)
1336 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1342 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.");
1343 strMiscWarning = strMessage;
1344 printf("*** %s\n", strMessage.c_str());
1345 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
1350 BOOST_FOREACH(int64 n, vSorted)
1351 printf("%+"PRI64d" ", n);
1354 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1358 uint32_t insecure_rand_Rz = 11;
1359 uint32_t insecure_rand_Rw = 11;
1360 void seed_insecure_rand(bool fDeterministic)
1362 //The seed values have some unlikely fixed points which we avoid.
1365 insecure_rand_Rz = insecure_rand_Rw = 11;
1369 RAND_bytes((unsigned char*)&tmp, 4);
1370 } while(tmp == 0 || tmp == 0x9068ffffU);
1371 insecure_rand_Rz = tmp;
1373 RAND_bytes((unsigned char*)&tmp, 4);
1374 } while(tmp == 0 || tmp == 0x464fffffU);
1375 insecure_rand_Rw = tmp;
1379 string FormatVersion(int nVersion)
1381 if (nVersion%100 == 0)
1382 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1384 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1387 string FormatFullVersion()
1389 return CLIENT_BUILD;
1392 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1393 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1395 std::ostringstream ss;
1397 ss << name << ":" << FormatVersion(nClientVersion);
1398 if (!comments.empty())
1399 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1405 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1407 namespace fs = boost::filesystem;
1409 char pszPath[MAX_PATH] = "";
1411 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1413 return fs::path(pszPath);
1416 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1417 return fs::path("");
1421 boost::filesystem::path GetTempPath() {
1422 #if BOOST_FILESYSTEM_VERSION == 3
1423 return boost::filesystem::temp_directory_path();
1425 // TODO: remove when we don't support filesystem v2 anymore
1426 boost::filesystem::path path;
1428 char pszPath[MAX_PATH] = "";
1430 if (GetTempPathA(MAX_PATH, pszPath))
1431 path = boost::filesystem::path(pszPath);
1433 path = boost::filesystem::path("/tmp");
1435 if (path.empty() || !boost::filesystem::is_directory(path)) {
1436 printf("GetTempPath(): failed to find temp path\n");
1437 return boost::filesystem::path("");
1443 void runCommand(std::string strCommand)
1445 int nErr = ::system(strCommand.c_str());
1447 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1450 void RenameThread(const char* name)
1452 #if defined(PR_SET_NAME)
1453 // Only the first 15 characters are used (16 - NUL terminator)
1454 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1455 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1456 // TODO: This is currently disabled because it needs to be verified to work
1457 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1459 pthread_set_name_np(pthread_self(), name);
1461 #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
1463 // pthread_setname_np is XCode 10.6-and-later
1464 #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
1465 pthread_setname_np(name);
1469 // Prevent warnings for unused parameters...