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 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
);
204 std::vector
<std::string
> GetArgs(const std::string
& strArg
);
207 * Return true if the given argument has been manually set
209 * @param strArg Argument to get (e.g. "-foo")
210 * @return true if the argument has been set
212 bool IsArgSet(const std::string
& strArg
);
215 * Return string argument or default value
217 * @param strArg Argument to get (e.g. "-foo")
218 * @param default (e.g. "1")
219 * @return command-line argument or default value
221 std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
);
224 * Return integer argument or default value
226 * @param strArg Argument to get (e.g. "-foo")
227 * @param default (e.g. 1)
228 * @return command-line argument (0 if invalid number) or default value
230 int64_t GetArg(const std::string
& strArg
, int64_t nDefault
);
233 * Return boolean argument or default value
235 * @param strArg Argument to get (e.g. "-foo")
236 * @param default (true or false)
237 * @return command-line argument or default value
239 bool GetBoolArg(const std::string
& strArg
, bool fDefault
);
242 * Set an argument if it doesn't already have a value
244 * @param strArg Argument to set (e.g. "-foo")
245 * @param strValue Value (e.g. "1")
246 * @return true if argument gets set, false if it already had a value
248 bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
);
251 * Set a boolean argument if it doesn't already have a value
253 * @param strArg Argument to set (e.g. "-foo")
254 * @param fValue Value (e.g. false)
255 * @return true if argument gets set, false if it already had a value
257 bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
);
259 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
260 // been set. Also called directly in testing.
261 void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
);
264 extern ArgsManager gArgs
;
266 // wrappers using the global ArgsManager:
267 static inline void ParseParameters(int argc
, const char*const argv
[])
269 gArgs
.ParseParameters(argc
, argv
);
272 static inline void ReadConfigFile(const std::string
& confPath
)
274 gArgs
.ReadConfigFile(confPath
);
277 static inline bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
279 return gArgs
.SoftSetArg(strArg
, strValue
);
282 static inline void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
284 gArgs
.ForceSetArg(strArg
, strValue
);
287 static inline bool IsArgSet(const std::string
& strArg
)
289 return gArgs
.IsArgSet(strArg
);
292 static inline std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
)
294 return gArgs
.GetArg(strArg
, strDefault
);
297 static inline int64_t GetArg(const std::string
& strArg
, int64_t nDefault
)
299 return gArgs
.GetArg(strArg
, nDefault
);
302 static inline bool GetBoolArg(const std::string
& strArg
, bool fDefault
)
304 return gArgs
.GetBoolArg(strArg
, fDefault
);
307 static inline bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
309 return gArgs
.SoftSetBoolArg(strArg
, fValue
);
313 * Format a string to be used as group of options in help messages
315 * @param message Group name (e.g. "RPC server options:")
316 * @return the formatted string
318 std::string
HelpMessageGroup(const std::string
& message
);
321 * Format a string to be used as option description in help messages
323 * @param option Option message (e.g. "-rpcuser=<user>")
324 * @param message Option description (e.g. "Username for JSON-RPC connections")
325 * @return the formatted string
327 std::string
HelpMessageOpt(const std::string
& option
, const std::string
& message
);
330 * Return the number of physical cores available on the current system.
331 * @note This does not count virtual cores, such as those provided by HyperThreading
332 * when boost is newer than 1.56.
336 void RenameThread(const char* name
);
339 * .. and a wrapper that just calls func once
341 template <typename Callable
> void TraceThread(const char* name
, Callable func
)
343 std::string s
= strprintf("bitcoin-%s", name
);
344 RenameThread(s
.c_str());
347 LogPrintf("%s thread start\n", name
);
349 LogPrintf("%s thread exit\n", name
);
351 catch (const boost::thread_interrupted
&)
353 LogPrintf("%s thread interrupt\n", name
);
356 catch (const std::exception
& e
) {
357 PrintExceptionContinue(&e
, name
);
361 PrintExceptionContinue(NULL
, name
);
366 std::string
CopyrightHolders(const std::string
& strPrefix
);
368 #endif // BITCOIN_UTIL_H