Merge #9895: Turn TryCreateDirectory() into TryCreateDirectories()
[bitcoinplatinum.git] / src / util.h
blob76f8b32a5e5fa115462b0f70ca6a2e7b80c802a2
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>
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
39 public:
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;
49 extern bool fLogIPs;
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;
58 /**
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
73 std::string category;
74 bool active;
77 namespace BCLog {
78 enum LogFlags : uint32_t {
79 NONE = 0,
80 NET = (1 << 0),
81 TOR = (1 << 1),
82 MEMPOOL = (1 << 2),
83 HTTP = (1 << 3),
84 BENCH = (1 << 4),
85 ZMQ = (1 << 5),
86 DB = (1 << 6),
87 RPC = (1 << 7),
88 ESTIMATEFEE = (1 << 8),
89 ADDRMAN = (1 << 9),
90 SELECTCOINS = (1 << 10),
91 REINDEX = (1 << 11),
92 CMPCTBLOCK = (1 << 12),
93 RAND = (1 << 13),
94 PRUNE = (1 << 14),
95 PROXY = (1 << 15),
96 MEMPOOLREJ = (1 << 16),
97 LIBEVENT = (1 << 17),
98 COINDB = (1 << 18),
99 QT = (1 << 19),
100 LEVELDB = (1 << 20),
101 ALL = ~(uint32_t)0,
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 */ \
127 try { \
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_); \
134 } while(0)
136 #define LogPrint(category, ...) do { \
137 if (LogAcceptCategory((category))) { \
138 LogPrintf(__VA_ARGS__); \
140 } while(0)
142 template<typename... Args>
143 bool error(const char* fmt, const Args&... args)
145 LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
146 return false;
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);
160 #ifndef WIN32
161 fs::path GetPidFile();
162 void CreatePidFile(const fs::path &path, pid_t pid);
163 #endif
164 #ifdef WIN32
165 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
166 #endif
167 void OpenDebugLog();
168 void ShrinkDebugFile();
169 void runCommand(const std::string& strCommand);
171 inline bool IsSwitchChar(char c)
173 #ifdef WIN32
174 return c == '-' || c == '/';
175 #else
176 return c == '-';
177 #endif
180 class ArgsManager
182 protected:
183 CCriticalSection cs_args;
184 std::map<std::string, std::string> mapArgs;
185 std::map<std::string, std::vector<std::string> > mapMultiArgs;
186 public:
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.
318 int GetNumCores();
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);
332 func();
333 LogPrintf("%s thread exit\n", name);
335 catch (const boost::thread_interrupted&)
337 LogPrintf("%s thread interrupt\n", name);
338 throw;
340 catch (const std::exception& e) {
341 PrintExceptionContinue(&e, name);
342 throw;
344 catch (...) {
345 PrintExceptionContinue(NULL, name);
346 throw;
350 std::string CopyrightHolders(const std::string& strPrefix);
352 #endif // BITCOIN_UTIL_H