Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

util.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2019 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
11 #ifndef BITCOIN_UTIL_H
12 #define BITCOIN_UTIL_H
13 
14 #if defined(HAVE_CONFIG_H)
15 #include <config/dash-config.h>
16 #endif
17 
18 #include <compat.h>
19 #include <fs.h>
20 #include <sync.h>
21 #include <tinyformat.h>
22 #include <utiltime.h>
23 #include <amount.h>
24 
25 #include <atomic>
26 #include <exception>
27 #include <map>
28 #include <memory>
29 #include <set>
30 #include <stdint.h>
31 #include <string>
32 #include <unordered_map>
33 #include <unordered_set>
34 #include <vector>
35 
36 #include <boost/signals2/signal.hpp>
37 #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
38 
39 // Debugging macros
40 
41 // Uncomment the following line to enable debugging messages
42 // or enable on a per file basis prior to inclusion of util.h
43 //#define ENABLE_DASH_DEBUG
44 #ifdef ENABLE_DASH_DEBUG
45 #define DBG( x ) x
46 #else
47 #define DBG( x )
48 #endif
49 
50 //Dash only features
51 
52 extern bool fMasternodeMode;
53 extern bool fDisableGovernance;
54 extern int nWalletBackups;
55 
56 // Application startup time (used for uptime calculation)
57 int64_t GetStartupTime();
58 
59 static const bool DEFAULT_LOGTIMEMICROS = false;
60 static const bool DEFAULT_LOGIPS = false;
61 static const bool DEFAULT_LOGTIMESTAMPS = true;
62 static const bool DEFAULT_LOGTHREADNAMES = false;
63 extern const char * const DEFAULT_DEBUGLOGFILE;
64 
67 {
68 public:
70  boost::signals2::signal<std::string (const char* psz)> Translate;
71 };
72 
73 extern bool fPrintToConsole;
74 extern bool fPrintToDebugLog;
75 
76 extern bool fLogTimestamps;
77 extern bool fLogTimeMicros;
78 extern bool fLogThreadNames;
79 extern bool fLogIPs;
80 extern std::atomic<bool> fReopenDebugLog;
82 
83 extern const char * const BITCOIN_CONF_FILENAME;
84 extern const char * const BITCOIN_PID_FILENAME;
85 
86 extern std::atomic<uint64_t> logCategories;
87 
92 inline std::string _(const char* psz)
93 {
94  boost::optional<std::string> rv = translationInterface.Translate(psz);
95  return rv ? (*rv) : psz;
96 }
97 
98 void SetupEnvironment();
99 bool SetupNetworking();
100 
102 {
103  std::string category;
104  bool active;
105 };
106 
107 namespace BCLog {
108  enum LogFlags : uint64_t {
109  NONE = 0,
110  NET = (1 << 0),
111  TOR = (1 << 1),
112  MEMPOOL = (1 << 2),
113  HTTP = (1 << 3),
114  BENCHMARK = (1 << 4),
115  ZMQ = (1 << 5),
116  DB = (1 << 6),
117  RPC = (1 << 7),
118  ESTIMATEFEE = (1 << 8),
119  ADDRMAN = (1 << 9),
120  SELECTCOINS = (1 << 10),
121  REINDEX = (1 << 11),
122  CMPCTBLOCK = (1 << 12),
123  RANDOM = (1 << 13),
124  PRUNE = (1 << 14),
125  PROXY = (1 << 15),
126  MEMPOOLREJ = (1 << 16),
127  LIBEVENT = (1 << 17),
128  COINDB = (1 << 18),
129  QT = (1 << 19),
130  LEVELDB = (1 << 20),
131 
132  //Start Dash
133  CHAINLOCKS = ((uint64_t)1 << 32),
134  GOBJECT = ((uint64_t)1 << 33),
135  INSTANTSEND = ((uint64_t)1 << 34),
136  KEEPASS = ((uint64_t)1 << 35),
137  LLMQ = ((uint64_t)1 << 36),
138  LLMQ_DKG = ((uint64_t)1 << 37),
139  LLMQ_SIGS = ((uint64_t)1 << 38),
140  MNPAYMENTS = ((uint64_t)1 << 39),
141  MNSYNC = ((uint64_t)1 << 40),
142  PRIVATESEND = ((uint64_t)1 << 41),
143  SPORK = ((uint64_t)1 << 42),
144  NETCONN = ((uint64_t)1 << 43),
145  //End Dash
146 
147  NET_NETCONN = NET | NETCONN, // use this to have something logged in NET and NETCONN as well
148 
149  ALL = ~(uint64_t)0,
150  };
151 }
152 static inline bool LogAcceptCategory(uint64_t category)
153 {
154  return (logCategories.load(std::memory_order_relaxed) & category) != 0;
155 }
156 
158 std::string ListLogCategories();
159 
161 std::string ListActiveLogCategoriesString();
162 
164 std::vector<CLogCategoryActive> ListActiveLogCategories();
165 
167 bool GetLogCategory(uint64_t *f, const std::string *str);
168 
170 int LogPrintStr(const std::string &str);
171 
173 template<typename... Args>
174 std::string SafeStringFormat(const std::string& fmt, const Args&... args)
175 {
176  try {
177  return tinyformat::format(fmt, args...);
178  } catch (std::runtime_error& fmterr) {
179  std::string message = tinyformat::format("\n****TINYFORMAT ERROR****\n err=\"%s\"\n fmt=\"%s\"\n", fmterr.what(), fmt);
180  fprintf(stderr, "%s", message.c_str());
181  return message;
182  }
183 }
184 
186 template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
187 
188 static inline void MarkUsed() {}
189 template<typename T, typename... Args> static inline void MarkUsed(const T& t, const Args&... args)
190 {
191  (void)t;
192  MarkUsed(args...);
193 }
194 
195 // Be conservative when using LogPrintf/error or other things which
196 // unconditionally log to debug.log! It should not be the case that an inbound
197 // peer can fill up a users disk with debug.log entries.
198 
199 #ifdef USE_COVERAGE
200 #define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
201 #define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
202 #else
203 #define LogPrintf(...) do { \
204  std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
205  try { \
206  _log_msg_ = tfm::format(__VA_ARGS__); \
207  } catch (tinyformat::format_error &e) { \
208  /* Original format string will have newline so don't add one here */ \
209  _log_msg_ = "Error \"" + std::string(e.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
210  } \
211  LogPrintStr(_log_msg_); \
212 } while(0)
213 
214 #define LogPrint(category, ...) do { \
215  if (LogAcceptCategory((category))) { \
216  LogPrintf(__VA_ARGS__); \
217  } \
218 } while(0)
219 #endif
220 
221 template<typename... Args>
222 bool error(const char* fmt, const Args&... args)
223 {
224  LogPrintStr("ERROR: " + SafeStringFormat(fmt, args...) + "\n");
225  return false;
226 }
227 
228 void PrintExceptionContinue(const std::exception_ptr pex, const char* pszExceptionOrigin);
229 void FileCommit(FILE *file);
230 bool TruncateFile(FILE *file, unsigned int length);
231 int RaiseFileDescriptorLimit(int nMinFD);
232 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
233 bool RenameOver(fs::path src, fs::path dest);
234 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false);
235 
239 void ReleaseDirectoryLocks();
240 
241 bool TryCreateDirectories(const fs::path& p);
242 fs::path GetDefaultDataDir();
243 const fs::path &GetDataDir(bool fNetSpecific = true);
244 fs::path GetBackupsDir();
245 void ClearDatadirCache();
246 fs::path GetConfigFile(const std::string& confPath);
247 #ifndef WIN32
248 fs::path GetPidFile();
249 void CreatePidFile(const fs::path &path, pid_t pid);
250 #endif
251 #ifdef WIN32
252 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
253 #endif
254 fs::path GetDebugLogPath();
255 bool OpenDebugLog();
256 void ShrinkDebugFile();
257 void runCommand(const std::string& strCommand);
258 
267 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true);
268 
269 inline bool IsSwitchChar(char c)
270 {
271 #ifdef WIN32
272  return c == '-' || c == '/';
273 #else
274  return c == '-';
275 #endif
276 }
277 
279 {
280 protected:
281  friend class ArgsManagerHelper;
282 
284  std::map<std::string, std::vector<std::string>> m_override_args;
285  std::map<std::string, std::vector<std::string>> m_config_args;
286  std::string m_network;
287  std::set<std::string> m_network_only_args;
288 
289  void ReadConfigStream(std::istream& stream);
290 
291 public:
292  ArgsManager();
293 
297  void SelectConfigNetwork(const std::string& network);
298 
299  void ParseParameters(int argc, const char*const argv[]);
300  void ReadConfigFile(const std::string& confPath);
301 
308  void WarnForSectionOnlyArgs();
309 
316  std::vector<std::string> GetArgs(const std::string& strArg) const;
317 
324  bool IsArgSet(const std::string& strArg) const;
325 
333  bool IsArgNegated(const std::string& strArg) const;
334 
342  std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
343 
351  int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
352 
360  bool GetBoolArg(const std::string& strArg, bool fDefault) const;
361 
369  bool SoftSetArg(const std::string& strArg, const std::string& strValue);
370 
378  bool SoftSetBoolArg(const std::string& strArg, bool fValue);
379 
380  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
381  // been set. Also called directly in testing.
382  void ForceSetArg(const std::string& strArg, const std::string& strValue);
383  void ForceRemoveArg(const std::string& strArg);
384 
389  std::string GetChainName() const;
390 
396  std::string GetDevNetName() const;
397 };
398 
399 extern ArgsManager gArgs;
400 
407 std::string HelpMessageGroup(const std::string& message);
408 
416 std::string HelpMessageOpt(const std::string& option, const std::string& message);
417 
423 int GetNumCores();
424 
425 void RenameThread(const char* name);
426 std::string GetThreadName();
427 
428 namespace ctpl {
429  class thread_pool;
430 }
431 void RenameThreadPool(ctpl::thread_pool& tp, const char* baseName);
432 
436 template <typename Callable> void TraceThread(const std::string name, Callable func)
437 {
438  std::string s = "dash-" + name;
439  RenameThread(s.c_str());
440  try
441  {
442  LogPrintf("%s thread start\n", name);
443  func();
444  LogPrintf("%s thread exit\n", name);
445  }
446  catch (const boost::thread_interrupted&)
447  {
448  LogPrintf("%s thread interrupt\n", name);
449  throw;
450  }
451  catch (...) {
452  PrintExceptionContinue(std::current_exception(), name.c_str());
453  throw;
454  }
455 }
456 
457 std::string CopyrightHolders(const std::string& strPrefix, unsigned int nStartYear, unsigned int nEndYear);
458 
465 uint32_t StringVersionToInt(const std::string& strVersion);
466 
467 
474 std::string IntVersionToString(uint32_t nVersion);
475 
476 
484 std::string SafeIntVersionToString(uint32_t nVersion);
485 
486 
488 template <typename T, typename... Args>
489 std::unique_ptr<T> MakeUnique(Args&&... args)
490 {
491  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
492 }
493 
494 #endif // BITCOIN_UTIL_H
ArgsManager()
Definition: util.cpp:681
const char *const DEFAULT_DEBUGLOGFILE
Definition: util.cpp:106
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:784
void ParseParameters(int argc, const char *const argv[])
Definition: util.cpp:730
void TraceThread(const std::string name, Callable func)
Definition: util.h:436
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:840
int64_t GetStartupTime()
Definition: util.cpp:1429
Definition: util.h:107
void ShrinkDebugFile()
Definition: util.cpp:1193
Definition: ctpl.h:46
bool fPrintToConsole
Definition: util.cpp:109
bool GetLogCategory(uint64_t *f, const std::string *str)
Return true if str parses as a log category and set the flags in f.
Definition: util.cpp:291
std::string GetThreadName()
Definition: util.cpp:1261
void WarnForSectionOnlyArgs()
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: util.cpp:697
std::string SafeIntVersionToString(uint32_t nVersion)
Copy of the IntVersionToString, that returns "Invalid version" string instead of throwing std::bad_ca...
Definition: util.cpp:1415
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: util.cpp:477
bool fLogThreadNames
Definition: util.cpp:114
std::vector< CLogCategoryActive > ListActiveLogCategories()
Returns a vector of the active log categories.
Definition: util.cpp:337
bool SetupNetworking()
Definition: util.cpp:1343
int nWalletBackups
nWalletBackups: 1..10 - number of automatic backups to keep 0 - disabled by command-line -1 - disable...
Definition: util.cpp:102
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: util.cpp:725
void RenameThread(const char *name)
Definition: util.cpp:1244
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:824
std::map< std::string, std::vector< std::string > > m_config_args
Definition: util.h:285
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: util.cpp:848
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:880
void ReadConfigFile(const std::string &confPath)
Definition: util.cpp:1000
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:832
static const bool DEFAULT_LOGTIMEMICROS
Definition: util.h:59
std::set< std::string > m_network_only_args
Definition: util.h:287
static bool LogAcceptCategory(uint64_t category)
Definition: util.h:152
uint32_t StringVersionToInt(const std::string &strVersion)
Converts version strings to 4-byte unsigned integer.
Definition: util.cpp:1379
static const bool DEFAULT_LOGTIMESTAMPS
Definition: util.h:61
void SetupEnvironment()
Definition: util.cpp:1314
std::string CopyrightHolders(const std::string &strPrefix, unsigned int nStartYear, unsigned int nEndYear)
Definition: util.cpp:1364
void RenameThreadPool(ctpl::thread_pool &tp, const char *baseName)
Definition: util.cpp:1276
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: util.cpp:1085
fs::path GetBackupsDir()
Definition: util.cpp:960
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:105
fs::path GetDefaultDataDir()
Definition: util.cpp:898
static const bool DEFAULT_LOGIPS
Definition: util.h:60
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: util.cpp:790
#define LogPrintf(...)
Definition: util.h:203
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:1058
void PrintExceptionContinue(const std::exception_ptr pex, const char *pszExceptionOrigin)
Definition: util.cpp:891
fs::path GetDebugLogPath()
Definition: util.cpp:208
std::atomic< uint64_t > logCategories
const char * name
Definition: rest.cpp:36
std::string ListLogCategories()
Returns a string with the log categories.
Definition: util.cpp:322
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:967
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: util.cpp:506
fs::path GetPidFile()
Definition: util.cpp:1053
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:1355
CCriticalSection cs_args
Definition: util.h:283
bool OpenDebugLog()
Definition: util.cpp:214
static const bool DEFAULT_LOGTHREADNAMES
Definition: util.h:62
bool fLogIPs
Definition: util.cpp:115
bool fDisableGovernance
Definition: util.cpp:94
void ForceRemoveArg(const std::string &strArg)
Definition: util.cpp:854
const fs::path & GetDataDir(bool fNetSpecific=true)
Definition: util.cpp:928
void runCommand(const std::string &strCommand)
Definition: util.cpp:1236
LogFlags
Definition: util.h:108
void ClearDatadirCache()
Definition: util.cpp:968
std::string ListActiveLogCategoriesString()
Returns a string with the list of active log categories.
Definition: util.cpp:352
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:976
std::string GetDevNetName() const
Looks for -devnet and returns either "devnet-<name>" or simply "devnet" if no name was specified...
Definition: util.cpp:1045
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:104
std::unique_ptr< T > MakeUnique(Args &&... args)
Substitute for C++14 std::make_unique.
Definition: util.h:489
bool IsSwitchChar(char c)
Definition: util.h:269
bool fMasternodeMode
Definition: util.cpp:93
Internal helper functions for ArgsManager.
Definition: util.cpp:537
std::atomic< bool > fReopenDebugLog
void FileCommit(FILE *file)
Definition: util.cpp:1099
void ReadConfigStream(std::istream &stream)
Definition: util.cpp:981
boost::signals2::signal< std::string(const char *psz)> Translate
Translate a message to the native language of the user.
Definition: util.h:70
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
Signals for translation.
Definition: util.h:66
std::string category
Definition: util.h:103
bool fLogTimeMicros
Definition: util.cpp:113
std::string IntVersionToString(uint32_t nVersion)
Converts version as 4-byte unsigned integer to string.
Definition: util.cpp:1399
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:1069
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:1128
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: util.cpp:1026
ArgsManager gArgs
Definition: util.cpp:108
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:1151
CTranslationInterface translationInterface
Definition: util.cpp:117
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1116
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:765
static void MarkUsed()
Definition: util.h:188
int LogPrintStr(const std::string &str)
Send a string to the log output.
Definition: util.cpp:422
std::string SafeStringFormat(const std::string &fmt, const Args &... args)
Formats a string without throwing exceptions.
Definition: util.h:174
bool fLogTimestamps
Definition: util.cpp:112
std::string m_network
Definition: util.h:286
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: util.cpp:1434
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: util.cpp:884
std::string FormatStringFromLogArgs(const char *fmt, const Args &... args)
Get format string from VA_ARGS for error reporting.
Definition: util.h:186
std::map< std::string, std::vector< std::string > > m_override_args
Definition: util.h:284
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:92
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
bool fPrintToDebugLog
Definition: util.cpp:110
Released under the MIT license