Remove duplicate includes
[bitcoinplatinum.git] / src / util.h
blob4386ddd550e63e9ddf373f5a6593acaacf6bd373
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.
6 /**
7 * Server/client environment: argument handling, config file parsing,
8 * logging, thread wrappers
9 */
10 #ifndef BITCOIN_UTIL_H
11 #define BITCOIN_UTIL_H
13 #if defined(HAVE_CONFIG_H)
14 #include "config/bitcoin-config.h"
15 #endif
17 #include "compat.h"
18 #include "fs.h"
19 #include "sync.h"
20 #include "tinyformat.h"
21 #include "utiltime.h"
23 #include <atomic>
24 #include <exception>
25 #include <map>
26 #include <stdint.h>
27 #include <string>
28 #include <vector>
30 #include <boost/signals2/signal.hpp>
31 #include <boost/thread/exceptions.hpp>
33 static const bool DEFAULT_LOGTIMEMICROS = false;
34 static const bool DEFAULT_LOGIPS = false;
35 static const bool DEFAULT_LOGTIMESTAMPS = true;
37 /** Signals for translation. */
38 class CTranslationInterface
40 public:
41 /** Translate a message to the native language of the user. */
42 boost::signals2::signal<std::string (const char* psz)> Translate;
45 extern bool fPrintToConsole;
46 extern bool fPrintToDebugLog;
48 extern bool fLogTimestamps;
49 extern bool fLogTimeMicros;
50 extern bool fLogIPs;
51 extern std::atomic<bool> fReopenDebugLog;
52 extern CTranslationInterface translationInterface;
54 extern const char * const BITCOIN_CONF_FILENAME;
55 extern const char * const BITCOIN_PID_FILENAME;
57 extern std::atomic<uint32_t> logCategories;
59 /**
60 * Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
61 * If no translation slot is registered, nothing is returned, and simply return the input.
63 inline std::string _(const char* psz)
65 boost::optional<std::string> rv = translationInterface.Translate(psz);
66 return rv ? (*rv) : psz;
69 void SetupEnvironment();
70 bool SetupNetworking();
72 struct CLogCategoryActive
74 std::string category;
75 bool active;
78 namespace BCLog {
79 enum LogFlags : uint32_t {
80 NONE = 0,
81 NET = (1 << 0),
82 TOR = (1 << 1),
83 MEMPOOL = (1 << 2),
84 HTTP = (1 << 3),
85 BENCH = (1 << 4),
86 ZMQ = (1 << 5),
87 DB = (1 << 6),
88 RPC = (1 << 7),
89 ESTIMATEFEE = (1 << 8),
90 ADDRMAN = (1 << 9),
91 SELECTCOINS = (1 << 10),
92 REINDEX = (1 << 11),
93 CMPCTBLOCK = (1 << 12),
94 RAND = (1 << 13),
95 PRUNE = (1 << 14),
96 PROXY = (1 << 15),
97 MEMPOOLREJ = (1 << 16),
98 LIBEVENT = (1 << 17),
99 COINDB = (1 << 18),
100 QT = (1 << 19),
101 LEVELDB = (1 << 20),
102 ALL = ~(uint32_t)0,
105 /** Return true if log accepts specified category */
106 static inline bool LogAcceptCategory(uint32_t category)
108 return (logCategories.load(std::memory_order_relaxed) & category) != 0;
111 /** Returns a string with the log categories. */
112 std::string ListLogCategories();
114 /** Returns a vector of the active log categories. */
115 std::vector<CLogCategoryActive> ListActiveLogCategories();
117 /** Return true if str parses as a log category and set the flags in f */
118 bool GetLogCategory(uint32_t *f, const std::string *str);
120 /** Send a string to the log output */
121 int LogPrintStr(const std::string &str);
123 /** Get format string from VA_ARGS for error reporting */
124 template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
126 #define LogPrintf(...) do { \
127 std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
128 try { \
129 _log_msg_ = tfm::format(__VA_ARGS__); \
130 } catch (tinyformat::format_error &fmterr) { \
131 /* Original format string will have newline so don't add one here */ \
132 _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
134 LogPrintStr(_log_msg_); \
135 } while(0)
137 #define LogPrint(category, ...) do { \
138 if (LogAcceptCategory((category))) { \
139 LogPrintf(__VA_ARGS__); \
141 } while(0)
143 template<typename... Args>
144 bool error(const char* fmt, const Args&... args)
146 LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
147 return false;
150 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
151 void FileCommit(FILE *file);
152 bool TruncateFile(FILE *file, unsigned int length);
153 int RaiseFileDescriptorLimit(int nMinFD);
154 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
155 bool RenameOver(fs::path src, fs::path dest);
156 bool TryCreateDirectory(const fs::path& p);
157 fs::path GetDefaultDataDir();
158 const fs::path &GetDataDir(bool fNetSpecific = true);
159 void ClearDatadirCache();
160 fs::path GetConfigFile(const std::string& confPath);
161 #ifndef WIN32
162 fs::path GetPidFile();
163 void CreatePidFile(const fs::path &path, pid_t pid);
164 #endif
165 #ifdef WIN32
166 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
167 #endif
168 void OpenDebugLog();
169 void ShrinkDebugFile();
170 void runCommand(const std::string& strCommand);
172 inline bool IsSwitchChar(char c)
174 #ifdef WIN32
175 return c == '-' || c == '/';
176 #else
177 return c == '-';
178 #endif
181 class ArgsManager
183 protected:
184 CCriticalSection cs_args;
185 std::map<std::string, std::string> mapArgs;
186 std::map<std::string, std::vector<std::string> > mapMultiArgs;
187 public:
188 void ParseParameters(int argc, const char*const argv[]);
189 void ReadConfigFile(const std::string& confPath);
190 std::vector<std::string> GetArgs(const std::string& strArg);
192 * Return true if the given argument has been manually set
194 * @param strArg Argument to get (e.g. "-foo")
195 * @return true if the argument has been set
197 bool IsArgSet(const std::string& strArg);
200 * Return string argument or default value
202 * @param strArg Argument to get (e.g. "-foo")
203 * @param default (e.g. "1")
204 * @return command-line argument or default value
206 std::string GetArg(const std::string& strArg, const std::string& strDefault);
209 * Return integer argument or default value
211 * @param strArg Argument to get (e.g. "-foo")
212 * @param default (e.g. 1)
213 * @return command-line argument (0 if invalid number) or default value
215 int64_t GetArg(const std::string& strArg, int64_t nDefault);
218 * Return boolean argument or default value
220 * @param strArg Argument to get (e.g. "-foo")
221 * @param default (true or false)
222 * @return command-line argument or default value
224 bool GetBoolArg(const std::string& strArg, bool fDefault);
227 * Set an argument if it doesn't already have a value
229 * @param strArg Argument to set (e.g. "-foo")
230 * @param strValue Value (e.g. "1")
231 * @return true if argument gets set, false if it already had a value
233 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
236 * Set a boolean argument if it doesn't already have a value
238 * @param strArg Argument to set (e.g. "-foo")
239 * @param fValue Value (e.g. false)
240 * @return true if argument gets set, false if it already had a value
242 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
244 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
245 // been set. Also called directly in testing.
246 void ForceSetArg(const std::string& strArg, const std::string& strValue);
249 extern ArgsManager gArgs;
251 // wrappers using the global ArgsManager:
252 static inline void ParseParameters(int argc, const char*const argv[])
254 gArgs.ParseParameters(argc, argv);
257 static inline void ReadConfigFile(const std::string& confPath)
259 gArgs.ReadConfigFile(confPath);
262 static inline bool SoftSetArg(const std::string& strArg, const std::string& strValue)
264 return gArgs.SoftSetArg(strArg, strValue);
267 static inline void ForceSetArg(const std::string& strArg, const std::string& strValue)
269 gArgs.ForceSetArg(strArg, strValue);
272 static inline bool IsArgSet(const std::string& strArg)
274 return gArgs.IsArgSet(strArg);
277 static inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
279 return gArgs.GetArg(strArg, strDefault);
282 static inline int64_t GetArg(const std::string& strArg, int64_t nDefault)
284 return gArgs.GetArg(strArg, nDefault);
287 static inline bool GetBoolArg(const std::string& strArg, bool fDefault)
289 return gArgs.GetBoolArg(strArg, fDefault);
292 static inline bool SoftSetBoolArg(const std::string& strArg, bool fValue)
294 return gArgs.SoftSetBoolArg(strArg, fValue);
298 * Format a string to be used as group of options in help messages
300 * @param message Group name (e.g. "RPC server options:")
301 * @return the formatted string
303 std::string HelpMessageGroup(const std::string& message);
306 * Format a string to be used as option description in help messages
308 * @param option Option message (e.g. "-rpcuser=<user>")
309 * @param message Option description (e.g. "Username for JSON-RPC connections")
310 * @return the formatted string
312 std::string HelpMessageOpt(const std::string& option, const std::string& message);
315 * Return the number of physical cores available on the current system.
316 * @note This does not count virtual cores, such as those provided by HyperThreading
317 * when boost is newer than 1.56.
319 int GetNumCores();
321 void RenameThread(const char* name);
324 * .. and a wrapper that just calls func once
326 template <typename Callable> void TraceThread(const char* name, Callable func)
328 std::string s = strprintf("bitcoin-%s", name);
329 RenameThread(s.c_str());
332 LogPrintf("%s thread start\n", name);
333 func();
334 LogPrintf("%s thread exit\n", name);
336 catch (const boost::thread_interrupted&)
338 LogPrintf("%s thread interrupt\n", name);
339 throw;
341 catch (const std::exception& e) {
342 PrintExceptionContinue(&e, name);
343 throw;
345 catch (...) {
346 PrintExceptionContinue(NULL, name);
347 throw;
351 std::string CopyrightHolders(const std::string& strPrefix);
353 #endif // BITCOIN_UTIL_H