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 
23 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
24 
25 namespace init {
26 void SetGlobals()
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 
47  if (!glibcxx_sanity_test())
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 
81 void SetLoggingOptions(const ArgsManager& args)
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 
120 bool 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  LogInstance().m_file_path.string()));
132  }
133 
134  if (!LogInstance().m_log_timestamps)
135  LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
136  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
137  LogPrintf("Using data directory %s\n", gArgs.GetDataDirNet().string());
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", config_file_path.string());
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"), config_file_path.string()));
146  } else {
147  // Not categorizing as "Warning" because it's the default behavior
148  LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
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
ArgsManager::LogArgs
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1052
AbsPathForConfigVal
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:1367
DEFAULT_LOGTIMEMICROS
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
fLogIPs
bool fLogIPs
Definition: logging.cpp:38
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:92
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:600
ArgsManager::AddHiddenArgs
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:661
_
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
init::SanityChecks
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:41
init::SetLoggingCategories
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:96
globalVerifyHandle
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: common.cpp:23
GetDefaultDataDir
fs::path GetDefaultDataDir()
Definition: system.cpp:786
ArgsManager::GetDataDirNet
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:282
init::SetGlobals
void SetGlobals()
Definition: common.cpp:26
ChronoSanityCheck
bool ChronoSanityCheck()
Sanity check epoch match normal Unix epoch.
Definition: time.cpp:36
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
Definition: system.h:166
DEFAULT_LOGIPS
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:492
ECC_InitSanityCheck
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:363
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
glibcxx_sanity_test
bool glibcxx_sanity_test()
Definition: glibcxx_sanity.cpp:58
clientversion.h
DEFAULT_LOGTIMESTAMPS
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23
bitcoin-config.h
pubkey.h
sanity.h
FormatISO8601DateTime
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:132
ArgsManager::DEBUG_ONLY
@ DEBUG_ONLY
Definition: system.h:167
BITCOIN_CONF_FILENAME
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:81
SHA256AutoDetect
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:562
BCLog::Logger::m_log_timestamps
bool m_log_timestamps
Definition: logging.h:94
init::SetLoggingOptions
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:81
random.h
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
ECC_Stop
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:387
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:362
init::LogPackageVersion
void LogPackageVersion()
Definition: common.cpp:157
InitError
bool InitError(const bilingual_str &str)
Show error message.
Definition: ui_interface.cpp:56
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:295
ArgsManager::AddArg
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:640
time.h
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:588
LogPrintf
#define LogPrintf(...)
Definition: logging.h:185
OptionsCategory::OPTIONS
@ OPTIONS
DEFAULT_LOGSOURCELOCATIONS
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:25
init::UnsetGlobals
void UnsetGlobals()
Definition: common.cpp:35
RandomInit
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:710
gArgs
ArgsManager gArgs
Definition: system.cpp:84
BCLog::Logger::m_log_sourcelocations
bool m_log_sourcelocations
Definition: logging.h:97
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:99
ui_interface.h
sha256.h
DEFAULT_LOGTHREADNAMES
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
InitWarning
void InitWarning(const bilingual_str &str)
Show warning message.
Definition: ui_interface.cpp:62
system.h
ECC_Start
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:370
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
key.h
ArgsManager::IsArgNegated
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:583
ECCVerifyHandle
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:315
GetConfigFile
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:817
ArgsManager
Definition: system.h:158
translation.h
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:91
init::StartLogging
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:120
init
Definition: bitcoin-node.cpp:16
Random_SanityCheck
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:641
BCLog::Logger::m_log_time_micros
bool m_log_time_micros
Definition: logging.h:95
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
OptionsCategory::DEBUG_TEST
@ DEBUG_TEST
DEFAULT_DEBUGLOGFILE
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:15
ArgsManager::GetArgs
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:483
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:50
init::AddLoggingArgs
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:61
BCLog::Logger::m_log_threadnames
bool m_log_threadnames
Definition: logging.h:96