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
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 static const bool DEFAULT_LOGTIMEMICROS
= false;
33 static const bool DEFAULT_LOGIPS
= false;
34 static const bool DEFAULT_LOGTIMESTAMPS
= true;
36 /** Signals for translation. */
37 class CTranslationInterface
40 /** Translate a message to the native language of the user. */
41 boost::signals2::signal
<std::string (const char* psz
)> Translate
;
44 extern bool fPrintToConsole
;
45 extern bool fPrintToDebugLog
;
47 extern bool fLogTimestamps
;
48 extern bool fLogTimeMicros
;
50 extern std::atomic
<bool> fReopenDebugLog
;
51 extern CTranslationInterface translationInterface
;
53 extern const char * const BITCOIN_CONF_FILENAME
;
54 extern const char * const BITCOIN_PID_FILENAME
;
56 extern std::atomic
<uint32_t> logCategories
;
59 * Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
60 * If no translation slot is registered, nothing is returned, and simply return the input.
62 inline std::string
_(const char* psz
)
64 boost::optional
<std::string
> rv
= translationInterface
.Translate(psz
);
65 return rv
? (*rv
) : psz
;
68 void SetupEnvironment();
69 bool SetupNetworking();
71 struct CLogCategoryActive
78 enum LogFlags
: uint32_t {
88 ESTIMATEFEE
= (1 << 8),
90 SELECTCOINS
= (1 << 10),
92 CMPCTBLOCK
= (1 << 12),
96 MEMPOOLREJ
= (1 << 16),
104 /** Return true if log accepts specified category */
105 static inline bool LogAcceptCategory(uint32_t category
)
107 return (logCategories
.load(std::memory_order_relaxed
) & category
) != 0;
110 /** Returns a string with the log categories. */
111 std::string
ListLogCategories();
113 /** Returns a vector of the active log categories. */
114 std::vector
<CLogCategoryActive
> ListActiveLogCategories();
116 /** Return true if str parses as a log category and set the flags in f */
117 bool GetLogCategory(uint32_t *f
, const std::string
*str
);
119 /** Send a string to the log output */
120 int LogPrintStr(const std::string
&str
);
122 /** Get format string from VA_ARGS for error reporting */
123 template<typename
... Args
> std::string
FormatStringFromLogArgs(const char *fmt
, const Args
&... args
) { return fmt
; }
125 #define LogPrintf(...) do { \
126 std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
128 _log_msg_ = tfm::format(__VA_ARGS__); \
129 } catch (tinyformat::format_error &fmterr) { \
130 /* Original format string will have newline so don't add one here */ \
131 _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
133 LogPrintStr(_log_msg_); \
136 #define LogPrint(category, ...) do { \
137 if (LogAcceptCategory((category))) { \
138 LogPrintf(__VA_ARGS__); \
142 template<typename
... Args
>
143 bool error(const char* fmt
, const Args
&... args
)
145 LogPrintStr("ERROR: " + tfm::format(fmt
, args
...) + "\n");
149 void PrintExceptionContinue(const std::exception
*pex
, const char* pszThread
);
150 void FileCommit(FILE *file
);
151 bool TruncateFile(FILE *file
, unsigned int length
);
152 int RaiseFileDescriptorLimit(int nMinFD
);
153 void AllocateFileRange(FILE *file
, unsigned int offset
, unsigned int length
);
154 bool RenameOver(fs::path src
, fs::path dest
);
155 bool TryCreateDirectories(const fs::path
& p
);
156 fs::path
GetDefaultDataDir();
157 const fs::path
&GetDataDir(bool fNetSpecific
= true);
158 void ClearDatadirCache();
159 fs::path
GetConfigFile(const std::string
& confPath
);
161 fs::path
GetPidFile();
162 void CreatePidFile(const fs::path
&path
, pid_t pid
);
165 fs::path
GetSpecialFolderPath(int nFolder
, bool fCreate
= true);
168 void ShrinkDebugFile();
169 void runCommand(const std::string
& strCommand
);
171 inline bool IsSwitchChar(char c
)
174 return c
== '-' || c
== '/';
183 CCriticalSection cs_args
;
184 std::map
<std::string
, std::string
> mapArgs
;
185 std::map
<std::string
, std::vector
<std::string
> > mapMultiArgs
;
187 void ParseParameters(int argc
, const char*const argv
[]);
188 void ReadConfigFile(const std::string
& confPath
);
189 std::vector
<std::string
> GetArgs(const std::string
& strArg
);
191 * Return true if the given argument has been manually set
193 * @param strArg Argument to get (e.g. "-foo")
194 * @return true if the argument has been set
196 bool IsArgSet(const std::string
& strArg
);
199 * Return string argument or default value
201 * @param strArg Argument to get (e.g. "-foo")
202 * @param default (e.g. "1")
203 * @return command-line argument or default value
205 std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
);
208 * Return integer argument or default value
210 * @param strArg Argument to get (e.g. "-foo")
211 * @param default (e.g. 1)
212 * @return command-line argument (0 if invalid number) or default value
214 int64_t GetArg(const std::string
& strArg
, int64_t nDefault
);
217 * Return boolean argument or default value
219 * @param strArg Argument to get (e.g. "-foo")
220 * @param default (true or false)
221 * @return command-line argument or default value
223 bool GetBoolArg(const std::string
& strArg
, bool fDefault
);
226 * Set an argument if it doesn't already have a value
228 * @param strArg Argument to set (e.g. "-foo")
229 * @param strValue Value (e.g. "1")
230 * @return true if argument gets set, false if it already had a value
232 bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
);
235 * Set a boolean argument if it doesn't already have a value
237 * @param strArg Argument to set (e.g. "-foo")
238 * @param fValue Value (e.g. false)
239 * @return true if argument gets set, false if it already had a value
241 bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
);
243 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
244 // been set. Also called directly in testing.
245 void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
);
248 extern ArgsManager gArgs
;
250 // wrappers using the global ArgsManager:
251 static inline void ParseParameters(int argc
, const char*const argv
[])
253 gArgs
.ParseParameters(argc
, argv
);
256 static inline void ReadConfigFile(const std::string
& confPath
)
258 gArgs
.ReadConfigFile(confPath
);
261 static inline bool SoftSetArg(const std::string
& strArg
, const std::string
& strValue
)
263 return gArgs
.SoftSetArg(strArg
, strValue
);
266 static inline void ForceSetArg(const std::string
& strArg
, const std::string
& strValue
)
268 gArgs
.ForceSetArg(strArg
, strValue
);
271 static inline bool IsArgSet(const std::string
& strArg
)
273 return gArgs
.IsArgSet(strArg
);
276 static inline std::string
GetArg(const std::string
& strArg
, const std::string
& strDefault
)
278 return gArgs
.GetArg(strArg
, strDefault
);
281 static inline int64_t GetArg(const std::string
& strArg
, int64_t nDefault
)
283 return gArgs
.GetArg(strArg
, nDefault
);
286 static inline bool GetBoolArg(const std::string
& strArg
, bool fDefault
)
288 return gArgs
.GetBoolArg(strArg
, fDefault
);
291 static inline bool SoftSetBoolArg(const std::string
& strArg
, bool fValue
)
293 return gArgs
.SoftSetBoolArg(strArg
, fValue
);
297 * Format a string to be used as group of options in help messages
299 * @param message Group name (e.g. "RPC server options:")
300 * @return the formatted string
302 std::string
HelpMessageGroup(const std::string
& message
);
305 * Format a string to be used as option description in help messages
307 * @param option Option message (e.g. "-rpcuser=<user>")
308 * @param message Option description (e.g. "Username for JSON-RPC connections")
309 * @return the formatted string
311 std::string
HelpMessageOpt(const std::string
& option
, const std::string
& message
);
314 * Return the number of physical cores available on the current system.
315 * @note This does not count virtual cores, such as those provided by HyperThreading
316 * when boost is newer than 1.56.
320 void RenameThread(const char* name
);
323 * .. and a wrapper that just calls func once
325 template <typename Callable
> void TraceThread(const char* name
, Callable func
)
327 std::string s
= strprintf("bitcoin-%s", name
);
328 RenameThread(s
.c_str());
331 LogPrintf("%s thread start\n", name
);
333 LogPrintf("%s thread exit\n", name
);
335 catch (const boost::thread_interrupted
&)
337 LogPrintf("%s thread interrupt\n", name
);
340 catch (const std::exception
& e
) {
341 PrintExceptionContinue(&e
, name
);
345 PrintExceptionContinue(NULL
, name
);
350 std::string
CopyrightHolders(const std::string
& strPrefix
);
352 #endif // BITCOIN_UTIL_H