Bitcoin Core 22.99.0
P2P Digital Currency
common.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#if defined(HAVE_CONFIG_H)
7#endif
8
9#include <clientversion.h>
10#include <compat/sanity.h>
11#include <crypto/sha256.h>
12#include <key.h>
13#include <logging.h>
14#include <node/ui_interface.h>
15#include <pubkey.h>
16#include <random.h>
17#include <util/system.h>
18#include <util/time.h>
19#include <util/translation.h>
20
21#include <memory>
22
23static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
24
25namespace init {
27{
28 std::string sha256_algo = SHA256AutoDetect();
29 LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
30 RandomInit();
31 ECC_Start();
33}
34
36{
37 globalVerifyHandle.reset();
38 ECC_Stop();
39}
40
42{
43 if (!ECC_InitSanityCheck()) {
44 return InitError(Untranslated("Elliptic curve cryptography sanity check failure. Aborting."));
45 }
46
48 return false;
49
50 if (!Random_SanityCheck()) {
51 return InitError(Untranslated("OS cryptographic RNG sanity check failure. Aborting."));
52 }
53
54 if (!ChronoSanityCheck()) {
55 return InitError(Untranslated("Clock epoch mismatch. Aborting."));
56 }
57
58 return true;
59}
60
62{
63 argsman.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
64 argsman.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
65 "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + LogInstance().LogCategoriesString() + ". This option can be specified multiple times to output multiple categories.",
67 argsman.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except the specified category. This option can be specified multiple times to exclude multiple categories."), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
68 argsman.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
69 argsman.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
70#ifdef HAVE_THREAD_LOCAL
71 argsman.AddArg("-logthreadnames", strprintf("Prepend debug output with name of the originating thread (only available on platforms supporting thread_local) (default: %u)", DEFAULT_LOGTHREADNAMES), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
72#else
73 argsman.AddHiddenArgs({"-logthreadnames"});
74#endif
75 argsman.AddArg("-logsourcelocations", strprintf("Prepend debug output with name of the originating source location (source file, line number and function name) (default: %u)", DEFAULT_LOGSOURCELOCATIONS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
76 argsman.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
77 argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
78 argsman.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
79}
80
82{
83 LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
85 LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
88#ifdef HAVE_THREAD_LOCAL
90#endif
92
93 fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
94}
95
97{
98 if (args.IsArgSet("-debug")) {
99 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
100 const std::vector<std::string> categories = args.GetArgs("-debug");
101
102 if (std::none_of(categories.begin(), categories.end(),
103 [](std::string cat){return cat == "0" || cat == "none";})) {
104 for (const auto& cat : categories) {
105 if (!LogInstance().EnableCategory(cat)) {
106 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
107 }
108 }
109 }
110 }
111
112 // Now remove the logging categories which were explicitly excluded
113 for (const std::string& cat : args.GetArgs("-debugexclude")) {
114 if (!LogInstance().DisableCategory(cat)) {
115 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
116 }
117 }
118}
119
120bool StartLogging(const ArgsManager& args)
121{
122 if (LogInstance().m_print_to_file) {
123 if (args.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
124 // Do this first since it both loads a bunch of debug.log into memory,
125 // and because this needs to happen before any other debug.log printing
127 }
128 }
129 if (!LogInstance().StartLogging()) {
130 return InitError(strprintf(Untranslated("Could not open debug log file %s"),
131 fs::PathToString(LogInstance().m_file_path)));
132 }
133
134 if (!LogInstance().m_log_timestamps)
135 LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
136 LogPrintf("Default data directory %s\n", fs::PathToString(GetDefaultDataDir()));
137 LogPrintf("Using data directory %s\n", fs::PathToString(gArgs.GetDataDirNet()));
138
139 // Only log conf file usage message if conf file actually exists.
140 fs::path config_file_path = GetConfigFile(args.GetArg("-conf", BITCOIN_CONF_FILENAME));
141 if (fs::exists(config_file_path)) {
142 LogPrintf("Config file: %s\n", fs::PathToString(config_file_path));
143 } else if (args.IsArgSet("-conf")) {
144 // Warn if no conf file exists at path provided by user
145 InitWarning(strprintf(_("The specified config file %s does not exist"), fs::PathToString(config_file_path)));
146 } else {
147 // Not categorizing as "Warning" because it's the default behavior
148 LogPrintf("Config file: %s (not found, skipping)\n", fs::PathToString(config_file_path));
149 }
150
151 // Log the config arguments to debug.log
152 args.LogArgs();
153
154 return true;
155}
156
158{
159 std::string version_string = FormatFullVersion();
160#ifdef DEBUG
161 version_string += " (debug build)";
162#else
163 version_string += " (release build)";
164#endif
165 LogPrintf(PACKAGE_NAME " version %s\n", version_string);
166}
167} // namespace init
#define PACKAGE_NAME
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:585
@ ALLOW_ANY
disable validation
Definition: system.h:166
@ DEBUG_ONLY
Definition: system.h:173
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:487
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:496
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:288
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1053
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:590
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:663
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:642
bool m_log_sourcelocations
Definition: logging.h:99
fs::path m_file_path
Definition: logging.h:101
bool m_log_time_micros
Definition: logging.h:97
bool m_log_threadnames
Definition: logging.h:98
bool m_log_timestamps
Definition: logging.h:96
void ShrinkDebugFile()
Definition: logging.cpp:297
bool m_print_to_file
Definition: logging.h:94
bool m_print_to_console
Definition: logging.h:93
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:316
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
std::string FormatFullVersion()
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: common.cpp:23
bool glibcxx_sanity_test()
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:363
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:370
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:387
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
bool fLogIPs
Definition: logging.cpp:38
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:15
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:25
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
#define LogPrintf(...)
Definition: logging.h:187
static bool exists(const path &p)
Definition: fs.h:77
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:133
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:61
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:96
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:41
void SetGlobals()
Definition: common.cpp:26
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:120
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:81
void UnsetGlobals()
Definition: common.cpp:35
void LogPackageVersion()
Definition: common.cpp:157
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:641
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:710
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:562
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
bool ChronoSanityCheck()
Sanity check epoch match normal Unix epoch.
Definition: time.cpp:36
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:132
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
fs::path GetDefaultDataDir()
Definition: system.cpp:788
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1368
ArgsManager gArgs
Definition: system.cpp:85
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:819
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:82