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"
16 #include "utilstrencodings.h"
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
23 #include <pthread_np.h>
27 // for posix_fallocate
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
34 #define _POSIX_C_SOURCE 200112L
40 #include <sys/resource.h>
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
55 #define _WIN32_WINNT 0x0501
60 #define _WIN32_IE 0x0501
62 #define WIN32_LEAN_AND_MEAN 1
67 #include <io.h> /* for _commit */
71 #ifdef HAVE_SYS_PRCTL_H
72 #include <sys/prctl.h>
75 #ifdef HAVE_MALLOPT_ARENA_MAX
79 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
80 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
81 #include <boost/program_options/detail/config_file.hpp>
82 #include <boost/thread.hpp>
83 #include <openssl/crypto.h>
84 #include <openssl/rand.h>
85 #include <openssl/conf.h>
88 const char * const BITCOIN_CONF_FILENAME
= "bitcoin.conf";
89 const char * const BITCOIN_PID_FILENAME
= "bitcoind.pid";
92 bool fPrintToConsole
= false;
93 bool fPrintToDebugLog
= true;
95 bool fLogTimestamps
= DEFAULT_LOGTIMESTAMPS
;
96 bool fLogTimeMicros
= DEFAULT_LOGTIMEMICROS
;
97 bool fLogIPs
= DEFAULT_LOGIPS
;
98 std::atomic
<bool> fReopenDebugLog(false);
99 CTranslationInterface translationInterface
;
101 /** Log categories bitfield. */
102 std::atomic
<uint32_t> logCategories(0);
104 /** Init OpenSSL library multithreading support */
105 static std::unique_ptr
<CCriticalSection
[]> ppmutexOpenSSL
;
106 void locking_callback(int mode
, int i
, const char* file
, int line
) NO_THREAD_SAFETY_ANALYSIS
108 if (mode
& CRYPTO_LOCK
) {
109 ENTER_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
111 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
115 // Singleton for wrapping OpenSSL setup/teardown.
121 // Init OpenSSL library multithreading support
122 ppmutexOpenSSL
.reset(new CCriticalSection
[CRYPTO_num_locks()]);
123 CRYPTO_set_locking_callback(locking_callback
);
125 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
126 // We don't use them so we don't require the config. However some of our libs may call functions
127 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
128 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
129 // that the config appears to have been loaded and there are no modules/engines available.
133 // Seed OpenSSL PRNG with current contents of the screen
137 // Seed OpenSSL PRNG with performance counter
142 // Securely erase the memory used by the PRNG
144 // Shutdown OpenSSL library multithreading support
145 CRYPTO_set_locking_callback(NULL
);
146 // Clear the set of locks now to maintain symmetry with the constructor.
147 ppmutexOpenSSL
.reset();
153 * LogPrintf() has been broken a couple of times now
154 * by well-meaning people adding mutexes in the most straightforward way.
155 * It breaks because it may be called by global destructors during shutdown.
156 * Since the order of destruction of static/global objects is undefined,
157 * defining a mutex as a global object doesn't work (the mutex gets
158 * destroyed, and then some later destructor calls OutputDebugStringF,
159 * maybe indirectly, and you get a core dump at shutdown trying to lock
163 static boost::once_flag debugPrintInitFlag
= BOOST_ONCE_INIT
;
166 * We use boost::call_once() to make sure mutexDebugLog and
167 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
169 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
170 * are leaked on exit. This is ugly, but will be cleaned up by
171 * the OS/libc. When the shutdown sequence is fully audited and
172 * tested, explicit destruction of these objects can be implemented.
174 static FILE* fileout
= NULL
;
175 static boost::mutex
* mutexDebugLog
= NULL
;
176 static std::list
<std::string
>* vMsgsBeforeOpenLog
;
178 static int FileWriteStr(const std::string
&str
, FILE *fp
)
180 return fwrite(str
.data(), 1, str
.size(), fp
);
183 static void DebugPrintInit()
185 assert(mutexDebugLog
== NULL
);
186 mutexDebugLog
= new boost::mutex();
187 vMsgsBeforeOpenLog
= new std::list
<std::string
>;
192 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
193 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
195 assert(fileout
== NULL
);
196 assert(vMsgsBeforeOpenLog
);
197 fs::path pathDebug
= GetDataDir() / "debug.log";
198 fileout
= fsbridge::fopen(pathDebug
, "a");
200 setbuf(fileout
, NULL
); // unbuffered
201 // dump buffered messages from before we opened the log
202 while (!vMsgsBeforeOpenLog
->empty()) {
203 FileWriteStr(vMsgsBeforeOpenLog
->front(), fileout
);
204 vMsgsBeforeOpenLog
->pop_front();
208 delete vMsgsBeforeOpenLog
;
209 vMsgsBeforeOpenLog
= NULL
;
212 struct CLogCategoryDesc
215 std::string category
;
218 const CLogCategoryDesc LogCategories
[] =
223 {BCLog::MEMPOOL
, "mempool"},
224 {BCLog::HTTP
, "http"},
225 {BCLog::BENCH
, "bench"},
229 {BCLog::ESTIMATEFEE
, "estimatefee"},
230 {BCLog::ADDRMAN
, "addrman"},
231 {BCLog::SELECTCOINS
, "selectcoins"},
232 {BCLog::REINDEX
, "reindex"},
233 {BCLog::CMPCTBLOCK
, "cmpctblock"},
234 {BCLog::RAND
, "rand"},
235 {BCLog::PRUNE
, "prune"},
236 {BCLog::PROXY
, "proxy"},
237 {BCLog::MEMPOOLREJ
, "mempoolrej"},
238 {BCLog::LIBEVENT
, "libevent"},
239 {BCLog::COINDB
, "coindb"},
241 {BCLog::LEVELDB
, "leveldb"},
246 bool GetLogCategory(uint32_t *f
, const std::string
*str
)
253 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
254 if (LogCategories
[i
].category
== *str
) {
255 *f
= LogCategories
[i
].flag
;
263 std::string
ListLogCategories()
267 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
268 // Omit the special cases.
269 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
270 if (outcount
!= 0) ret
+= ", ";
271 ret
+= LogCategories
[i
].category
;
278 std::vector
<CLogCategoryActive
> ListActiveLogCategories()
280 std::vector
<CLogCategoryActive
> ret
;
281 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
282 // Omit the special cases.
283 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
284 CLogCategoryActive catActive
;
285 catActive
.category
= LogCategories
[i
].category
;
286 catActive
.active
= LogAcceptCategory(LogCategories
[i
].flag
);
287 ret
.push_back(catActive
);
294 * fStartedNewLine is a state variable held by the calling context that will
295 * suppress printing of the timestamp when multiple calls are made that don't
296 * end in a newline. Initialize it to true, and hold it, in the calling context.
298 static std::string
LogTimestampStr(const std::string
&str
, std::atomic_bool
*fStartedNewLine
)
300 std::string strStamped
;
305 if (*fStartedNewLine
) {
306 int64_t nTimeMicros
= GetTimeMicros();
307 strStamped
= DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros
/1000000);
309 strStamped
+= strprintf(".%06d", nTimeMicros
%1000000);
310 int64_t mocktime
= GetMockTime();
312 strStamped
+= " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime
) + ")";
314 strStamped
+= ' ' + str
;
318 if (!str
.empty() && str
[str
.size()-1] == '\n')
319 *fStartedNewLine
= true;
321 *fStartedNewLine
= false;
326 int LogPrintStr(const std::string
&str
)
328 int ret
= 0; // Returns total number of characters written
329 static std::atomic_bool
fStartedNewLine(true);
331 std::string strTimestamped
= LogTimestampStr(str
, &fStartedNewLine
);
336 ret
= fwrite(strTimestamped
.data(), 1, strTimestamped
.size(), stdout
);
339 else if (fPrintToDebugLog
)
341 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
342 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
344 // buffer if we haven't opened the log yet
345 if (fileout
== NULL
) {
346 assert(vMsgsBeforeOpenLog
);
347 ret
= strTimestamped
.length();
348 vMsgsBeforeOpenLog
->push_back(strTimestamped
);
352 // reopen the log file, if requested
353 if (fReopenDebugLog
) {
354 fReopenDebugLog
= false;
355 fs::path pathDebug
= GetDataDir() / "debug.log";
356 if (fsbridge::freopen(pathDebug
,"a",fileout
) != NULL
)
357 setbuf(fileout
, NULL
); // unbuffered
360 ret
= FileWriteStr(strTimestamped
, fileout
);
366 /** Interpret string as boolean, for argument parsing */
367 static bool InterpretBool(const std::string
& strValue
)
369 if (strValue
.empty())
371 return (atoi(strValue
) != 0);
374 /** Turn -noX into -X=0 */
375 static void InterpretNegativeSetting(std::string
& strKey
, std::string
& strValue
)
377 if (strKey
.length()>3 && strKey
[0]=='-' && strKey
[1]=='n' && strKey
[2]=='o')
379 strKey
= "-" + strKey
.substr(3);
380 strValue
= InterpretBool(strValue
) ? "0" : "1";
384 void ArgsManager::ParseParameters(int argc
, const char* const argv
[])
388 mapMultiArgs
.clear();
390 for (int i
= 1; i
< argc
; i
++)
392 std::string
str(argv
[i
]);
393 std::string strValue
;
394 size_t is_index
= str
.find('=');
395 if (is_index
!= std::string::npos
)
397 strValue
= str
.substr(is_index
+1);
398 str
= str
.substr(0, is_index
);
401 boost::to_lower(str
);
402 if (boost::algorithm::starts_with(str
, "/"))
403 str
= "-" + str
.substr(1);
409 // Interpret --foo as -foo.
410 // If both --foo and -foo are set, the last takes effect.
411 if (str
.length() > 1 && str
[1] == '-')
413 InterpretNegativeSetting(str
, strValue
);
415 mapArgs
[str
] = strValue
;
416 mapMultiArgs
[str
].push_back(strValue
);
420 std::vector
<std::string
> ArgsManager::GetArgs(const std::string
& strArg
)
423 return mapMultiArgs
.at(strArg
);
426 bool ArgsManager::IsArgSet(const std::string
& strArg
)
429 return mapArgs
.count(strArg
);
432 std::string
ArgsManager::GetArg(const std::string
& strArg
, const std::string
& strDefault
)
435 if (mapArgs
.count(strArg
))
436 return mapArgs
[strArg
];
440 int64_t ArgsManager::GetArg(const std::string
& strArg
, int64_t nDefault
)
443 if (mapArgs
.count(strArg
))
444 return atoi64(mapArgs
[strArg
]);
448 bool ArgsManager::GetBoolArg(const std::string
& strArg
, bool fDefault
)
451 if (mapArgs
.count(strArg
))
452 return InterpretBool(mapArgs
[strArg
]);
456 bool ArgsManager::SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
459 if (mapArgs
.count(strArg
))
461 ForceSetArg(strArg
, strValue
);
465 bool ArgsManager::SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
468 return SoftSetArg(strArg
, std::string("1"));
470 return SoftSetArg(strArg
, std::string("0"));
473 void ArgsManager::ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
476 mapArgs
[strArg
] = strValue
;
477 mapMultiArgs
[strArg
].push_back(strValue
);
482 static const int screenWidth
= 79;
483 static const int optIndent
= 2;
484 static const int msgIndent
= 7;
486 std::string
HelpMessageGroup(const std::string
&message
) {
487 return std::string(message
) + std::string("\n\n");
490 std::string
HelpMessageOpt(const std::string
&option
, const std::string
&message
) {
491 return std::string(optIndent
,' ') + std::string(option
) +
492 std::string("\n") + std::string(msgIndent
,' ') +
493 FormatParagraph(message
, screenWidth
- msgIndent
, msgIndent
) +
497 static std::string
FormatException(const std::exception
* pex
, const char* pszThread
)
500 char pszModule
[MAX_PATH
] = "";
501 GetModuleFileNameA(NULL
, pszModule
, sizeof(pszModule
));
503 const char* pszModule
= "bitcoin";
507 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex
).name(), pex
->what(), pszModule
, pszThread
);
510 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule
, pszThread
);
513 void PrintExceptionContinue(const std::exception
* pex
, const char* pszThread
)
515 std::string message
= FormatException(pex
, pszThread
);
516 LogPrintf("\n\n************************\n%s\n", message
);
517 fprintf(stderr
, "\n\n************************\n%s\n", message
.c_str());
520 fs::path
GetDefaultDataDir()
522 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
523 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
524 // Mac: ~/Library/Application Support/Bitcoin
528 return GetSpecialFolderPath(CSIDL_APPDATA
) / "Bitcoin";
531 char* pszHome
= getenv("HOME");
532 if (pszHome
== NULL
|| strlen(pszHome
) == 0)
533 pathRet
= fs::path("/");
535 pathRet
= fs::path(pszHome
);
538 return pathRet
/ "Library/Application Support/Bitcoin";
541 return pathRet
/ ".bitcoin";
546 static fs::path pathCached
;
547 static fs::path pathCachedNetSpecific
;
548 static CCriticalSection csPathCached
;
550 const fs::path
&GetDataDir(bool fNetSpecific
)
555 fs::path
&path
= fNetSpecific
? pathCachedNetSpecific
: pathCached
;
557 // This can be called during exceptions by LogPrintf(), so we cache the
558 // value so we don't have to do memory allocations after that.
562 if (IsArgSet("-datadir")) {
563 path
= fs::system_complete(GetArg("-datadir", ""));
564 if (!fs::is_directory(path
)) {
569 path
= GetDefaultDataDir();
572 path
/= BaseParams().DataDir();
574 fs::create_directories(path
);
579 void ClearDatadirCache()
583 pathCached
= fs::path();
584 pathCachedNetSpecific
= fs::path();
587 fs::path
GetConfigFile(const std::string
& confPath
)
589 fs::path
pathConfigFile(confPath
);
590 if (!pathConfigFile
.is_complete())
591 pathConfigFile
= GetDataDir(false) / pathConfigFile
;
593 return pathConfigFile
;
596 void ArgsManager::ReadConfigFile(const std::string
& confPath
)
598 fs::ifstream
streamConfig(GetConfigFile(confPath
));
599 if (!streamConfig
.good())
600 return; // No bitcoin.conf file is OK
604 std::set
<std::string
> setOptions
;
605 setOptions
.insert("*");
607 for (boost::program_options::detail::config_file_iterator
it(streamConfig
, setOptions
), end
; it
!= end
; ++it
)
609 // Don't overwrite existing settings so command line settings override bitcoin.conf
610 std::string strKey
= std::string("-") + it
->string_key
;
611 std::string strValue
= it
->value
[0];
612 InterpretNegativeSetting(strKey
, strValue
);
613 if (mapArgs
.count(strKey
) == 0)
614 mapArgs
[strKey
] = strValue
;
615 mapMultiArgs
[strKey
].push_back(strValue
);
618 // If datadir is changed in .conf file:
623 fs::path
GetPidFile()
625 fs::path
pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME
));
626 if (!pathPidFile
.is_complete()) pathPidFile
= GetDataDir() / pathPidFile
;
630 void CreatePidFile(const fs::path
&path
, pid_t pid
)
632 FILE* file
= fsbridge::fopen(path
, "w");
635 fprintf(file
, "%d\n", pid
);
641 bool RenameOver(fs::path src
, fs::path dest
)
644 return MoveFileExA(src
.string().c_str(), dest
.string().c_str(),
645 MOVEFILE_REPLACE_EXISTING
) != 0;
647 int rc
= std::rename(src
.string().c_str(), dest
.string().c_str());
653 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
654 * Specifically handles case where path p exists, but it wasn't possible for the user to
655 * write to the parent directory.
657 bool TryCreateDirectory(const fs::path
& p
)
661 return fs::create_directory(p
);
662 } catch (const fs::filesystem_error
&) {
663 if (!fs::exists(p
) || !fs::is_directory(p
))
667 // create_directory didn't create the directory, it had to have existed already
671 void FileCommit(FILE *file
)
673 fflush(file
); // harmless if redundantly called
675 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
676 FlushFileBuffers(hFile
);
678 #if defined(__linux__) || defined(__NetBSD__)
679 fdatasync(fileno(file
));
680 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
681 fcntl(fileno(file
), F_FULLFSYNC
, 0);
688 bool TruncateFile(FILE *file
, unsigned int length
) {
690 return _chsize(_fileno(file
), length
) == 0;
692 return ftruncate(fileno(file
), length
) == 0;
697 * this function tries to raise the file descriptor limit to the requested number.
698 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
700 int RaiseFileDescriptorLimit(int nMinFD
) {
704 struct rlimit limitFD
;
705 if (getrlimit(RLIMIT_NOFILE
, &limitFD
) != -1) {
706 if (limitFD
.rlim_cur
< (rlim_t
)nMinFD
) {
707 limitFD
.rlim_cur
= nMinFD
;
708 if (limitFD
.rlim_cur
> limitFD
.rlim_max
)
709 limitFD
.rlim_cur
= limitFD
.rlim_max
;
710 setrlimit(RLIMIT_NOFILE
, &limitFD
);
711 getrlimit(RLIMIT_NOFILE
, &limitFD
);
713 return limitFD
.rlim_cur
;
715 return nMinFD
; // getrlimit failed, assume it's fine
720 * this function tries to make a particular range of a file allocated (corresponding to disk space)
721 * it is advisory, and the range specified in the arguments will never contain live data
723 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
) {
725 // Windows-specific version
726 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
727 LARGE_INTEGER nFileSize
;
728 int64_t nEndPos
= (int64_t)offset
+ length
;
729 nFileSize
.u
.LowPart
= nEndPos
& 0xFFFFFFFF;
730 nFileSize
.u
.HighPart
= nEndPos
>> 32;
731 SetFilePointerEx(hFile
, nFileSize
, 0, FILE_BEGIN
);
733 #elif defined(MAC_OSX)
734 // OSX specific version
736 fst
.fst_flags
= F_ALLOCATECONTIG
;
737 fst
.fst_posmode
= F_PEOFPOSMODE
;
739 fst
.fst_length
= (off_t
)offset
+ length
;
740 fst
.fst_bytesalloc
= 0;
741 if (fcntl(fileno(file
), F_PREALLOCATE
, &fst
) == -1) {
742 fst
.fst_flags
= F_ALLOCATEALL
;
743 fcntl(fileno(file
), F_PREALLOCATE
, &fst
);
745 ftruncate(fileno(file
), fst
.fst_length
);
746 #elif defined(__linux__)
747 // Version using posix_fallocate
748 off_t nEndPos
= (off_t
)offset
+ length
;
749 posix_fallocate(fileno(file
), 0, nEndPos
);
752 // TODO: just write one byte per block
753 static const char buf
[65536] = {};
754 fseek(file
, offset
, SEEK_SET
);
756 unsigned int now
= 65536;
759 fwrite(buf
, 1, now
, file
); // allowed to fail; this function is advisory anyway
765 void ShrinkDebugFile()
767 // Amount of debug.log to save at end when shrinking (must fit in memory)
768 constexpr size_t RECENT_DEBUG_HISTORY_SIZE
= 10 * 1000000;
769 // Scroll debug.log if it's getting too big
770 fs::path pathLog
= GetDataDir() / "debug.log";
771 FILE* file
= fsbridge::fopen(pathLog
, "r");
772 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
773 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
774 if (file
&& fs::file_size(pathLog
) > 11 * (RECENT_DEBUG_HISTORY_SIZE
/ 10))
776 // Restart the file with some of the end
777 std::vector
<char> vch(RECENT_DEBUG_HISTORY_SIZE
, 0);
778 fseek(file
, -((long)vch
.size()), SEEK_END
);
779 int nBytes
= fread(vch
.data(), 1, vch
.size(), file
);
782 file
= fsbridge::fopen(pathLog
, "w");
785 fwrite(vch
.data(), 1, nBytes
, file
);
789 else if (file
!= NULL
)
794 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
)
796 char pszPath
[MAX_PATH
] = "";
798 if(SHGetSpecialFolderPathA(NULL
, pszPath
, nFolder
, fCreate
))
800 return fs::path(pszPath
);
803 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
808 void runCommand(const std::string
& strCommand
)
810 int nErr
= ::system(strCommand
.c_str());
812 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand
, nErr
);
815 void RenameThread(const char* name
)
817 #if defined(PR_SET_NAME)
818 // Only the first 15 characters are used (16 - NUL terminator)
819 ::prctl(PR_SET_NAME
, name
, 0, 0, 0);
820 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
821 pthread_set_name_np(pthread_self(), name
);
823 #elif defined(MAC_OSX)
824 pthread_setname_np(name
);
826 // Prevent warnings for unused parameters...
831 void SetupEnvironment()
833 #ifdef HAVE_MALLOPT_ARENA_MAX
834 // glibc-specific: On 32-bit systems set the number of arenas to 1.
835 // By default, since glibc 2.10, the C library will create up to two heap
836 // arenas per core. This is known to cause excessive virtual address space
837 // usage in our usage. Work around it by setting the maximum number of
839 if (sizeof(void*) == 4) {
840 mallopt(M_ARENA_MAX
, 1);
843 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
844 // may be invalid, in which case the "C" locale is used as fallback.
845 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
847 std::locale(""); // Raises a runtime error if current locale is invalid
848 } catch (const std::runtime_error
&) {
849 setenv("LC_ALL", "C", 1);
852 // The path locale is lazy initialized and to avoid deinitialization errors
853 // in multithreading environments, it is set explicitly by the main thread.
854 // A dummy locale is used to extract the internal default locale, used by
855 // fs::path, which is then used to explicitly imbue the path.
856 std::locale loc
= fs::path::imbue(std::locale::classic());
857 fs::path::imbue(loc
);
860 bool SetupNetworking()
863 // Initialize Windows Sockets
865 int ret
= WSAStartup(MAKEWORD(2,2), &wsadata
);
866 if (ret
!= NO_ERROR
|| LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 2)
874 #if BOOST_VERSION >= 105600
875 return boost::thread::physical_concurrency();
876 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
877 return boost::thread::hardware_concurrency();
881 std::string
CopyrightHolders(const std::string
& strPrefix
)
883 std::string strCopyrightHolders
= strPrefix
+ strprintf(_(COPYRIGHT_HOLDERS
), _(COPYRIGHT_HOLDERS_SUBSTITUTION
));
885 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
886 if (strprintf(COPYRIGHT_HOLDERS
, COPYRIGHT_HOLDERS_SUBSTITUTION
).find("Bitcoin Core") == std::string::npos
) {
887 strCopyrightHolders
+= "\n" + strPrefix
+ "The Bitcoin Core developers";
889 return strCopyrightHolders
;