Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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)
6#include <config/bitcoin-config.h>
7#endif
8
9#include <clientversion.h>
10#include <common/args.h>
11#include <compat/sanity.h>
12#include <crypto/sha256.h>
13#include <key.h>
14#include <logging.h>
15#include <node/miner.h>
16#include <node/ui_interface.h>
17#include <pubkey.h>
18#include <random.h>
19#include <util/fs_helpers.h>
20#include <util/time.h>
21#include <util/translation.h>
22
23#include <memory>
24
26
27static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
28
29namespace init {
30void SetGlobals() {
31 std::string sha256_algo = SHA256AutoDetect();
32 LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
33 RandomInit();
34 ECC_Start();
36}
37
39 globalVerifyHandle.reset();
40 ECC_Stop();
41}
42
44 if (!ECC_InitSanityCheck()) {
46 "Elliptic curve cryptography sanity check failure. Aborting."));
47 }
48
49 if (!glibcxx_sanity_test()) {
50 return false;
51 }
52
53 if (!Random_SanityCheck()) {
55 "OS cryptographic RNG sanity check failure. Aborting."));
56 }
57
58 if (!ChronoSanityCheck()) {
59 return InitError(Untranslated("Clock epoch mismatch. Aborting."));
60 }
61
62 return true;
63}
64
66 argsman.AddArg(
67 "-debuglogfile=<file>",
68 strprintf("Specify location of debug log file. Relative paths will be "
69 "prefixed by a net-specific datadir location. "
70 "(-nodebuglogfile to disable; default: %s)",
73 argsman.AddArg("-debug=<category>",
74 "Output debugging information (default: -nodebug, supplying "
75 "<category> is optional). "
76 "If <category> is not supplied or if <category> = 1, output "
77 "all debugging information. <category> can be: " +
78 LogInstance().LogCategoriesString() +
79 ". This option can be specified multiple times to "
80 "output multiple categories.",
82 argsman.AddArg(
83 "-debugexclude=<category>",
85 "Exclude debugging information for a category. Can be used in "
86 "conjunction with -debug=1 to output debug logs for all categories "
87 "except the specified category. This option can be specified "
88 "multiple times to exclude multiple categories."),
90 argsman.AddArg(
91 "-logips",
92 strprintf("Include IP addresses in debug output (default: %u)",
95 argsman.AddArg(
96 "-logtimestamps",
97 strprintf("Prepend debug output with timestamp (default: %u)",
100#ifdef HAVE_THREAD_LOCAL
101 argsman.AddArg(
102 "-logthreadnames",
103 strprintf(
104 "Prepend debug output with name of the originating thread (only "
105 "available on platforms supporting thread_local) (default: %u)",
108#else
109 argsman.AddHiddenArgs({"-logthreadnames"});
110#endif
111 argsman.AddArg(
112 "-logsourcelocations",
113 strprintf(
114 "Prepend debug output with name of the originating source location "
115 "(source file, line number and function name) (default: %u)",
118 argsman.AddArg(
119 "-logtimemicros",
120 strprintf("Add microsecond precision to debug timestamps (default: %u)",
124 argsman.AddArg("-printtoconsole",
125 "Send trace/debug info to console (default: 1 when no "
126 "-daemon. To disable logging to file, set -nodebuglogfile)",
128 argsman.AddArg("-printpriority",
129 strprintf("Log transaction priority and fee per kB when "
130 "mining blocks (default: %d)",
131 DEFAULT_PRINTPRIORITY),
134 argsman.AddArg(
135 "-shrinkdebugfile",
136 "Shrink debug.log file on client startup (default: 1 when no -debug)",
138}
139
141 LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
143 args, args.GetPathArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
144
146 args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
148 args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
150 args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
151#ifdef HAVE_THREAD_LOCAL
153 args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
154#endif
156 args.GetBoolArg("-logsourcelocations", DEFAULT_LOGSOURCELOCATIONS);
157
158 fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
159}
160
162 if (args.IsArgSet("-debug")) {
163 // Special-case: if -debug=0/-nodebug is set, turn off debugging
164 // messages
165 const std::vector<std::string> categories = args.GetArgs("-debug");
166
167 if (std::none_of(
168 categories.begin(), categories.end(),
169 [](std::string cat) { return cat == "0" || cat == "none"; })) {
170 for (const auto &cat : categories) {
173 strprintf(_("Unsupported logging category %s=%s."),
174 "-debug", cat));
175 }
176 }
177 }
178 }
179
180 // Now remove the logging categories which were explicitly excluded
181 for (const std::string &cat : args.GetArgs("-debugexclude")) {
183 InitWarning(strprintf(_("Unsupported logging category %s=%s."),
184 "-debugexclude", cat));
185 }
186 }
187}
188
189bool StartLogging(const ArgsManager &args) {
191 if (logger.m_print_to_file) {
192 if (args.GetBoolArg("-shrinkdebugfile",
193 logger.DefaultShrinkDebugFile())) {
194 // Do this first since it both loads a bunch of debug.log into
195 // memory, and because this needs to happen before any other
196 // debug.log printing.
197 logger.ShrinkDebugFile();
198 }
199 }
200
201 if (!logger.StartLogging()) {
202 return InitError(
203 strprintf(Untranslated("Could not open debug log file %s"),
204 fs::PathToString(logger.m_file_path)));
205 }
206
207 if (!logger.m_log_timestamps) {
208 LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
209 }
210 LogPrintf("Default data directory %s\n",
212 LogPrintf("Using data directory %s\n",
214
215 // Only log conf file usage message if conf file actually exists.
218 LogPrintf("Config file: %s\n", fs::PathToString(config_file_path));
219 } else if (args.IsArgSet("-conf")) {
220 // Warn if no conf file exists at path provided by user
222 strprintf(_("The specified config file %s does not exist\n"),
224 } else {
225 // Not categorizing as "Warning" because it's the default behavior
226 LogPrintf("Config file: %s (not found, skipping)\n",
228 }
229
230 // Log the config arguments to debug.log
231 args.LogArgs();
232
233 return true;
234}
235
237 std::string version_string = FormatFullVersion();
238#ifdef DEBUG
239 version_string += " (debug build)";
240#else
241 version_string += " (release build)";
242#endif
243 LogPrintf("%s version %s\n", CLIENT_NAME, version_string);
244}
245} // namespace init
fs::path GetDefaultDataDir()
Definition args.cpp:759
ArgsManager gArgs
Definition args.cpp:38
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition args.cpp:490
@ ALLOW_ANY
Definition args.h:103
@ DEBUG_ONLY
Definition args.h:104
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition args.cpp:371
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition args.h:215
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition args.cpp:381
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition args.cpp:789
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition args.cpp:860
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:556
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition args.cpp:275
bool m_log_sourcelocations
Definition logging.h:117
fs::path m_file_path
Definition logging.h:119
bool m_log_time_micros
Definition logging.h:115
bool m_log_threadnames
Definition logging.h:116
void DisableCategory(LogFlags category)
Definition logging.cpp:387
void EnableCategory(LogFlags category)
Definition logging.cpp:374
bool m_log_timestamps
Definition logging.h:114
bool m_print_to_file
Definition logging.h:112
bool m_print_to_console
Definition logging.h:111
Users of this module must hold an ECCVerifyHandle.
Definition pubkey.h:223
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition fs.h:30
std::string FormatFullVersion()
const std::string CLIENT_NAME
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition common.cpp:27
bool glibcxx_sanity_test()
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition key.cpp:427
void ECC_Start()
Initialize the elliptic curve support.
Definition key.cpp:434
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition key.cpp:451
BCLog::Logger & LogInstance()
Definition logging.cpp:21
bool fLogIPs
Definition logging.cpp:18
const char *const DEFAULT_DEBUGLOGFILE
Definition logging.cpp:19
static const bool DEFAULT_LOGTIMESTAMPS
Definition logging.h:24
static const bool DEFAULT_LOGIPS
Definition logging.h:23
static const bool DEFAULT_LOGTHREADNAMES
Definition logging.h:25
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition logging.h:26
static const bool DEFAULT_LOGTIMEMICROS
Definition logging.h:22
#define LogPrintf(...)
Definition logging.h:227
static bool exists(const path &p)
Definition fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition fs.h:142
void AddLoggingArgs(ArgsManager &argsman)
Definition common.cpp:65
void SetLoggingCategories(const ArgsManager &args)
Definition common.cpp:161
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition common.cpp:43
void SetGlobals()
Definition common.cpp:30
bool StartLogging(const ArgsManager &args)
Definition common.cpp:189
void SetLoggingOptions(const ArgsManager &args)
Definition common.cpp:140
void UnsetGlobals()
Definition common.cpp:38
void LogPackageVersion()
Definition common.cpp:236
static const bool DEFAULT_PRINTPRIORITY
Definition miner.h:35
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition random.cpp:706
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition random.cpp:786
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition sha256.cpp:746
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:109
bool ChronoSanityCheck()
Sanity check epoch match normal Unix epoch.
Definition time.cpp:30
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition time.cpp:113
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition translation.h:36
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.