1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
12 #include "chainparamsbase.h"
15 #include "serialize.h"
17 #include "utilstrencodings.h"
22 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
24 #include <pthread_np.h>
28 // for posix_fallocate
31 #ifdef _POSIX_C_SOURCE
32 #undef _POSIX_C_SOURCE
35 #define _POSIX_C_SOURCE 200112L
41 #include <sys/resource.h>
47 #pragma warning(disable:4786)
48 #pragma warning(disable:4804)
49 #pragma warning(disable:4805)
50 #pragma warning(disable:4717)
56 #define _WIN32_WINNT 0x0501
61 #define _WIN32_IE 0x0501
63 #define WIN32_LEAN_AND_MEAN 1
68 #include <io.h> /* for _commit */
72 #ifdef HAVE_SYS_PRCTL_H
73 #include <sys/prctl.h>
76 #ifdef HAVE_MALLOPT_ARENA_MAX
80 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
81 #include <boost/algorithm/string/join.hpp>
82 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
83 #include <boost/foreach.hpp>
84 #include <boost/program_options/detail/config_file.hpp>
85 #include <boost/program_options/parsers.hpp>
86 #include <boost/thread.hpp>
87 #include <openssl/crypto.h>
88 #include <openssl/rand.h>
89 #include <openssl/conf.h>
92 const char * const BITCOIN_CONF_FILENAME
= "bitcoin.conf";
93 const char * const BITCOIN_PID_FILENAME
= "bitcoind.pid";
95 CCriticalSection cs_args
;
96 std::map
<std::string
, std::string
> mapArgs
;
97 static std::map
<std::string
, std::vector
<std::string
> > _mapMultiArgs
;
98 const std::map
<std::string
, std::vector
<std::string
> >& mapMultiArgs
= _mapMultiArgs
;
99 bool fPrintToConsole
= false;
100 bool fPrintToDebugLog
= true;
102 bool fLogTimestamps
= DEFAULT_LOGTIMESTAMPS
;
103 bool fLogTimeMicros
= DEFAULT_LOGTIMEMICROS
;
104 bool fLogIPs
= DEFAULT_LOGIPS
;
105 std::atomic
<bool> fReopenDebugLog(false);
106 CTranslationInterface translationInterface
;
108 /** Log categories bitfield. */
109 std::atomic
<uint32_t> logCategories(0);
111 /** Init OpenSSL library multithreading support */
112 static std::unique_ptr
<CCriticalSection
[]> ppmutexOpenSSL
;
113 void locking_callback(int mode
, int i
, const char* file
, int line
) NO_THREAD_SAFETY_ANALYSIS
115 if (mode
& CRYPTO_LOCK
) {
116 ENTER_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
118 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
122 // Singleton for wrapping OpenSSL setup/teardown.
128 // Init OpenSSL library multithreading support
129 ppmutexOpenSSL
.reset(new CCriticalSection
[CRYPTO_num_locks()]);
130 CRYPTO_set_locking_callback(locking_callback
);
132 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
133 // We don't use them so we don't require the config. However some of our libs may call functions
134 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
135 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
136 // that the config appears to have been loaded and there are no modules/engines available.
140 // Seed OpenSSL PRNG with current contents of the screen
144 // Seed OpenSSL PRNG with performance counter
149 // Securely erase the memory used by the PRNG
151 // Shutdown OpenSSL library multithreading support
152 CRYPTO_set_locking_callback(NULL
);
153 // Clear the set of locks now to maintain symmetry with the constructor.
154 ppmutexOpenSSL
.reset();
160 * LogPrintf() has been broken a couple of times now
161 * by well-meaning people adding mutexes in the most straightforward way.
162 * It breaks because it may be called by global destructors during shutdown.
163 * Since the order of destruction of static/global objects is undefined,
164 * defining a mutex as a global object doesn't work (the mutex gets
165 * destroyed, and then some later destructor calls OutputDebugStringF,
166 * maybe indirectly, and you get a core dump at shutdown trying to lock
170 static boost::once_flag debugPrintInitFlag
= BOOST_ONCE_INIT
;
173 * We use boost::call_once() to make sure mutexDebugLog and
174 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
176 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
177 * are leaked on exit. This is ugly, but will be cleaned up by
178 * the OS/libc. When the shutdown sequence is fully audited and
179 * tested, explicit destruction of these objects can be implemented.
181 static FILE* fileout
= NULL
;
182 static boost::mutex
* mutexDebugLog
= NULL
;
183 static std::list
<std::string
>* vMsgsBeforeOpenLog
;
185 static int FileWriteStr(const std::string
&str
, FILE *fp
)
187 return fwrite(str
.data(), 1, str
.size(), fp
);
190 static void DebugPrintInit()
192 assert(mutexDebugLog
== NULL
);
193 mutexDebugLog
= new boost::mutex();
194 vMsgsBeforeOpenLog
= new std::list
<std::string
>;
199 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
200 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
202 assert(fileout
== NULL
);
203 assert(vMsgsBeforeOpenLog
);
204 fs::path pathDebug
= GetDataDir() / "debug.log";
205 fileout
= fsbridge::fopen(pathDebug
, "a");
207 setbuf(fileout
, NULL
); // unbuffered
208 // dump buffered messages from before we opened the log
209 while (!vMsgsBeforeOpenLog
->empty()) {
210 FileWriteStr(vMsgsBeforeOpenLog
->front(), fileout
);
211 vMsgsBeforeOpenLog
->pop_front();
215 delete vMsgsBeforeOpenLog
;
216 vMsgsBeforeOpenLog
= NULL
;
219 struct CLogCategoryDesc
222 std::string category
;
225 const CLogCategoryDesc LogCategories
[] =
230 {BCLog::MEMPOOL
, "mempool"},
231 {BCLog::HTTP
, "http"},
232 {BCLog::BENCH
, "bench"},
236 {BCLog::ESTIMATEFEE
, "estimatefee"},
237 {BCLog::ADDRMAN
, "addrman"},
238 {BCLog::SELECTCOINS
, "selectcoins"},
239 {BCLog::REINDEX
, "reindex"},
240 {BCLog::CMPCTBLOCK
, "cmpctblock"},
241 {BCLog::RAND
, "rand"},
242 {BCLog::PRUNE
, "prune"},
243 {BCLog::PROXY
, "proxy"},
244 {BCLog::MEMPOOLREJ
, "mempoolrej"},
245 {BCLog::LIBEVENT
, "libevent"},
246 {BCLog::COINDB
, "coindb"},
248 {BCLog::LEVELDB
, "leveldb"},
253 bool GetLogCategory(uint32_t *f
, const std::string
*str
)
260 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
261 if (LogCategories
[i
].category
== *str
) {
262 *f
= LogCategories
[i
].flag
;
270 std::string
ListLogCategories()
274 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
275 // Omit the special cases.
276 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
277 if (outcount
!= 0) ret
+= ", ";
278 ret
+= LogCategories
[i
].category
;
285 std::vector
<CLogCategoryActive
> ListActiveLogCategories()
287 std::vector
<CLogCategoryActive
> ret
;
288 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
289 // Omit the special cases.
290 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
291 CLogCategoryActive catActive
;
292 catActive
.category
= LogCategories
[i
].category
;
293 catActive
.active
= LogAcceptCategory(LogCategories
[i
].flag
);
294 ret
.push_back(catActive
);
301 * fStartedNewLine is a state variable held by the calling context that will
302 * suppress printing of the timestamp when multiple calls are made that don't
303 * end in a newline. Initialize it to true, and hold it, in the calling context.
305 static std::string
LogTimestampStr(const std::string
&str
, std::atomic_bool
*fStartedNewLine
)
307 std::string strStamped
;
312 if (*fStartedNewLine
) {
313 int64_t nTimeMicros
= GetLogTimeMicros();
314 strStamped
= DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros
/1000000);
316 strStamped
+= strprintf(".%06d", nTimeMicros
%1000000);
317 strStamped
+= ' ' + str
;
321 if (!str
.empty() && str
[str
.size()-1] == '\n')
322 *fStartedNewLine
= true;
324 *fStartedNewLine
= false;
329 int LogPrintStr(const std::string
&str
)
331 int ret
= 0; // Returns total number of characters written
332 static std::atomic_bool
fStartedNewLine(true);
334 std::string strTimestamped
= LogTimestampStr(str
, &fStartedNewLine
);
339 ret
= fwrite(strTimestamped
.data(), 1, strTimestamped
.size(), stdout
);
342 else if (fPrintToDebugLog
)
344 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
345 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
347 // buffer if we haven't opened the log yet
348 if (fileout
== NULL
) {
349 assert(vMsgsBeforeOpenLog
);
350 ret
= strTimestamped
.length();
351 vMsgsBeforeOpenLog
->push_back(strTimestamped
);
355 // reopen the log file, if requested
356 if (fReopenDebugLog
) {
357 fReopenDebugLog
= false;
358 fs::path pathDebug
= GetDataDir() / "debug.log";
359 if (fsbridge::freopen(pathDebug
,"a",fileout
) != NULL
)
360 setbuf(fileout
, NULL
); // unbuffered
363 ret
= FileWriteStr(strTimestamped
, fileout
);
369 /** Interpret string as boolean, for argument parsing */
370 static bool InterpretBool(const std::string
& strValue
)
372 if (strValue
.empty())
374 return (atoi(strValue
) != 0);
377 /** Turn -noX into -X=0 */
378 static void InterpretNegativeSetting(std::string
& strKey
, std::string
& strValue
)
380 if (strKey
.length()>3 && strKey
[0]=='-' && strKey
[1]=='n' && strKey
[2]=='o')
382 strKey
= "-" + strKey
.substr(3);
383 strValue
= InterpretBool(strValue
) ? "0" : "1";
387 void ParseParameters(int argc
, const char* const argv
[])
391 _mapMultiArgs
.clear();
393 for (int i
= 1; i
< argc
; i
++)
395 std::string
str(argv
[i
]);
396 std::string strValue
;
397 size_t is_index
= str
.find('=');
398 if (is_index
!= std::string::npos
)
400 strValue
= str
.substr(is_index
+1);
401 str
= str
.substr(0, is_index
);
404 boost::to_lower(str
);
405 if (boost::algorithm::starts_with(str
, "/"))
406 str
= "-" + str
.substr(1);
412 // Interpret --foo as -foo.
413 // If both --foo and -foo are set, the last takes effect.
414 if (str
.length() > 1 && str
[1] == '-')
416 InterpretNegativeSetting(str
, strValue
);
418 mapArgs
[str
] = strValue
;
419 _mapMultiArgs
[str
].push_back(strValue
);
423 bool IsArgSet(const std::string
& strArg
)
426 return mapArgs
.count(strArg
);
429 std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
)
432 if (mapArgs
.count(strArg
))
433 return mapArgs
[strArg
];
437 int64_t GetArg(const std::string
& strArg
, int64_t nDefault
)
440 if (mapArgs
.count(strArg
))
441 return atoi64(mapArgs
[strArg
]);
445 bool GetBoolArg(const std::string
& strArg
, bool fDefault
)
448 if (mapArgs
.count(strArg
))
449 return InterpretBool(mapArgs
[strArg
]);
453 bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
456 if (mapArgs
.count(strArg
))
458 mapArgs
[strArg
] = strValue
;
462 bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
465 return SoftSetArg(strArg
, std::string("1"));
467 return SoftSetArg(strArg
, std::string("0"));
470 void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
473 mapArgs
[strArg
] = strValue
;
478 static const int screenWidth
= 79;
479 static const int optIndent
= 2;
480 static const int msgIndent
= 7;
482 std::string
HelpMessageGroup(const std::string
&message
) {
483 return std::string(message
) + std::string("\n\n");
486 std::string
HelpMessageOpt(const std::string
&option
, const std::string
&message
) {
487 return std::string(optIndent
,' ') + std::string(option
) +
488 std::string("\n") + std::string(msgIndent
,' ') +
489 FormatParagraph(message
, screenWidth
- msgIndent
, msgIndent
) +
493 static std::string
FormatException(const std::exception
* pex
, const char* pszThread
)
496 char pszModule
[MAX_PATH
] = "";
497 GetModuleFileNameA(NULL
, pszModule
, sizeof(pszModule
));
499 const char* pszModule
= "bitcoin";
503 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex
).name(), pex
->what(), pszModule
, pszThread
);
506 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule
, pszThread
);
509 void PrintExceptionContinue(const std::exception
* pex
, const char* pszThread
)
511 std::string message
= FormatException(pex
, pszThread
);
512 LogPrintf("\n\n************************\n%s\n", message
);
513 fprintf(stderr
, "\n\n************************\n%s\n", message
.c_str());
516 fs::path
GetDefaultDataDir()
518 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
519 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
520 // Mac: ~/Library/Application Support/Bitcoin
524 return GetSpecialFolderPath(CSIDL_APPDATA
) / "Bitcoin";
527 char* pszHome
= getenv("HOME");
528 if (pszHome
== NULL
|| strlen(pszHome
) == 0)
529 pathRet
= fs::path("/");
531 pathRet
= fs::path(pszHome
);
534 return pathRet
/ "Library/Application Support/Bitcoin";
537 return pathRet
/ ".bitcoin";
542 static fs::path pathCached
;
543 static fs::path pathCachedNetSpecific
;
544 static CCriticalSection csPathCached
;
546 const fs::path
&GetDataDir(bool fNetSpecific
)
551 fs::path
&path
= fNetSpecific
? pathCachedNetSpecific
: pathCached
;
553 // This can be called during exceptions by LogPrintf(), so we cache the
554 // value so we don't have to do memory allocations after that.
558 if (IsArgSet("-datadir")) {
559 path
= fs::system_complete(GetArg("-datadir", ""));
560 if (!fs::is_directory(path
)) {
565 path
= GetDefaultDataDir();
568 path
/= BaseParams().DataDir();
570 fs::create_directories(path
);
575 void ClearDatadirCache()
579 pathCached
= fs::path();
580 pathCachedNetSpecific
= fs::path();
583 fs::path
GetConfigFile(const std::string
& confPath
)
585 fs::path
pathConfigFile(confPath
);
586 if (!pathConfigFile
.is_complete())
587 pathConfigFile
= GetDataDir(false) / pathConfigFile
;
589 return pathConfigFile
;
592 void ReadConfigFile(const std::string
& confPath
)
594 fs::ifstream
streamConfig(GetConfigFile(confPath
));
595 if (!streamConfig
.good())
596 return; // No bitcoin.conf file is OK
600 std::set
<std::string
> setOptions
;
601 setOptions
.insert("*");
603 for (boost::program_options::detail::config_file_iterator
it(streamConfig
, setOptions
), end
; it
!= end
; ++it
)
605 // Don't overwrite existing settings so command line settings override bitcoin.conf
606 std::string strKey
= std::string("-") + it
->string_key
;
607 std::string strValue
= it
->value
[0];
608 InterpretNegativeSetting(strKey
, strValue
);
609 if (mapArgs
.count(strKey
) == 0)
610 mapArgs
[strKey
] = strValue
;
611 _mapMultiArgs
[strKey
].push_back(strValue
);
614 // If datadir is changed in .conf file:
619 fs::path
GetPidFile()
621 fs::path
pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME
));
622 if (!pathPidFile
.is_complete()) pathPidFile
= GetDataDir() / pathPidFile
;
626 void CreatePidFile(const fs::path
&path
, pid_t pid
)
628 FILE* file
= fsbridge::fopen(path
, "w");
631 fprintf(file
, "%d\n", pid
);
637 bool RenameOver(fs::path src
, fs::path dest
)
640 return MoveFileExA(src
.string().c_str(), dest
.string().c_str(),
641 MOVEFILE_REPLACE_EXISTING
) != 0;
643 int rc
= std::rename(src
.string().c_str(), dest
.string().c_str());
649 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
650 * Specifically handles case where path p exists, but it wasn't possible for the user to
651 * write to the parent directory.
653 bool TryCreateDirectory(const fs::path
& p
)
657 return fs::create_directory(p
);
658 } catch (const fs::filesystem_error
&) {
659 if (!fs::exists(p
) || !fs::is_directory(p
))
663 // create_directory didn't create the directory, it had to have existed already
667 void FileCommit(FILE *file
)
669 fflush(file
); // harmless if redundantly called
671 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
672 FlushFileBuffers(hFile
);
674 #if defined(__linux__) || defined(__NetBSD__)
675 fdatasync(fileno(file
));
676 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
677 fcntl(fileno(file
), F_FULLFSYNC
, 0);
684 bool TruncateFile(FILE *file
, unsigned int length
) {
686 return _chsize(_fileno(file
), length
) == 0;
688 return ftruncate(fileno(file
), length
) == 0;
693 * this function tries to raise the file descriptor limit to the requested number.
694 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
696 int RaiseFileDescriptorLimit(int nMinFD
) {
700 struct rlimit limitFD
;
701 if (getrlimit(RLIMIT_NOFILE
, &limitFD
) != -1) {
702 if (limitFD
.rlim_cur
< (rlim_t
)nMinFD
) {
703 limitFD
.rlim_cur
= nMinFD
;
704 if (limitFD
.rlim_cur
> limitFD
.rlim_max
)
705 limitFD
.rlim_cur
= limitFD
.rlim_max
;
706 setrlimit(RLIMIT_NOFILE
, &limitFD
);
707 getrlimit(RLIMIT_NOFILE
, &limitFD
);
709 return limitFD
.rlim_cur
;
711 return nMinFD
; // getrlimit failed, assume it's fine
716 * this function tries to make a particular range of a file allocated (corresponding to disk space)
717 * it is advisory, and the range specified in the arguments will never contain live data
719 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
) {
721 // Windows-specific version
722 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
723 LARGE_INTEGER nFileSize
;
724 int64_t nEndPos
= (int64_t)offset
+ length
;
725 nFileSize
.u
.LowPart
= nEndPos
& 0xFFFFFFFF;
726 nFileSize
.u
.HighPart
= nEndPos
>> 32;
727 SetFilePointerEx(hFile
, nFileSize
, 0, FILE_BEGIN
);
729 #elif defined(MAC_OSX)
730 // OSX specific version
732 fst
.fst_flags
= F_ALLOCATECONTIG
;
733 fst
.fst_posmode
= F_PEOFPOSMODE
;
735 fst
.fst_length
= (off_t
)offset
+ length
;
736 fst
.fst_bytesalloc
= 0;
737 if (fcntl(fileno(file
), F_PREALLOCATE
, &fst
) == -1) {
738 fst
.fst_flags
= F_ALLOCATEALL
;
739 fcntl(fileno(file
), F_PREALLOCATE
, &fst
);
741 ftruncate(fileno(file
), fst
.fst_length
);
742 #elif defined(__linux__)
743 // Version using posix_fallocate
744 off_t nEndPos
= (off_t
)offset
+ length
;
745 posix_fallocate(fileno(file
), 0, nEndPos
);
748 // TODO: just write one byte per block
749 static const char buf
[65536] = {};
750 fseek(file
, offset
, SEEK_SET
);
752 unsigned int now
= 65536;
755 fwrite(buf
, 1, now
, file
); // allowed to fail; this function is advisory anyway
761 void ShrinkDebugFile()
763 // Amount of debug.log to save at end when shrinking (must fit in memory)
764 constexpr size_t RECENT_DEBUG_HISTORY_SIZE
= 10 * 1000000;
765 // Scroll debug.log if it's getting too big
766 fs::path pathLog
= GetDataDir() / "debug.log";
767 FILE* file
= fsbridge::fopen(pathLog
, "r");
768 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
769 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
770 if (file
&& fs::file_size(pathLog
) > 11 * (RECENT_DEBUG_HISTORY_SIZE
/ 10))
772 // Restart the file with some of the end
773 std::vector
<char> vch(RECENT_DEBUG_HISTORY_SIZE
, 0);
774 fseek(file
, -((long)vch
.size()), SEEK_END
);
775 int nBytes
= fread(vch
.data(), 1, vch
.size(), file
);
778 file
= fsbridge::fopen(pathLog
, "w");
781 fwrite(vch
.data(), 1, nBytes
, file
);
785 else if (file
!= NULL
)
790 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
)
792 char pszPath
[MAX_PATH
] = "";
794 if(SHGetSpecialFolderPathA(NULL
, pszPath
, nFolder
, fCreate
))
796 return fs::path(pszPath
);
799 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
804 void runCommand(const std::string
& strCommand
)
806 int nErr
= ::system(strCommand
.c_str());
808 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand
, nErr
);
811 void RenameThread(const char* name
)
813 #if defined(PR_SET_NAME)
814 // Only the first 15 characters are used (16 - NUL terminator)
815 ::prctl(PR_SET_NAME
, name
, 0, 0, 0);
816 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
817 pthread_set_name_np(pthread_self(), name
);
819 #elif defined(MAC_OSX)
820 pthread_setname_np(name
);
822 // Prevent warnings for unused parameters...
827 void SetupEnvironment()
829 #ifdef HAVE_MALLOPT_ARENA_MAX
830 // glibc-specific: On 32-bit systems set the number of arenas to 1.
831 // By default, since glibc 2.10, the C library will create up to two heap
832 // arenas per core. This is known to cause excessive virtual address space
833 // usage in our usage. Work around it by setting the maximum number of
835 if (sizeof(void*) == 4) {
836 mallopt(M_ARENA_MAX
, 1);
839 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
840 // may be invalid, in which case the "C" locale is used as fallback.
841 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
843 std::locale(""); // Raises a runtime error if current locale is invalid
844 } catch (const std::runtime_error
&) {
845 setenv("LC_ALL", "C", 1);
848 // The path locale is lazy initialized and to avoid deinitialization errors
849 // in multithreading environments, it is set explicitly by the main thread.
850 // A dummy locale is used to extract the internal default locale, used by
851 // fs::path, which is then used to explicitly imbue the path.
852 std::locale loc
= fs::path::imbue(std::locale::classic());
853 fs::path::imbue(loc
);
856 bool SetupNetworking()
859 // Initialize Windows Sockets
861 int ret
= WSAStartup(MAKEWORD(2,2), &wsadata
);
862 if (ret
!= NO_ERROR
|| LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 2)
870 #if BOOST_VERSION >= 105600
871 return boost::thread::physical_concurrency();
872 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
873 return boost::thread::hardware_concurrency();
877 std::string
CopyrightHolders(const std::string
& strPrefix
)
879 std::string strCopyrightHolders
= strPrefix
+ strprintf(_(COPYRIGHT_HOLDERS
), _(COPYRIGHT_HOLDERS_SUBSTITUTION
));
881 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
882 if (strprintf(COPYRIGHT_HOLDERS
, COPYRIGHT_HOLDERS_SUBSTITUTION
).find("Bitcoin Core") == std::string::npos
) {
883 strCopyrightHolders
+= "\n" + strPrefix
+ "The Bitcoin Core developers";
885 return strCopyrightHolders
;