Merge #12001: [RPC] Adding ::minRelayTxFee amount to getmempoolinfo and updating...
[bitcoinplatinum.git] / src / util.h
blob6a0d6a31e745d1016d868817f8a3fbbd94152c40
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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, startup time
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/condition_variable.hpp> // for boost::thread_interrupted
33 // Application startup time (used for uptime calculation)
34 int64_t GetStartupTime();
36 static const bool DEFAULT_LOGTIMEMICROS = false;
37 static const bool DEFAULT_LOGIPS = false;
38 static const bool DEFAULT_LOGTIMESTAMPS = true;
39 extern const char * const DEFAULT_DEBUGLOGFILE;
41 /** Signals for translation. */
42 class CTranslationInterface
44 public:
45 /** Translate a message to the native language of the user. */
46 boost::signals2::signal<std::string (const char* psz)> Translate;
49 extern bool fPrintToConsole;
50 extern bool fPrintToDebugLog;
52 extern bool fLogTimestamps;
53 extern bool fLogTimeMicros;
54 extern bool fLogIPs;
55 extern std::atomic<bool> fReopenDebugLog;
56 extern CTranslationInterface translationInterface;
58 extern const char * const BITCOIN_CONF_FILENAME;
59 extern const char * const BITCOIN_PID_FILENAME;
61 extern std::atomic<uint32_t> logCategories;
63 /**
64 * Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
65 * If no translation slot is registered, nothing is returned, and simply return the input.
67 inline std::string _(const char* psz)
69 boost::optional<std::string> rv = translationInterface.Translate(psz);
70 return rv ? (*rv) : psz;
73 void SetupEnvironment();
74 bool SetupNetworking();
76 struct CLogCategoryActive
78 std::string category;
79 bool active;
82 namespace BCLog {
83 enum LogFlags : uint32_t {
84 NONE = 0,
85 NET = (1 << 0),
86 TOR = (1 << 1),
87 MEMPOOL = (1 << 2),
88 HTTP = (1 << 3),
89 BENCH = (1 << 4),
90 ZMQ = (1 << 5),
91 DB = (1 << 6),
92 RPC = (1 << 7),
93 ESTIMATEFEE = (1 << 8),
94 ADDRMAN = (1 << 9),
95 SELECTCOINS = (1 << 10),
96 REINDEX = (1 << 11),
97 CMPCTBLOCK = (1 << 12),
98 RAND = (1 << 13),
99 PRUNE = (1 << 14),
100 PROXY = (1 << 15),
101 MEMPOOLREJ = (1 << 16),
102 LIBEVENT = (1 << 17),
103 COINDB = (1 << 18),
104 QT = (1 << 19),
105 LEVELDB = (1 << 20),
106 ALL = ~(uint32_t)0,
109 /** Return true if log accepts specified category */
110 static inline bool LogAcceptCategory(uint32_t category)
112 return (logCategories.load(std::memory_order_relaxed) & category) != 0;
115 /** Returns a string with the log categories. */
116 std::string ListLogCategories();
118 /** Returns a vector of the active log categories. */
119 std::vector<CLogCategoryActive> ListActiveLogCategories();
121 /** Return true if str parses as a log category and set the flags in f */
122 bool GetLogCategory(uint32_t *f, const std::string *str);
124 /** Send a string to the log output */
125 int LogPrintStr(const std::string &str);
127 /** Get format string from VA_ARGS for error reporting */
128 template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
130 static inline void MarkUsed() {}
131 template<typename T, typename... Args> static inline void MarkUsed(const T& t, const Args&... args)
133 (void)t;
134 MarkUsed(args...);
137 // Be conservative when using LogPrintf/error or other things which
138 // unconditionally log to debug.log! It should not be the case that an inbound
139 // peer can fill up a users disk with debug.log entries.
141 #ifdef USE_COVERAGE
142 #define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
143 #define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
144 #else
145 #define LogPrintf(...) do { \
146 std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
147 try { \
148 _log_msg_ = tfm::format(__VA_ARGS__); \
149 } catch (tinyformat::format_error &fmterr) { \
150 /* Original format string will have newline so don't add one here */ \
151 _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
153 LogPrintStr(_log_msg_); \
154 } while(0)
156 #define LogPrint(category, ...) do { \
157 if (LogAcceptCategory((category))) { \
158 LogPrintf(__VA_ARGS__); \
160 } while(0)
161 #endif
163 template<typename... Args>
164 bool error(const char* fmt, const Args&... args)
166 LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
167 return false;
170 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
171 void FileCommit(FILE *file);
172 bool TruncateFile(FILE *file, unsigned int length);
173 int RaiseFileDescriptorLimit(int nMinFD);
174 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
175 bool RenameOver(fs::path src, fs::path dest);
176 bool TryCreateDirectories(const fs::path& p);
177 fs::path GetDefaultDataDir();
178 const fs::path &GetDataDir(bool fNetSpecific = true);
179 void ClearDatadirCache();
180 fs::path GetConfigFile(const std::string& confPath);
181 #ifndef WIN32
182 fs::path GetPidFile();
183 void CreatePidFile(const fs::path &path, pid_t pid);
184 #endif
185 #ifdef WIN32
186 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
187 #endif
188 fs::path GetDebugLogPath();
189 bool OpenDebugLog();
190 void ShrinkDebugFile();
191 void runCommand(const std::string& strCommand);
193 inline bool IsSwitchChar(char c)
195 #ifdef WIN32
196 return c == '-' || c == '/';
197 #else
198 return c == '-';
199 #endif
202 class ArgsManager
204 protected:
205 mutable CCriticalSection cs_args;
206 std::map<std::string, std::string> mapArgs;
207 std::map<std::string, std::vector<std::string>> mapMultiArgs;
208 public:
209 void ParseParameters(int argc, const char*const argv[]);
210 void ReadConfigFile(const std::string& confPath);
213 * Return a vector of strings of the given argument
215 * @param strArg Argument to get (e.g. "-foo")
216 * @return command-line arguments
218 std::vector<std::string> GetArgs(const std::string& strArg) const;
221 * Return true if the given argument has been manually set
223 * @param strArg Argument to get (e.g. "-foo")
224 * @return true if the argument has been set
226 bool IsArgSet(const std::string& strArg) const;
229 * Return string argument or default value
231 * @param strArg Argument to get (e.g. "-foo")
232 * @param strDefault (e.g. "1")
233 * @return command-line argument or default value
235 std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
238 * Return integer argument or default value
240 * @param strArg Argument to get (e.g. "-foo")
241 * @param nDefault (e.g. 1)
242 * @return command-line argument (0 if invalid number) or default value
244 int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
247 * Return boolean argument or default value
249 * @param strArg Argument to get (e.g. "-foo")
250 * @param fDefault (true or false)
251 * @return command-line argument or default value
253 bool GetBoolArg(const std::string& strArg, bool fDefault) const;
256 * Set an argument if it doesn't already have a value
258 * @param strArg Argument to set (e.g. "-foo")
259 * @param strValue Value (e.g. "1")
260 * @return true if argument gets set, false if it already had a value
262 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
265 * Set a boolean argument if it doesn't already have a value
267 * @param strArg Argument to set (e.g. "-foo")
268 * @param fValue Value (e.g. false)
269 * @return true if argument gets set, false if it already had a value
271 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
273 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
274 // been set. Also called directly in testing.
275 void ForceSetArg(const std::string& strArg, const std::string& strValue);
278 extern ArgsManager gArgs;
281 * Format a string to be used as group of options in help messages
283 * @param message Group name (e.g. "RPC server options:")
284 * @return the formatted string
286 std::string HelpMessageGroup(const std::string& message);
289 * Format a string to be used as option description in help messages
291 * @param option Option message (e.g. "-rpcuser=<user>")
292 * @param message Option description (e.g. "Username for JSON-RPC connections")
293 * @return the formatted string
295 std::string HelpMessageOpt(const std::string& option, const std::string& message);
298 * Return the number of physical cores available on the current system.
299 * @note This does not count virtual cores, such as those provided by HyperThreading
300 * when boost is newer than 1.56.
302 int GetNumCores();
304 void RenameThread(const char* name);
307 * .. and a wrapper that just calls func once
309 template <typename Callable> void TraceThread(const char* name, Callable func)
311 std::string s = strprintf("bitcoin-%s", name);
312 RenameThread(s.c_str());
315 LogPrintf("%s thread start\n", name);
316 func();
317 LogPrintf("%s thread exit\n", name);
319 catch (const boost::thread_interrupted&)
321 LogPrintf("%s thread interrupt\n", name);
322 throw;
324 catch (const std::exception& e) {
325 PrintExceptionContinue(&e, name);
326 throw;
328 catch (...) {
329 PrintExceptionContinue(nullptr, name);
330 throw;
334 std::string CopyrightHolders(const std::string& strPrefix);
336 //! Substitute for C++14 std::make_unique.
337 template <typename T, typename... Args>
338 std::unique_ptr<T> MakeUnique(Args&&... args)
340 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
343 #endif // BITCOIN_UTIL_H