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/join.hpp>
81 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
82 #include <boost/foreach.hpp>
83 #include <boost/program_options/detail/config_file.hpp>
84 #include <boost/program_options/parsers.hpp>
85 #include <boost/thread.hpp>
86 #include <openssl/crypto.h>
87 #include <openssl/rand.h>
88 #include <openssl/conf.h>
91 const char * const BITCOIN_CONF_FILENAME
= "bitcoin.conf";
92 const char * const BITCOIN_PID_FILENAME
= "bitcoind.pid";
95 bool fPrintToConsole
= false;
96 bool fPrintToDebugLog
= true;
98 bool fLogTimestamps
= DEFAULT_LOGTIMESTAMPS
;
99 bool fLogTimeMicros
= DEFAULT_LOGTIMEMICROS
;
100 bool fLogIPs
= DEFAULT_LOGIPS
;
101 std::atomic
<bool> fReopenDebugLog(false);
102 CTranslationInterface translationInterface
;
104 /** Log categories bitfield. */
105 std::atomic
<uint32_t> logCategories(0);
107 /** Init OpenSSL library multithreading support */
108 static std::unique_ptr
<CCriticalSection
[]> ppmutexOpenSSL
;
109 void locking_callback(int mode
, int i
, const char* file
, int line
) NO_THREAD_SAFETY_ANALYSIS
111 if (mode
& CRYPTO_LOCK
) {
112 ENTER_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
114 LEAVE_CRITICAL_SECTION(ppmutexOpenSSL
[i
]);
118 // Singleton for wrapping OpenSSL setup/teardown.
124 // Init OpenSSL library multithreading support
125 ppmutexOpenSSL
.reset(new CCriticalSection
[CRYPTO_num_locks()]);
126 CRYPTO_set_locking_callback(locking_callback
);
128 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
129 // We don't use them so we don't require the config. However some of our libs may call functions
130 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
131 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
132 // that the config appears to have been loaded and there are no modules/engines available.
136 // Seed OpenSSL PRNG with current contents of the screen
140 // Seed OpenSSL PRNG with performance counter
145 // Securely erase the memory used by the PRNG
147 // Shutdown OpenSSL library multithreading support
148 CRYPTO_set_locking_callback(NULL
);
149 // Clear the set of locks now to maintain symmetry with the constructor.
150 ppmutexOpenSSL
.reset();
156 * LogPrintf() has been broken a couple of times now
157 * by well-meaning people adding mutexes in the most straightforward way.
158 * It breaks because it may be called by global destructors during shutdown.
159 * Since the order of destruction of static/global objects is undefined,
160 * defining a mutex as a global object doesn't work (the mutex gets
161 * destroyed, and then some later destructor calls OutputDebugStringF,
162 * maybe indirectly, and you get a core dump at shutdown trying to lock
166 static boost::once_flag debugPrintInitFlag
= BOOST_ONCE_INIT
;
169 * We use boost::call_once() to make sure mutexDebugLog and
170 * vMsgsBeforeOpenLog are initialized in a thread-safe manner.
172 * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
173 * are leaked on exit. This is ugly, but will be cleaned up by
174 * the OS/libc. When the shutdown sequence is fully audited and
175 * tested, explicit destruction of these objects can be implemented.
177 static FILE* fileout
= NULL
;
178 static boost::mutex
* mutexDebugLog
= NULL
;
179 static std::list
<std::string
>* vMsgsBeforeOpenLog
;
181 static int FileWriteStr(const std::string
&str
, FILE *fp
)
183 return fwrite(str
.data(), 1, str
.size(), fp
);
186 static void DebugPrintInit()
188 assert(mutexDebugLog
== NULL
);
189 mutexDebugLog
= new boost::mutex();
190 vMsgsBeforeOpenLog
= new std::list
<std::string
>;
195 boost::call_once(&DebugPrintInit
, debugPrintInitFlag
);
196 boost::mutex::scoped_lock
scoped_lock(*mutexDebugLog
);
198 assert(fileout
== NULL
);
199 assert(vMsgsBeforeOpenLog
);
200 fs::path pathDebug
= GetDataDir() / "debug.log";
201 fileout
= fsbridge::fopen(pathDebug
, "a");
203 setbuf(fileout
, NULL
); // unbuffered
204 // dump buffered messages from before we opened the log
205 while (!vMsgsBeforeOpenLog
->empty()) {
206 FileWriteStr(vMsgsBeforeOpenLog
->front(), fileout
);
207 vMsgsBeforeOpenLog
->pop_front();
211 delete vMsgsBeforeOpenLog
;
212 vMsgsBeforeOpenLog
= NULL
;
215 struct CLogCategoryDesc
218 std::string category
;
221 const CLogCategoryDesc LogCategories
[] =
226 {BCLog::MEMPOOL
, "mempool"},
227 {BCLog::HTTP
, "http"},
228 {BCLog::BENCH
, "bench"},
232 {BCLog::ESTIMATEFEE
, "estimatefee"},
233 {BCLog::ADDRMAN
, "addrman"},
234 {BCLog::SELECTCOINS
, "selectcoins"},
235 {BCLog::REINDEX
, "reindex"},
236 {BCLog::CMPCTBLOCK
, "cmpctblock"},
237 {BCLog::RAND
, "rand"},
238 {BCLog::PRUNE
, "prune"},
239 {BCLog::PROXY
, "proxy"},
240 {BCLog::MEMPOOLREJ
, "mempoolrej"},
241 {BCLog::LIBEVENT
, "libevent"},
242 {BCLog::COINDB
, "coindb"},
244 {BCLog::LEVELDB
, "leveldb"},
249 bool GetLogCategory(uint32_t *f
, const std::string
*str
)
256 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
257 if (LogCategories
[i
].category
== *str
) {
258 *f
= LogCategories
[i
].flag
;
266 std::string
ListLogCategories()
270 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
271 // Omit the special cases.
272 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
273 if (outcount
!= 0) ret
+= ", ";
274 ret
+= LogCategories
[i
].category
;
281 std::vector
<CLogCategoryActive
> ListActiveLogCategories()
283 std::vector
<CLogCategoryActive
> ret
;
284 for (unsigned int i
= 0; i
< ARRAYLEN(LogCategories
); i
++) {
285 // Omit the special cases.
286 if (LogCategories
[i
].flag
!= BCLog::NONE
&& LogCategories
[i
].flag
!= BCLog::ALL
) {
287 CLogCategoryActive catActive
;
288 catActive
.category
= LogCategories
[i
].category
;
289 catActive
.active
= LogAcceptCategory(LogCategories
[i
].flag
);
290 ret
.push_back(catActive
);
297 * fStartedNewLine is a state variable held by the calling context that will
298 * suppress printing of the timestamp when multiple calls are made that don't
299 * end in a newline. Initialize it to true, and hold it, in the calling context.
301 static std::string
LogTimestampStr(const std::string
&str
, std::atomic_bool
*fStartedNewLine
)
303 std::string strStamped
;
308 if (*fStartedNewLine
) {
309 int64_t nTimeMicros
= GetTimeMicros();
310 strStamped
= DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros
/1000000);
312 strStamped
+= strprintf(".%06d", nTimeMicros
%1000000);
313 int64_t mocktime
= GetMockTime();
315 strStamped
+= " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime
) + ")";
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 ArgsManager::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 std::vector
<std::string
> ArgsManager::GetArgs(const std::string
& strArg
)
426 return mapMultiArgs
.at(strArg
);
429 bool ArgsManager::IsArgSet(const std::string
& strArg
)
432 return mapArgs
.count(strArg
);
435 std::string
ArgsManager::GetArg(const std::string
& strArg
, const std::string
& strDefault
)
438 if (mapArgs
.count(strArg
))
439 return mapArgs
[strArg
];
443 int64_t ArgsManager::GetArg(const std::string
& strArg
, int64_t nDefault
)
446 if (mapArgs
.count(strArg
))
447 return atoi64(mapArgs
[strArg
]);
451 bool ArgsManager::GetBoolArg(const std::string
& strArg
, bool fDefault
)
454 if (mapArgs
.count(strArg
))
455 return InterpretBool(mapArgs
[strArg
]);
459 bool ArgsManager::SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
462 if (mapArgs
.count(strArg
))
464 ForceSetArg(strArg
, strValue
);
468 bool ArgsManager::SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
471 return SoftSetArg(strArg
, std::string("1"));
473 return SoftSetArg(strArg
, std::string("0"));
476 void ArgsManager::ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
479 mapArgs
[strArg
] = strValue
;
480 mapMultiArgs
[strArg
].push_back(strValue
);
485 static const int screenWidth
= 79;
486 static const int optIndent
= 2;
487 static const int msgIndent
= 7;
489 std::string
HelpMessageGroup(const std::string
&message
) {
490 return std::string(message
) + std::string("\n\n");
493 std::string
HelpMessageOpt(const std::string
&option
, const std::string
&message
) {
494 return std::string(optIndent
,' ') + std::string(option
) +
495 std::string("\n") + std::string(msgIndent
,' ') +
496 FormatParagraph(message
, screenWidth
- msgIndent
, msgIndent
) +
500 static std::string
FormatException(const std::exception
* pex
, const char* pszThread
)
503 char pszModule
[MAX_PATH
] = "";
504 GetModuleFileNameA(NULL
, pszModule
, sizeof(pszModule
));
506 const char* pszModule
= "bitcoin";
510 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex
).name(), pex
->what(), pszModule
, pszThread
);
513 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule
, pszThread
);
516 void PrintExceptionContinue(const std::exception
* pex
, const char* pszThread
)
518 std::string message
= FormatException(pex
, pszThread
);
519 LogPrintf("\n\n************************\n%s\n", message
);
520 fprintf(stderr
, "\n\n************************\n%s\n", message
.c_str());
523 fs::path
GetDefaultDataDir()
525 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
526 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
527 // Mac: ~/Library/Application Support/Bitcoin
531 return GetSpecialFolderPath(CSIDL_APPDATA
) / "Bitcoin";
534 char* pszHome
= getenv("HOME");
535 if (pszHome
== NULL
|| strlen(pszHome
) == 0)
536 pathRet
= fs::path("/");
538 pathRet
= fs::path(pszHome
);
541 return pathRet
/ "Library/Application Support/Bitcoin";
544 return pathRet
/ ".bitcoin";
549 static fs::path pathCached
;
550 static fs::path pathCachedNetSpecific
;
551 static CCriticalSection csPathCached
;
553 const fs::path
&GetDataDir(bool fNetSpecific
)
558 fs::path
&path
= fNetSpecific
? pathCachedNetSpecific
: pathCached
;
560 // This can be called during exceptions by LogPrintf(), so we cache the
561 // value so we don't have to do memory allocations after that.
565 if (IsArgSet("-datadir")) {
566 path
= fs::system_complete(GetArg("-datadir", ""));
567 if (!fs::is_directory(path
)) {
572 path
= GetDefaultDataDir();
575 path
/= BaseParams().DataDir();
577 fs::create_directories(path
);
582 void ClearDatadirCache()
586 pathCached
= fs::path();
587 pathCachedNetSpecific
= fs::path();
590 fs::path
GetConfigFile(const std::string
& confPath
)
592 fs::path
pathConfigFile(confPath
);
593 if (!pathConfigFile
.is_complete())
594 pathConfigFile
= GetDataDir(false) / pathConfigFile
;
596 return pathConfigFile
;
599 void ArgsManager::ReadConfigFile(const std::string
& confPath
)
601 fs::ifstream
streamConfig(GetConfigFile(confPath
));
602 if (!streamConfig
.good())
603 return; // No bitcoin.conf file is OK
607 std::set
<std::string
> setOptions
;
608 setOptions
.insert("*");
610 for (boost::program_options::detail::config_file_iterator
it(streamConfig
, setOptions
), end
; it
!= end
; ++it
)
612 // Don't overwrite existing settings so command line settings override bitcoin.conf
613 std::string strKey
= std::string("-") + it
->string_key
;
614 std::string strValue
= it
->value
[0];
615 InterpretNegativeSetting(strKey
, strValue
);
616 if (mapArgs
.count(strKey
) == 0)
617 mapArgs
[strKey
] = strValue
;
618 mapMultiArgs
[strKey
].push_back(strValue
);
621 // If datadir is changed in .conf file:
626 fs::path
GetPidFile()
628 fs::path
pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME
));
629 if (!pathPidFile
.is_complete()) pathPidFile
= GetDataDir() / pathPidFile
;
633 void CreatePidFile(const fs::path
&path
, pid_t pid
)
635 FILE* file
= fsbridge::fopen(path
, "w");
638 fprintf(file
, "%d\n", pid
);
644 bool RenameOver(fs::path src
, fs::path dest
)
647 return MoveFileExA(src
.string().c_str(), dest
.string().c_str(),
648 MOVEFILE_REPLACE_EXISTING
) != 0;
650 int rc
= std::rename(src
.string().c_str(), dest
.string().c_str());
656 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
657 * Specifically handles case where path p exists, but it wasn't possible for the user to
658 * write to the parent directory.
660 bool TryCreateDirectory(const fs::path
& p
)
664 return fs::create_directory(p
);
665 } catch (const fs::filesystem_error
&) {
666 if (!fs::exists(p
) || !fs::is_directory(p
))
670 // create_directory didn't create the directory, it had to have existed already
674 void FileCommit(FILE *file
)
676 fflush(file
); // harmless if redundantly called
678 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
679 FlushFileBuffers(hFile
);
681 #if defined(__linux__) || defined(__NetBSD__)
682 fdatasync(fileno(file
));
683 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
684 fcntl(fileno(file
), F_FULLFSYNC
, 0);
691 bool TruncateFile(FILE *file
, unsigned int length
) {
693 return _chsize(_fileno(file
), length
) == 0;
695 return ftruncate(fileno(file
), length
) == 0;
700 * this function tries to raise the file descriptor limit to the requested number.
701 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
703 int RaiseFileDescriptorLimit(int nMinFD
) {
707 struct rlimit limitFD
;
708 if (getrlimit(RLIMIT_NOFILE
, &limitFD
) != -1) {
709 if (limitFD
.rlim_cur
< (rlim_t
)nMinFD
) {
710 limitFD
.rlim_cur
= nMinFD
;
711 if (limitFD
.rlim_cur
> limitFD
.rlim_max
)
712 limitFD
.rlim_cur
= limitFD
.rlim_max
;
713 setrlimit(RLIMIT_NOFILE
, &limitFD
);
714 getrlimit(RLIMIT_NOFILE
, &limitFD
);
716 return limitFD
.rlim_cur
;
718 return nMinFD
; // getrlimit failed, assume it's fine
723 * this function tries to make a particular range of a file allocated (corresponding to disk space)
724 * it is advisory, and the range specified in the arguments will never contain live data
726 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
) {
728 // Windows-specific version
729 HANDLE hFile
= (HANDLE
)_get_osfhandle(_fileno(file
));
730 LARGE_INTEGER nFileSize
;
731 int64_t nEndPos
= (int64_t)offset
+ length
;
732 nFileSize
.u
.LowPart
= nEndPos
& 0xFFFFFFFF;
733 nFileSize
.u
.HighPart
= nEndPos
>> 32;
734 SetFilePointerEx(hFile
, nFileSize
, 0, FILE_BEGIN
);
736 #elif defined(MAC_OSX)
737 // OSX specific version
739 fst
.fst_flags
= F_ALLOCATECONTIG
;
740 fst
.fst_posmode
= F_PEOFPOSMODE
;
742 fst
.fst_length
= (off_t
)offset
+ length
;
743 fst
.fst_bytesalloc
= 0;
744 if (fcntl(fileno(file
), F_PREALLOCATE
, &fst
) == -1) {
745 fst
.fst_flags
= F_ALLOCATEALL
;
746 fcntl(fileno(file
), F_PREALLOCATE
, &fst
);
748 ftruncate(fileno(file
), fst
.fst_length
);
749 #elif defined(__linux__)
750 // Version using posix_fallocate
751 off_t nEndPos
= (off_t
)offset
+ length
;
752 posix_fallocate(fileno(file
), 0, nEndPos
);
755 // TODO: just write one byte per block
756 static const char buf
[65536] = {};
757 fseek(file
, offset
, SEEK_SET
);
759 unsigned int now
= 65536;
762 fwrite(buf
, 1, now
, file
); // allowed to fail; this function is advisory anyway
768 void ShrinkDebugFile()
770 // Amount of debug.log to save at end when shrinking (must fit in memory)
771 constexpr size_t RECENT_DEBUG_HISTORY_SIZE
= 10 * 1000000;
772 // Scroll debug.log if it's getting too big
773 fs::path pathLog
= GetDataDir() / "debug.log";
774 FILE* file
= fsbridge::fopen(pathLog
, "r");
775 // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
776 // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
777 if (file
&& fs::file_size(pathLog
) > 11 * (RECENT_DEBUG_HISTORY_SIZE
/ 10))
779 // Restart the file with some of the end
780 std::vector
<char> vch(RECENT_DEBUG_HISTORY_SIZE
, 0);
781 fseek(file
, -((long)vch
.size()), SEEK_END
);
782 int nBytes
= fread(vch
.data(), 1, vch
.size(), file
);
785 file
= fsbridge::fopen(pathLog
, "w");
788 fwrite(vch
.data(), 1, nBytes
, file
);
792 else if (file
!= NULL
)
797 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
)
799 char pszPath
[MAX_PATH
] = "";
801 if(SHGetSpecialFolderPathA(NULL
, pszPath
, nFolder
, fCreate
))
803 return fs::path(pszPath
);
806 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
811 void runCommand(const std::string
& strCommand
)
813 int nErr
= ::system(strCommand
.c_str());
815 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand
, nErr
);
818 void RenameThread(const char* name
)
820 #if defined(PR_SET_NAME)
821 // Only the first 15 characters are used (16 - NUL terminator)
822 ::prctl(PR_SET_NAME
, name
, 0, 0, 0);
823 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
824 pthread_set_name_np(pthread_self(), name
);
826 #elif defined(MAC_OSX)
827 pthread_setname_np(name
);
829 // Prevent warnings for unused parameters...
834 void SetupEnvironment()
836 #ifdef HAVE_MALLOPT_ARENA_MAX
837 // glibc-specific: On 32-bit systems set the number of arenas to 1.
838 // By default, since glibc 2.10, the C library will create up to two heap
839 // arenas per core. This is known to cause excessive virtual address space
840 // usage in our usage. Work around it by setting the maximum number of
842 if (sizeof(void*) == 4) {
843 mallopt(M_ARENA_MAX
, 1);
846 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
847 // may be invalid, in which case the "C" locale is used as fallback.
848 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
850 std::locale(""); // Raises a runtime error if current locale is invalid
851 } catch (const std::runtime_error
&) {
852 setenv("LC_ALL", "C", 1);
855 // The path locale is lazy initialized and to avoid deinitialization errors
856 // in multithreading environments, it is set explicitly by the main thread.
857 // A dummy locale is used to extract the internal default locale, used by
858 // fs::path, which is then used to explicitly imbue the path.
859 std::locale loc
= fs::path::imbue(std::locale::classic());
860 fs::path::imbue(loc
);
863 bool SetupNetworking()
866 // Initialize Windows Sockets
868 int ret
= WSAStartup(MAKEWORD(2,2), &wsadata
);
869 if (ret
!= NO_ERROR
|| LOBYTE(wsadata
.wVersion
) != 2 || HIBYTE(wsadata
.wVersion
) != 2)
877 #if BOOST_VERSION >= 105600
878 return boost::thread::physical_concurrency();
879 #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
880 return boost::thread::hardware_concurrency();
884 std::string
CopyrightHolders(const std::string
& strPrefix
)
886 std::string strCopyrightHolders
= strPrefix
+ strprintf(_(COPYRIGHT_HOLDERS
), _(COPYRIGHT_HOLDERS_SUBSTITUTION
));
888 // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
889 if (strprintf(COPYRIGHT_HOLDERS
, COPYRIGHT_HOLDERS_SUBSTITUTION
).find("Bitcoin Core") == std::string::npos
) {
890 strCopyrightHolders
+= "\n" + strPrefix
+ "The Bitcoin Core developers";
892 return strCopyrightHolders
;