Bitcoin ABC  0.28.12
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)
6 #include <config/bitcoin-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/miner.h>
15 #include <node/ui_interface.h>
16 #include <pubkey.h>
17 #include <random.h>
18 #include <util/system.h>
19 #include <util/time.h>
20 #include <util/translation.h>
21 
22 #include <memory>
23 
25 
26 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
27 
28 namespace init {
29 void SetGlobals() {
30  std::string sha256_algo = SHA256AutoDetect();
31  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
32  RandomInit();
33  ECC_Start();
35 }
36 
37 void UnsetGlobals() {
38  globalVerifyHandle.reset();
39  ECC_Stop();
40 }
41 
42 bool SanityChecks() {
43  if (!ECC_InitSanityCheck()) {
44  return InitError(Untranslated(
45  "Elliptic curve cryptography sanity check failure. Aborting."));
46  }
47 
48  if (!glibcxx_sanity_test()) {
49  return false;
50  }
51 
52  if (!Random_SanityCheck()) {
53  return InitError(Untranslated(
54  "OS cryptographic RNG sanity check failure. Aborting."));
55  }
56 
57  if (!ChronoSanityCheck()) {
58  return InitError(Untranslated("Clock epoch mismatch. Aborting."));
59  }
60 
61  return true;
62 }
63 
64 void AddLoggingArgs(ArgsManager &argsman) {
65  argsman.AddArg(
66  "-debuglogfile=<file>",
67  strprintf("Specify location of debug log file. Relative paths will be "
68  "prefixed by a net-specific datadir location. "
69  "(-nodebuglogfile to disable; default: %s)",
72  argsman.AddArg("-debug=<category>",
73  "Output debugging information (default: -nodebug, supplying "
74  "<category> is optional). "
75  "If <category> is not supplied or if <category> = 1, output "
76  "all debugging information. <category> can be: " +
77  LogInstance().LogCategoriesString() +
78  ". This option can be specified multiple times to "
79  "output multiple categories.",
81  argsman.AddArg(
82  "-debugexclude=<category>",
83  strprintf(
84  "Exclude debugging information for a category. Can be used in "
85  "conjunction with -debug=1 to output debug logs for all categories "
86  "except the specified category. This option can be specified "
87  "multiple times to exclude multiple categories."),
89  argsman.AddArg(
90  "-logips",
91  strprintf("Include IP addresses in debug output (default: %u)",
94  argsman.AddArg(
95  "-logtimestamps",
96  strprintf("Prepend debug output with timestamp (default: %u)",
99 #ifdef HAVE_THREAD_LOCAL
100  argsman.AddArg(
101  "-logthreadnames",
102  strprintf(
103  "Prepend debug output with name of the originating thread (only "
104  "available on platforms supporting thread_local) (default: %u)",
107 #else
108  argsman.AddHiddenArgs({"-logthreadnames"});
109 #endif
110  argsman.AddArg(
111  "-logsourcelocations",
112  strprintf(
113  "Prepend debug output with name of the originating source location "
114  "(source file, line number and function name) (default: %u)",
117  argsman.AddArg(
118  "-logtimemicros",
119  strprintf("Add microsecond precision to debug timestamps (default: %u)",
123  argsman.AddArg("-printtoconsole",
124  "Send trace/debug info to console (default: 1 when no "
125  "-daemon. To disable logging to file, set -nodebuglogfile)",
127  argsman.AddArg("-printpriority",
128  strprintf("Log transaction priority and fee per kB when "
129  "mining blocks (default: %d)",
133  argsman.AddArg(
134  "-shrinkdebugfile",
135  "Shrink debug.log file on client startup (default: 1 when no -debug)",
137 }
138 
139 void SetLoggingOptions(const ArgsManager &args) {
140  LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
142  args.GetPathArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
143 
145  args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
147  args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
149  args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
150 #ifdef HAVE_THREAD_LOCAL
152  args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
153 #endif
155  args.GetBoolArg("-logsourcelocations", DEFAULT_LOGSOURCELOCATIONS);
156 
157  fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
158 }
159 
161  if (args.IsArgSet("-debug")) {
162  // Special-case: if -debug=0/-nodebug is set, turn off debugging
163  // messages
164  const std::vector<std::string> categories = args.GetArgs("-debug");
165 
166  if (std::none_of(
167  categories.begin(), categories.end(),
168  [](std::string cat) { return cat == "0" || cat == "none"; })) {
169  for (const auto &cat : categories) {
170  if (!LogInstance().EnableCategory(cat)) {
171  InitWarning(
172  strprintf(_("Unsupported logging category %s=%s."),
173  "-debug", cat));
174  }
175  }
176  }
177  }
178 
179  // Now remove the logging categories which were explicitly excluded
180  for (const std::string &cat : args.GetArgs("-debugexclude")) {
181  if (!LogInstance().DisableCategory(cat)) {
182  InitWarning(strprintf(_("Unsupported logging category %s=%s."),
183  "-debugexclude", cat));
184  }
185  }
186 }
187 
188 bool StartLogging(const ArgsManager &args) {
189  BCLog::Logger &logger = LogInstance();
190  if (logger.m_print_to_file) {
191  if (args.GetBoolArg("-shrinkdebugfile",
192  logger.DefaultShrinkDebugFile())) {
193  // Do this first since it both loads a bunch of debug.log into
194  // memory, and because this needs to happen before any other
195  // debug.log printing.
196  logger.ShrinkDebugFile();
197  }
198  }
199 
200  if (!logger.StartLogging()) {
201  return InitError(
202  strprintf(Untranslated("Could not open debug log file %s"),
203  fs::PathToString(logger.m_file_path)));
204  }
205 
206  if (!logger.m_log_timestamps) {
207  LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
208  }
209  LogPrintf("Default data directory %s\n",
211  LogPrintf("Using data directory %s\n",
213 
214  // Only log conf file usage message if conf file actually exists.
215  fs::path config_file_path =
217  if (fs::exists(config_file_path)) {
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
221  InitWarning(
222  strprintf(_("The specified config file %s does not exist\n"),
223  fs::PathToString(config_file_path)));
224  } else {
225  // Not categorizing as "Warning" because it's the default behavior
226  LogPrintf("Config file: %s (not found, skipping)\n",
227  fs::PathToString(config_file_path));
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
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:599
@ ALLOW_ANY
Definition: system.h:161
@ DEBUG_ONLY
Definition: system.h:162
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:480
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:490
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:268
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1190
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:603
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:665
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:751
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:729
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: system.cpp:396
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:362
bool m_log_sourcelocations
Definition: logging.h:108
fs::path m_file_path
Definition: logging.h:110
bool m_log_time_micros
Definition: logging.h:106
bool m_log_threadnames
Definition: logging.h:107
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:44
bool m_log_timestamps
Definition: logging.h:105
void ShrinkDebugFile()
Definition: logging.cpp:285
bool m_print_to_file
Definition: logging.h:103
bool m_print_to_console
Definition: logging.h:102
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:226
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:26
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
bool fLogIPs
Definition: logging.cpp:17
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:18
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
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:206
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
Definition: common.cpp:28
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:64
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:160
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:42
void SetGlobals()
Definition: common.cpp:29
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:188
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:139
void UnsetGlobals()
Definition: common.cpp:37
void LogPackageVersion()
Definition: common.cpp:236
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:31
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
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:746
fs::path GetDefaultDataDir()
Definition: system.cpp:892
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:1453
ArgsManager gArgs
Definition: system.cpp:80
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:922
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:77
int64_t GetTime()
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...
Definition: tinyformat.h:1202
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.