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.
7 * Server/client environment: argument handling, config file parsing,
8 * logging, thread wrappers, startup time
10 #ifndef BITCOIN_UTIL_H
11 #define BITCOIN_UTIL_H
13 #if defined(HAVE_CONFIG_H)
14 #include "config/bitcoin-config.h"
20 #include "tinyformat.h"
30 #include <boost/signals2/signal.hpp>
32 // Application startup time (used for uptime calculation)
33 int64_t GetStartupTime();
35 static const bool DEFAULT_LOGTIMEMICROS
= false;
36 static const bool DEFAULT_LOGIPS
= false;
37 static const bool DEFAULT_LOGTIMESTAMPS
= true;
39 /** Signals for translation. */
40 class CTranslationInterface
43 /** Translate a message to the native language of the user. */
44 boost::signals2::signal
<std::string (const char* psz
)> Translate
;
47 extern bool fPrintToConsole
;
48 extern bool fPrintToDebugLog
;
50 extern bool fLogTimestamps
;
51 extern bool fLogTimeMicros
;
53 extern std::atomic
<bool> fReopenDebugLog
;
54 extern CTranslationInterface translationInterface
;
56 extern const char * const BITCOIN_CONF_FILENAME
;
57 extern const char * const BITCOIN_PID_FILENAME
;
59 extern std::atomic
<uint32_t> logCategories
;
62 * Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
63 * If no translation slot is registered, nothing is returned, and simply return the input.
65 inline std::string
_(const char* psz
)
67 boost::optional
<std::string
> rv
= translationInterface
.Translate(psz
);
68 return rv
? (*rv
) : psz
;
71 void SetupEnvironment();
72 bool SetupNetworking();
74 struct CLogCategoryActive
81 enum LogFlags
: uint32_t {
91 ESTIMATEFEE
= (1 << 8),
93 SELECTCOINS
= (1 << 10),
95 CMPCTBLOCK
= (1 << 12),
99 MEMPOOLREJ
= (1 << 16),
100 LIBEVENT
= (1 << 17),
107 /** Return true if log accepts specified category */
108 static inline bool LogAcceptCategory(uint32_t category
)
110 return (logCategories
.load(std::memory_order_relaxed
) & category
) != 0;
113 /** Returns a string with the log categories. */
114 std::string
ListLogCategories();
116 /** Returns a vector of the active log categories. */
117 std::vector
<CLogCategoryActive
> ListActiveLogCategories();
119 /** Return true if str parses as a log category and set the flags in f */
120 bool GetLogCategory(uint32_t *f
, const std::string
*str
);
122 /** Send a string to the log output */
123 int LogPrintStr(const std::string
&str
);
125 /** Get format string from VA_ARGS for error reporting */
126 template<typename
... Args
> std::string
FormatStringFromLogArgs(const char *fmt
, const Args
&... args
) { return fmt
; }
128 static inline void MarkUsed() {}
129 template<typename T
, typename
... Args
> static inline void MarkUsed(const T
& t
, const Args
&... args
)
136 #define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
137 #define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
139 #define LogPrintf(...) do { \
140 std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
142 _log_msg_ = tfm::format(__VA_ARGS__); \
143 } catch (tinyformat::format_error &fmterr) { \
144 /* Original format string will have newline so don't add one here */ \
145 _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
147 LogPrintStr(_log_msg_); \
150 #define LogPrint(category, ...) do { \
151 if (LogAcceptCategory((category))) { \
152 LogPrintf(__VA_ARGS__); \
157 template<typename
... Args
>
158 bool error(const char* fmt
, const Args
&... args
)
160 LogPrintStr("ERROR: " + tfm::format(fmt
, args
...) + "\n");
164 void PrintExceptionContinue(const std::exception
*pex
, const char* pszThread
);
165 void FileCommit(FILE *file
);
166 bool TruncateFile(FILE *file
, unsigned int length
);
167 int RaiseFileDescriptorLimit(int nMinFD
);
168 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
);
169 bool RenameOver(fs::path src
, fs::path dest
);
170 bool TryCreateDirectories(const fs::path
& p
);
171 fs::path
GetDefaultDataDir();
172 const fs::path
&GetDataDir(bool fNetSpecific
= true);
173 void ClearDatadirCache();
174 fs::path
GetConfigFile(const std::string
& confPath
);
176 fs::path
GetPidFile();
177 void CreatePidFile(const fs::path
&path
, pid_t pid
);
180 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
= true);
183 void ShrinkDebugFile();
184 void runCommand(const std::string
& strCommand
);
186 inline bool IsSwitchChar(char c
)
189 return c
== '-' || c
== '/';
198 mutable CCriticalSection cs_args
;
199 std::map
<std::string
, std::string
> mapArgs
;
200 std::map
<std::string
, std::vector
<std::string
>> mapMultiArgs
;
202 void ParseParameters(int argc
, const char*const argv
[]);
203 void ReadConfigFile(const std::string
& confPath
);
206 * Return a vector of strings of the given argument
208 * @param strArg Argument to get (e.g. "-foo")
209 * @return command-line arguments
211 std::vector
<std::string
> GetArgs(const std::string
& strArg
) const;
214 * Return true if the given argument has been manually set
216 * @param strArg Argument to get (e.g. "-foo")
217 * @return true if the argument has been set
219 bool IsArgSet(const std::string
& strArg
) const;
222 * Return string argument or default value
224 * @param strArg Argument to get (e.g. "-foo")
225 * @param strDefault (e.g. "1")
226 * @return command-line argument or default value
228 std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
) const;
231 * Return integer argument or default value
233 * @param strArg Argument to get (e.g. "-foo")
234 * @param nDefault (e.g. 1)
235 * @return command-line argument (0 if invalid number) or default value
237 int64_t GetArg(const std::string
& strArg
, int64_t nDefault
) const;
240 * Return boolean argument or default value
242 * @param strArg Argument to get (e.g. "-foo")
243 * @param fDefault (true or false)
244 * @return command-line argument or default value
246 bool GetBoolArg(const std::string
& strArg
, bool fDefault
) const;
249 * Set an argument if it doesn't already have a value
251 * @param strArg Argument to set (e.g. "-foo")
252 * @param strValue Value (e.g. "1")
253 * @return true if argument gets set, false if it already had a value
255 bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
);
258 * Set a boolean argument if it doesn't already have a value
260 * @param strArg Argument to set (e.g. "-foo")
261 * @param fValue Value (e.g. false)
262 * @return true if argument gets set, false if it already had a value
264 bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
);
266 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
267 // been set. Also called directly in testing.
268 void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
);
271 extern ArgsManager gArgs
;
274 * Format a string to be used as group of options in help messages
276 * @param message Group name (e.g. "RPC server options:")
277 * @return the formatted string
279 std::string
HelpMessageGroup(const std::string
& message
);
282 * Format a string to be used as option description in help messages
284 * @param option Option message (e.g. "-rpcuser=<user>")
285 * @param message Option description (e.g. "Username for JSON-RPC connections")
286 * @return the formatted string
288 std::string
HelpMessageOpt(const std::string
& option
, const std::string
& message
);
291 * Return the number of physical cores available on the current system.
292 * @note This does not count virtual cores, such as those provided by HyperThreading
293 * when boost is newer than 1.56.
297 void RenameThread(const char* name
);
300 * .. and a wrapper that just calls func once
302 template <typename Callable
> void TraceThread(const char* name
, Callable func
)
304 std::string s
= strprintf("bitcoin-%s", name
);
305 RenameThread(s
.c_str());
308 LogPrintf("%s thread start\n", name
);
310 LogPrintf("%s thread exit\n", name
);
312 catch (const boost::thread_interrupted
&)
314 LogPrintf("%s thread interrupt\n", name
);
317 catch (const std::exception
& e
) {
318 PrintExceptionContinue(&e
, name
);
322 PrintExceptionContinue(nullptr, name
);
327 std::string
CopyrightHolders(const std::string
& strPrefix
);
329 #endif // BITCOIN_UTIL_H