Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2021 The Bitcoin Core developers
3 : // Copyright (c) 2014-2025 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 :
7 : #include <util/system.h>
8 :
9 : #include <support/allocators/secure.h>
10 :
11 : #include <chainparamsbase.h>
12 : #include <ctpl_stl.h>
13 : #include <fs.h>
14 : #include <stacktraces.h>
15 : #include <sync.h>
16 : #include <util/check.h>
17 : #include <util/getuniquepath.h>
18 : #include <util/strencodings.h>
19 : #include <util/string.h>
20 : #include <util/syserror.h>
21 : #include <util/threadnames.h>
22 : #include <util/translation.h>
23 :
24 : #include <tinyformat.h>
25 :
26 : #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
27 : #include <pthread.h>
28 : #include <pthread_np.h>
29 : #endif
30 :
31 : #ifndef WIN32
32 : // for posix_fallocate, in configure.ac we check if it is present after this
33 : #ifdef __linux__
34 :
35 : #ifdef _POSIX_C_SOURCE
36 : #undef _POSIX_C_SOURCE
37 : #endif
38 :
39 : #define _POSIX_C_SOURCE 200112L
40 :
41 : #endif // __linux__
42 :
43 : #include <algorithm>
44 : #include <atomic>
45 : #include <cassert>
46 : #include <fcntl.h>
47 : #include <sched.h>
48 : #include <sys/resource.h>
49 : #include <sys/stat.h>
50 :
51 : #else
52 :
53 : #include <codecvt>
54 :
55 : #include <io.h> /* for _commit */
56 : #include <shellapi.h>
57 : #include <shlobj.h>
58 : #endif
59 :
60 : #ifdef HAVE_MALLOPT_ARENA_MAX
61 : #include <malloc.h>
62 : #endif
63 :
64 : #include <univalue.h>
65 :
66 : #include <fstream>
67 : #include <map>
68 : #include <memory>
69 : #include <optional>
70 : #include <string>
71 : #include <system_error>
72 : #include <thread>
73 : #include <typeinfo>
74 :
75 : // Application startup time (used for uptime calculation)
76 4714 : const int64_t nStartupTime = GetTime();
77 :
78 : //Dash only features
79 : const std::string gCoinJoinName = "CoinJoin";
80 :
81 : /**
82 : nWalletBackups:
83 : 1..10 - number of automatic backups to keep
84 : 0 - disabled by command-line
85 : -1 - disabled because of some error during run-time
86 : -2 - disabled because wallet was locked and we were not able to replenish keypool
87 : */
88 : int nWalletBackups = 10;
89 :
90 : const char * const BITCOIN_CONF_FILENAME = "dash.conf";
91 : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
92 :
93 4714 : ArgsManager gArgs;
94 :
95 : /** Mutex to protect dir_locks. */
96 : static GlobalMutex cs_dir_locks;
97 :
98 : /** A map that contains all the currently held directory locks. After
99 : * successful locking, these will be held here until the global destructor
100 : * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
101 : * is called.
102 : */
103 4714 : static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
104 :
105 7998 : bool LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only)
106 : {
107 7998 : LOCK(cs_dir_locks);
108 7998 : fs::path pathLockFile = directory / lockfile_name;
109 :
110 : // If a lock for this directory already exists in the map, don't try to re-lock it
111 7998 : if (dir_locks.count(fs::PathToString(pathLockFile))) {
112 2 : return true;
113 : }
114 :
115 : // Create empty lock file if it doesn't exist.
116 7996 : FILE* file = fsbridge::fopen(pathLockFile, "a");
117 7996 : if (file) fclose(file);
118 7996 : auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
119 7996 : if (!lock->TryLock()) {
120 17 : return error("Error while attempting to lock directory %s: %s", fs::PathToString(directory), lock->GetReason());
121 : }
122 7979 : if (!probe_only) {
123 : // Lock successful and we're not just probing, put it into the map
124 4945 : dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
125 4945 : }
126 7979 : return true;
127 7998 : }
128 :
129 1912 : void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name)
130 : {
131 1912 : LOCK(cs_dir_locks);
132 1912 : dir_locks.erase(fs::PathToString(directory / lockfile_name));
133 1912 : }
134 :
135 3 : void ReleaseDirectoryLocks()
136 : {
137 3 : LOCK(cs_dir_locks);
138 3 : dir_locks.clear();
139 3 : }
140 :
141 6065 : bool DirIsWritable(const fs::path& directory)
142 : {
143 6065 : fs::path tmpFile = GetUniquePath(directory);
144 :
145 6065 : FILE* file = fsbridge::fopen(tmpFile, "a");
146 6065 : if (!file) return false;
147 :
148 6064 : fclose(file);
149 6064 : remove(tmpFile);
150 :
151 6064 : return true;
152 6065 : }
153 :
154 33308 : bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
155 : {
156 33308 : constexpr uint64_t min_disk_space = 52428800; // 50 MiB
157 :
158 33308 : uint64_t free_bytes_available = fs::space(dir).available;
159 33308 : return free_bytes_available >= min_disk_space + additional_bytes;
160 : }
161 :
162 0 : std::streampos GetFileSize(const char* path, std::streamsize max) {
163 0 : std::ifstream file{path, std::ios::binary};
164 0 : file.ignore(max);
165 0 : return file.gcount();
166 0 : }
167 :
168 : /**
169 : * Interpret a string argument as a boolean.
170 : *
171 : * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
172 : * like "foo", return 0. This means that if a user unintentionally supplies a
173 : * non-integer argument here, the return value is always false. This means that
174 : * -foo=false does what the user probably expects, but -foo=true is well defined
175 : * but does not do what they probably expected.
176 : *
177 : * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
178 : * representable as an int.
179 : *
180 : * For a more extensive discussion of this topic (and a wide range of opinions
181 : * on the Right Way to change this code), see PR12713.
182 : */
183 2421907 : static bool InterpretBool(const std::string& strValue)
184 : {
185 2421907 : if (strValue.empty())
186 19508 : return true;
187 2402399 : return (LocaleIndependentAtoi<int>(strValue) != 0);
188 2421907 : }
189 :
190 11510707 : static std::string SettingName(const std::string& arg)
191 : {
192 11510707 : return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
193 : }
194 :
195 324206 : struct KeyInfo {
196 : std::string name;
197 : std::string section;
198 324206 : bool negated{false};
199 : };
200 :
201 : /**
202 : * Parse "name", "section.name", "noname", "section.noname" settings keys.
203 : *
204 : * @note Where an option was negated can be later checked using the
205 : * IsArgNegated() method. One use case for this is to have a way to disable
206 : * options that are not normally boolean (e.g. using -nodebuglogfile to request
207 : * that debug log output is not sent to any file at all).
208 : */
209 324206 : KeyInfo InterpretKey(std::string key)
210 : {
211 324206 : KeyInfo result;
212 : // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
213 324206 : size_t option_index = key.find('.');
214 324206 : if (option_index != std::string::npos) {
215 135678 : result.section = key.substr(0, option_index);
216 135678 : key.erase(0, option_index + 1);
217 135678 : }
218 324206 : if (key.substr(0, 2) == "no") {
219 58947 : key.erase(0, 2);
220 58947 : result.negated = true;
221 58947 : }
222 324206 : result.name = key;
223 324206 : return result;
224 324206 : }
225 :
226 : /**
227 : * Interpret settings value based on registered flags.
228 : *
229 : * @param[in] key key information to know if key was negated
230 : * @param[in] value string value of setting to be parsed
231 : * @param[in] flags ArgsManager registered argument flags
232 : * @param[out] error Error description if settings value is not valid
233 : *
234 : * @return parsed settings value if it is valid, otherwise nullopt accompanied
235 : * by a descriptive error string
236 : */
237 302072 : static std::optional<util::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
238 : unsigned int flags, std::string& error)
239 : {
240 : // Return negated settings as false values.
241 302072 : if (key.negated) {
242 58947 : if (flags & ArgsManager::DISALLOW_NEGATION) {
243 0 : error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
244 0 : return std::nullopt;
245 : }
246 : // Double negatives like -nofoo=0 are supported (but discouraged)
247 58947 : if (value && !InterpretBool(*value)) {
248 11 : LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
249 11 : return true;
250 : }
251 58936 : return false;
252 : }
253 243125 : if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
254 2 : error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
255 2 : return std::nullopt;
256 : }
257 243123 : return value ? *value : "";
258 302072 : }
259 :
260 : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
261 : // #include class definitions for all members.
262 : // For example, m_settings has an internal dependency on univalue.
263 38849 : ArgsManager::ArgsManager() = default;
264 29419 : ArgsManager::~ArgsManager() = default;
265 :
266 30447 : std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
267 : {
268 30447 : std::set<std::string> unsuitables;
269 :
270 30447 : LOCK(cs_args);
271 :
272 : // if there's no section selected, don't worry
273 30447 : if (m_network.empty()) return std::set<std::string> {};
274 :
275 : // if it's okay to use the default section for this network, don't worry
276 30447 : if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
277 :
278 55575 : for (const auto& arg : m_network_only_args) {
279 34560 : if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
280 848 : unsuitables.insert(arg);
281 848 : }
282 : }
283 21015 : return unsuitables;
284 30447 : }
285 :
286 3733 : std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
287 : {
288 : // Section names to be recognized in the config file.
289 3733 : static const std::set<std::string> available_sections{
290 3222 : CBaseChainParams::REGTEST,
291 3222 : CBaseChainParams::DEVNET,
292 3222 : CBaseChainParams::TESTNET,
293 3222 : CBaseChainParams::MAIN,
294 : };
295 :
296 3733 : LOCK(cs_args);
297 3733 : std::list<SectionInfo> unrecognized = m_config_sections;
298 6841 : unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
299 3733 : return unrecognized;
300 3733 : }
301 :
302 0 : std::map<std::string, std::vector<util::SettingsValue>> ArgsManager::GetCommandLineArgs() const {
303 0 : LOCK(cs_args);
304 0 : return m_settings.command_line_options;
305 0 : }
306 :
307 5412 : void ArgsManager::SelectConfigNetwork(const std::string& network)
308 : {
309 5412 : LOCK(cs_args);
310 5412 : m_network = network;
311 5412 : }
312 :
313 33405 : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
314 : {
315 33405 : LOCK(cs_args);
316 33405 : m_settings.command_line_options.clear();
317 :
318 162889 : for (int i = 1; i < argc; i++) {
319 131449 : std::string key(argv[i]);
320 131449 : if (key == "-") break; //dash-tx using stdin
321 :
322 : #ifdef MAC_OSX
323 : // At the first time when a user gets the "App downloaded from the
324 : // internet" warning, and clicks the Open button, macOS passes
325 : // a unique process serial number (PSN) as -psn_... command-line
326 : // argument, which we filter out.
327 131437 : if (key.substr(0, 5) == "-psn_") continue;
328 : #endif
329 :
330 131437 : std::optional<std::string> val;
331 131437 : size_t is_index = key.find('=');
332 131437 : if (is_index != std::string::npos) {
333 112576 : val = key.substr(is_index + 1);
334 112576 : key.erase(is_index);
335 112576 : }
336 : #ifdef WIN32
337 : key = ToLower(key);
338 : if (key[0] == '/')
339 : key[0] = '-';
340 : #endif
341 :
342 131437 : if (key[0] != '-') {
343 1941 : if (!m_accept_any_command && m_command.empty()) {
344 : // The first non-dash arg is a registered command
345 133 : std::optional<unsigned int> flags = GetArgFlags(key);
346 133 : if (!flags || !(*flags & ArgsManager::COMMAND)) {
347 10 : error = strprintf("Invalid command '%s'", argv[i]);
348 10 : return false;
349 : }
350 123 : }
351 1931 : m_command.push_back(key);
352 3349 : while (++i < argc) {
353 : // The remaining args are command args
354 1418 : m_command.push_back(argv[i]);
355 : }
356 1931 : break;
357 : }
358 :
359 : // Transform --foo to -foo
360 129496 : if (key.length() > 1 && key[1] == '-')
361 6 : key.erase(0, 1);
362 :
363 : // Transform -foo to foo
364 129496 : key.erase(0, 1);
365 129496 : KeyInfo keyinfo = InterpretKey(key);
366 129496 : std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
367 :
368 : // Unknown command line options and command line options with dot
369 : // characters (which are returned from InterpretKey with nonempty
370 : // section strings) are not valid.
371 129496 : if (!flags || !keyinfo.section.empty()) {
372 10 : error = strprintf("Invalid parameter %s", argv[i]);
373 10 : return false;
374 : }
375 :
376 129486 : std::optional<util::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
377 129486 : if (!value) return false;
378 :
379 129484 : m_settings.command_line_options[keyinfo.name].push_back(*value);
380 131449 : }
381 :
382 : // we do not allow -includeconf from command line, only -noincludeconf
383 33383 : if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
384 7 : const util::SettingsSpan values{*includes};
385 : // Range may be empty if -noincludeconf was passed
386 7 : if (!values.empty()) {
387 6 : error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
388 6 : return false; // pick first value as example
389 : }
390 1 : }
391 33377 : return true;
392 33405 : }
393 :
394 435252 : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
395 : {
396 435252 : LOCK(cs_args);
397 2281215 : for (const auto& arg_map : m_available_args) {
398 2259779 : const auto search = arg_map.second.find(name);
399 2259779 : if (search != arg_map.second.end()) {
400 413816 : return search->second.m_flags;
401 : }
402 : }
403 21436 : return std::nullopt;
404 435252 : }
405 :
406 66479 : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
407 : {
408 66479 : if (IsArgNegated(arg)) return fs::path{};
409 66472 : std::string path_str = GetArg(arg, "");
410 66472 : if (path_str.empty()) return default_value;
411 25309 : fs::path result = fs::PathFromString(path_str).lexically_normal();
412 : // Remove trailing slash, if present.
413 25309 : return result.has_filename() ? result : result.parent_path();
414 66479 : }
415 :
416 1932499 : fs::path ArgsManager::GetBlocksDirPath() const
417 : {
418 1932499 : LOCK(cs_args);
419 1932499 : fs::path& path = m_cached_blocks_path;
420 :
421 : // Cache the path to avoid calling fs::create_directories on every call of
422 : // this function
423 1932499 : if (!path.empty()) return path;
424 :
425 3733 : if (IsArgSet("-blocksdir")) {
426 4 : path = fs::absolute(GetPathArg("-blocksdir"));
427 4 : if (!fs::is_directory(path)) {
428 2 : path = "";
429 2 : return path;
430 : }
431 2 : } else {
432 3729 : path = GetDataDirBase();
433 : }
434 :
435 3731 : path /= fs::PathFromString(BaseParams().DataDir());
436 3731 : path /= "blocks";
437 3731 : fs::create_directories(path);
438 3731 : return path;
439 1932499 : }
440 :
441 144859 : fs::path ArgsManager::GetDataDir(bool net_specific) const
442 : {
443 144859 : LOCK(cs_args);
444 144859 : fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
445 :
446 : // Used cached path if available
447 144859 : if (!path.empty()) return path;
448 :
449 13320 : const fs::path datadir{GetPathArg("-datadir")};
450 13320 : if (!datadir.empty()) {
451 13320 : path = fs::absolute(datadir);
452 13320 : if (!fs::is_directory(path)) {
453 0 : path = "";
454 0 : return path;
455 : }
456 13320 : } else {
457 0 : path = GetDefaultDataDir();
458 : }
459 :
460 13320 : if (net_specific && !BaseParams().DataDir().empty()) {
461 4495 : path /= fs::PathFromString(BaseParams().DataDir());
462 4495 : }
463 :
464 13320 : return path;
465 144859 : }
466 :
467 5 : fs::path ArgsManager::GetBackupsDirPath()
468 : {
469 5 : if (!IsArgSet("-walletbackupsdir"))
470 5 : return GetDataDirNet() / "backups";
471 :
472 0 : return fs::absolute(GetPathArg("-walletbackupsdir"));
473 5 : }
474 :
475 3114 : void ArgsManager::EnsureDataDir() const
476 : {
477 : /**
478 : * "/wallets" subdirectories are created in all **new**
479 : * datadirs, because wallet code will create new wallets in the "wallets"
480 : * subdirectory only if exists already, otherwise it will create them in
481 : * the top-level datadir where they could interfere with other files.
482 : * Wallet init code currently avoids creating "wallets" directories itself
483 : * for backwards compatibility, but this be changed in the future and
484 : * wallet code here could go away (#16220).
485 : */
486 3114 : auto path{GetDataDir(false)};
487 3114 : if (!fs::exists(path)) {
488 0 : fs::create_directories(path / "wallets");
489 0 : }
490 3114 : path = GetDataDir(true);
491 3114 : if (!fs::exists(path)) {
492 806 : fs::create_directories(path / "wallets");
493 806 : }
494 3114 : }
495 :
496 4948 : void ArgsManager::ClearPathCache()
497 : {
498 4948 : LOCK(cs_args);
499 :
500 4948 : m_cached_datadir_path = fs::path();
501 4948 : m_cached_network_datadir_path = fs::path();
502 4948 : m_cached_blocks_path = fs::path();
503 4948 : }
504 :
505 127 : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
506 : {
507 127 : Command ret;
508 127 : LOCK(cs_args);
509 127 : auto it = m_command.begin();
510 127 : if (it == m_command.end()) {
511 : // No command was passed
512 4 : return std::nullopt;
513 : }
514 123 : if (!m_accept_any_command) {
515 : // The registered command
516 123 : ret.command = *(it++);
517 123 : }
518 130 : while (it != m_command.end()) {
519 : // The unregistered command and args (if any)
520 7 : ret.args.push_back(*(it++));
521 : }
522 123 : return ret;
523 127 : }
524 :
525 329711 : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
526 : {
527 329711 : std::vector<std::string> result;
528 449551 : for (const util::SettingsValue& value : GetSettingsList(strArg)) {
529 119840 : result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
530 : }
531 329711 : return result;
532 329711 : }
533 :
534 550278 : bool ArgsManager::IsArgSet(const std::string& strArg) const
535 : {
536 550278 : return !GetSetting(strArg).isNull();
537 0 : }
538 :
539 3114 : bool ArgsManager::InitSettings(std::string& error)
540 : {
541 3114 : EnsureDataDir();
542 3114 : if (!GetSettingsPath()) {
543 4 : return true; // Do nothing if settings file disabled.
544 : }
545 :
546 3110 : std::vector<std::string> errors;
547 3110 : if (!ReadSettingsFile(&errors)) {
548 6 : error = strprintf("Failed loading settings file:\n%s\n", MakeUnorderedList(errors));
549 6 : return false;
550 : }
551 3104 : if (!WriteSettingsFile(&errors)) {
552 0 : error = strprintf("Failed saving settings file:\n%s\n", MakeUnorderedList(errors));
553 0 : return false;
554 : }
555 3104 : return true;
556 3114 : }
557 :
558 13701 : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
559 : {
560 13701 : fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
561 13701 : if (settings.empty()) {
562 4 : return false;
563 : }
564 13697 : if (backup) {
565 0 : settings += ".bak";
566 0 : }
567 13697 : if (filepath) {
568 10587 : *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
569 10587 : }
570 13697 : return true;
571 13701 : }
572 :
573 7 : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
574 : {
575 14 : for (const auto& error : errors) {
576 7 : if (error_out) {
577 6 : error_out->emplace_back(error);
578 6 : } else {
579 1 : LogPrintf("%s\n", error);
580 : }
581 : }
582 7 : }
583 :
584 3111 : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
585 : {
586 3111 : fs::path path;
587 3111 : if (!GetSettingsPath(&path, /* temp= */ false)) {
588 0 : return true; // Do nothing if settings file disabled.
589 : }
590 :
591 3111 : LOCK(cs_args);
592 3111 : m_settings.rw_settings.clear();
593 3111 : std::vector<std::string> read_errors;
594 3111 : if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
595 6 : SaveErrors(read_errors, errors);
596 6 : return false;
597 : }
598 3821 : for (const auto& setting : m_settings.rw_settings) {
599 716 : KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
600 716 : if (!GetArgFlags('-' + key.name)) {
601 13 : LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
602 13 : }
603 716 : }
604 3105 : return true;
605 3111 : }
606 :
607 3738 : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
608 : {
609 3738 : fs::path path, path_tmp;
610 3738 : if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
611 0 : throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
612 : }
613 :
614 3738 : LOCK(cs_args);
615 3738 : std::vector<std::string> write_errors;
616 3738 : if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
617 0 : SaveErrors(write_errors, errors);
618 0 : return false;
619 : }
620 3738 : if (!RenameOver(path_tmp, path)) {
621 1 : SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
622 1 : return false;
623 : }
624 3737 : return true;
625 3738 : }
626 :
627 0 : util::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
628 : {
629 0 : LOCK(cs_args);
630 0 : return util::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
631 : /*ignore_nonpersistent=*/true, /*get_chain_name=*/false);
632 0 : }
633 :
634 96943 : bool ArgsManager::IsArgNegated(const std::string& strArg) const
635 : {
636 96943 : return GetSetting(strArg).isFalse();
637 0 : }
638 :
639 280269 : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
640 : {
641 280269 : const util::SettingsValue value = GetSetting(strArg);
642 280269 : return SettingToString(value, strDefault);
643 280269 : }
644 :
645 280269 : std::string SettingToString(const util::SettingsValue& value, const std::string& strDefault)
646 : {
647 280269 : return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.isNum() ? value.getValStr() : value.get_str();
648 : }
649 :
650 1910015 : int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
651 : {
652 1910015 : const util::SettingsValue value = GetSetting(strArg);
653 1910015 : return SettingToInt(value, nDefault);
654 1910015 : }
655 :
656 1910016 : int64_t SettingToInt(const util::SettingsValue& value, int64_t nDefault)
657 : {
658 1910016 : return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.getInt<int64_t>() : LocaleIndependentAtoi<int64_t>(value.get_str());
659 : }
660 :
661 8217588 : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
662 : {
663 8217588 : const util::SettingsValue value = GetSetting(strArg);
664 8217588 : return SettingToBool(value, fDefault);
665 8217588 : }
666 :
667 8217624 : bool SettingToBool(const util::SettingsValue& value, bool fDefault)
668 : {
669 8217624 : return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
670 : }
671 :
672 39624 : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
673 : {
674 39624 : LOCK(cs_args);
675 39624 : if (IsArgSet(strArg)) return false;
676 5513 : ForceSetArg(strArg, strValue);
677 5513 : return true;
678 39624 : }
679 :
680 12250 : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
681 : {
682 12250 : if (fValue)
683 7555 : return SoftSetArg(strArg, std::string("1"));
684 : else
685 4695 : return SoftSetArg(strArg, std::string("0"));
686 12250 : }
687 :
688 33635 : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
689 : {
690 33635 : LOCK(cs_args);
691 33635 : m_settings.forced_settings[SettingName(strArg)] = strValue;
692 33635 : }
693 :
694 821 : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
695 : {
696 821 : Assert(cmd.find('=') == std::string::npos);
697 821 : Assert(cmd.at(0) != '-');
698 :
699 821 : LOCK(cs_args);
700 821 : m_accept_any_command = false; // latch to false
701 821 : std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
702 821 : auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
703 821 : Assert(ret.second); // Fail on duplicate commands
704 821 : }
705 :
706 1105210 : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
707 : {
708 1105210 : Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
709 :
710 : // Split arg name from its help param
711 1105210 : size_t eq_index = name.find('=');
712 1105210 : if (eq_index == std::string::npos) {
713 394272 : eq_index = name.size();
714 394272 : }
715 1105210 : std::string arg_name = name.substr(0, eq_index);
716 :
717 1105210 : LOCK(cs_args);
718 1105210 : std::map<std::string, Arg>& arg_map = m_available_args[cat];
719 1105210 : auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
720 1105210 : assert(ret.second); // Make sure an insertion actually happened
721 :
722 1105210 : if (flags & ArgsManager::NETWORK_ONLY) {
723 31505 : m_network_only_args.emplace(arg_name);
724 31505 : }
725 1105210 : }
726 :
727 8984 : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
728 : {
729 208824 : for (const std::string& name : names) {
730 199840 : AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
731 : }
732 8984 : }
733 :
734 2 : std::string ArgsManager::GetHelpMessage() const
735 : {
736 2 : const bool show_debug = GetBoolArg("-help-debug", false);
737 :
738 2 : std::string usage;
739 2 : LOCK(cs_args);
740 32 : for (const auto& arg_map : m_available_args) {
741 32 : switch(arg_map.first) {
742 : case OptionsCategory::OPTIONS:
743 2 : usage += HelpMessageGroup("Options:");
744 2 : break;
745 : case OptionsCategory::CONNECTION:
746 2 : usage += HelpMessageGroup("Connection options:");
747 2 : break;
748 : case OptionsCategory::INDEXING:
749 2 : usage += HelpMessageGroup("Indexing options:");
750 2 : break;
751 : case OptionsCategory::MASTERNODE:
752 2 : usage += HelpMessageGroup("Masternode options:");
753 2 : break;
754 : case OptionsCategory::STATSD:
755 2 : usage += HelpMessageGroup("Statsd options:");
756 2 : break;
757 : case OptionsCategory::ZMQ:
758 0 : usage += HelpMessageGroup("ZeroMQ notification options:");
759 0 : break;
760 : case OptionsCategory::DEBUG_TEST:
761 2 : usage += HelpMessageGroup("Debugging/Testing options:");
762 2 : break;
763 : case OptionsCategory::NODE_RELAY:
764 2 : usage += HelpMessageGroup("Node relay options:");
765 2 : break;
766 : case OptionsCategory::BLOCK_CREATION:
767 2 : usage += HelpMessageGroup("Block creation options:");
768 2 : break;
769 : case OptionsCategory::RPC:
770 2 : usage += HelpMessageGroup("RPC server options:");
771 2 : break;
772 : case OptionsCategory::WALLET:
773 2 : usage += HelpMessageGroup("Wallet options:");
774 2 : break;
775 : case OptionsCategory::WALLET_FEE:
776 2 : usage += HelpMessageGroup("Wallet fee options:");
777 2 : break;
778 : case OptionsCategory::WALLET_HD:
779 2 : usage += HelpMessageGroup("HD wallet options:");
780 2 : break;
781 : case OptionsCategory::WALLET_COINJOIN:
782 2 : usage += HelpMessageGroup("CoinJoin options:");
783 2 : break;
784 : case OptionsCategory::WALLET_DEBUG_TEST:
785 2 : if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
786 2 : break;
787 : case OptionsCategory::CHAINPARAMS:
788 2 : usage += HelpMessageGroup("Chain selection options:");
789 2 : break;
790 : case OptionsCategory::GUI:
791 0 : usage += HelpMessageGroup("UI Options:");
792 0 : break;
793 : case OptionsCategory::COMMANDS:
794 0 : usage += HelpMessageGroup("Commands:");
795 0 : break;
796 : case OptionsCategory::REGISTER_COMMANDS:
797 0 : usage += HelpMessageGroup("Register Commands:");
798 0 : break;
799 : default:
800 2 : break;
801 : }
802 :
803 : // When we get to the hidden options, stop
804 32 : if (arg_map.first == OptionsCategory::HIDDEN) break;
805 :
806 474 : for (const auto& arg : arg_map.second) {
807 444 : if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
808 342 : std::string name;
809 342 : if (arg.second.m_help_param.empty()) {
810 114 : name = arg.first;
811 114 : } else {
812 228 : name = arg.first + arg.second.m_help_param;
813 : }
814 342 : usage += HelpMessageOpt(name, arg.second.m_help_text);
815 342 : }
816 : }
817 : }
818 2 : return usage;
819 2 : }
820 :
821 3347 : void ArgsManager::ForceRemoveArg(const std::string& strArg)
822 : {
823 3347 : LOCK(cs_args);
824 3347 : const auto& ov = m_settings.forced_settings.find(strArg);
825 3347 : if (ov != m_settings.forced_settings.end()) {
826 91 : m_settings.forced_settings.erase(ov);
827 91 : }
828 :
829 16735 : for (const auto& network : { CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::REGTEST, CBaseChainParams::DEVNET }) {
830 13388 : if (auto* section = util::FindKey(m_settings.ro_config, network)) {
831 3241 : if (util::FindKey(*section, strArg)) {
832 0 : section->erase(strArg);
833 0 : }
834 3241 : }
835 : }
836 3347 : }
837 :
838 4544 : bool HelpRequested(const ArgsManager& args)
839 : {
840 4544 : return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
841 0 : }
842 :
843 5195 : void SetupHelpOptions(ArgsManager& args)
844 : {
845 5195 : args.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS);
846 5195 : args.AddHiddenArgs({"-h", "-help"});
847 5195 : }
848 :
849 : static const int screenWidth = 79;
850 : static const int optIndent = 2;
851 : static const int msgIndent = 7;
852 :
853 28 : std::string HelpMessageGroup(const std::string &message) {
854 28 : return std::string(message) + std::string("\n\n");
855 0 : }
856 :
857 342 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
858 1026 : return std::string(optIndent,' ') + std::string(option) +
859 1026 : std::string("\n") + std::string(msgIndent,' ') +
860 684 : FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
861 342 : std::string("\n\n");
862 0 : }
863 :
864 0 : void PrintExceptionContinue(const std::exception_ptr pex, const char* pszExceptionOrigin)
865 : {
866 0 : std::string message = strprintf("\"%s\" raised an exception\n%s", pszExceptionOrigin, GetPrettyExceptionStr(pex));
867 0 : LogPrintf("\n\n************************\n%s\n", message);
868 0 : tfm::format(std::cerr, "\n\n************************\n%s\n", message);
869 0 : }
870 :
871 3023 : fs::path GetDefaultDataDir()
872 : {
873 : // Windows: C:\Users\Username\AppData\Roaming\DashCore
874 : // macOS: ~/Library/Application Support/DashCore
875 : // Unix-like: ~/.dashcore
876 : #ifdef WIN32
877 : // Windows
878 : return GetSpecialFolderPath(CSIDL_APPDATA) / "DashCore";
879 : #else
880 3023 : fs::path pathRet;
881 3023 : char* pszHome = getenv("HOME");
882 3023 : if (pszHome == nullptr || strlen(pszHome) == 0)
883 0 : pathRet = fs::path("/");
884 : else
885 3023 : pathRet = fs::path(pszHome);
886 : #ifdef MAC_OSX
887 : // macOS
888 3023 : return pathRet / "Library/Application Support/DashCore";
889 : #else
890 : // Unix-like
891 : return pathRet / ".dashcore";
892 : #endif
893 : #endif
894 3023 : }
895 :
896 0 : fs::path GetBackupsDir()
897 : {
898 0 : return gArgs.GetBackupsDirPath();
899 : }
900 :
901 8778 : bool CheckDataDirOption()
902 : {
903 8778 : const fs::path datadir{gArgs.GetPathArg("-datadir")};
904 8778 : return datadir.empty() || fs::is_directory(fs::absolute(datadir));
905 8778 : }
906 :
907 7408 : fs::path GetConfigFile(const fs::path& configuration_file_path)
908 : {
909 7408 : return AbsPathForConfigVal(configuration_file_path, /*net_specific=*/false);
910 : }
911 :
912 32471 : static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
913 : {
914 32471 : std::string str, prefix;
915 : std::string::size_type pos;
916 32471 : int linenr = 1;
917 230825 : while (std::getline(stream, str)) {
918 198364 : bool used_hash = false;
919 198364 : if ((pos = str.find('#')) != std::string::npos) {
920 6 : str = str.substr(0, pos);
921 6 : used_hash = true;
922 6 : }
923 : const static std::string pattern = " \t\r\n";
924 198364 : str = TrimString(str, pattern);
925 198364 : if (!str.empty()) {
926 198361 : if (*str.begin() == '[' && *str.rbegin() == ']') {
927 4345 : const std::string section = str.substr(1, str.size() - 2);
928 4345 : sections.emplace_back(SectionInfo{section, filepath, linenr});
929 4345 : prefix = section + '.';
930 198361 : } else if (*str.begin() == '-') {
931 2 : error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
932 2 : return false;
933 194014 : } else if ((pos = str.find('=')) != std::string::npos) {
934 194012 : std::string name = prefix + TrimString(std::string_view{str}.substr(0, pos), pattern);
935 194012 : std::string_view value = TrimStringView(std::string_view{str}.substr(pos + 1), pattern);
936 194012 : if (used_hash && name.find("rpcpassword") != std::string::npos) {
937 6 : error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
938 6 : return false;
939 : }
940 194006 : options.emplace_back(name, value);
941 194006 : if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
942 51411 : sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
943 51411 : }
944 194012 : } else {
945 2 : error = strprintf("parse error on line %i: %s", linenr, str);
946 2 : if (str.size() >= 2 && str.substr(0, 2) == "no") {
947 2 : error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
948 2 : }
949 2 : return false;
950 : }
951 198351 : }
952 198354 : ++linenr;
953 : }
954 32461 : return true;
955 32471 : }
956 :
957 193994 : bool IsConfSupported(KeyInfo& key, std::string& error) {
958 193994 : if (key.name == "conf") {
959 4 : error = "conf cannot be set in the configuration file; use includeconf= if you want to include additional config files";
960 4 : return false;
961 : }
962 193990 : if (key.name == "reindex") {
963 : // reindex can be set in a config file but it is strongly discouraged as this will cause the node to reindex on
964 : // every restart. Allow the config but throw a warning
965 2 : LogPrintf("Warning: reindex=1 is set in the configuration file, which will significantly slow down startup. Consider removing or commenting out this option for better performance, unless there is currently a condition which makes rebuilding the indexes necessary\n");
966 2 : return true;
967 : }
968 193988 : return true;
969 193994 : }
970 :
971 32471 : bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
972 : {
973 32471 : LOCK(cs_args);
974 32471 : std::vector<std::pair<std::string, std::string>> options;
975 32471 : if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
976 10 : return false;
977 : }
978 226451 : for (const std::pair<std::string, std::string>& option : options) {
979 193994 : KeyInfo key = InterpretKey(option.first);
980 193994 : std::optional<unsigned int> flags = GetArgFlags('-' + key.name);
981 193994 : if (!IsConfSupported(key, error)) return false;
982 193990 : if (flags) {
983 172586 : std::optional<util::SettingsValue> value = InterpretValue(key, &option.second, *flags, error);
984 172586 : if (!value) {
985 0 : return false;
986 : }
987 172586 : m_settings.ro_config[key.section][key.name].push_back(*value);
988 172586 : } else {
989 21404 : if (ignore_invalid_keys) {
990 21404 : LogPrintf("Ignoring unknown configuration value %s\n", option.first);
991 21404 : } else {
992 0 : error = strprintf("Invalid configuration value %s", option.first);
993 0 : return false;
994 : }
995 : }
996 193994 : }
997 32457 : return true;
998 32471 : }
999 :
1000 4335 : fs::path ArgsManager::GetConfigFilePath() const
1001 : {
1002 4335 : return GetConfigFile(GetPathArg("-conf", BITCOIN_CONF_FILENAME));
1003 0 : }
1004 :
1005 4335 : bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
1006 : {
1007 : {
1008 4335 : LOCK(cs_args);
1009 4335 : m_settings.ro_config.clear();
1010 4335 : m_config_sections.clear();
1011 4335 : }
1012 :
1013 4335 : const auto conf_path{GetConfigFilePath()};
1014 4335 : std::ifstream stream{conf_path};
1015 :
1016 : // not ok to have a config file specified that cannot be opened
1017 4335 : if (IsArgSet("-conf") && !stream.good()) {
1018 2 : error = strprintf("specified config file \"%s\" could not be opened.", fs::PathToString(conf_path));
1019 2 : return false;
1020 : }
1021 : // ok to not have a config file
1022 4333 : if (stream.good()) {
1023 4333 : if (!ReadConfigStream(stream, fs::PathToString(conf_path), error, ignore_invalid_keys)) {
1024 2 : return false;
1025 : }
1026 : // `-includeconf` cannot be included in the command line arguments except
1027 : // as `-noincludeconf` (which indicates that no included conf file should be used).
1028 4331 : bool use_conf_file{true};
1029 : {
1030 4331 : LOCK(cs_args);
1031 4331 : if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
1032 : // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
1033 0 : assert(util::SettingsSpan(*includes).last_negated());
1034 0 : use_conf_file = false;
1035 0 : }
1036 4331 : }
1037 4331 : if (use_conf_file) {
1038 4331 : std::string chain_id = GetChainName();
1039 4331 : std::vector<std::string> conf_file_names;
1040 :
1041 21627 : auto add_includes = [&](const std::string& network, size_t skip = 0) {
1042 17296 : size_t num_values = 0;
1043 17296 : LOCK(cs_args);
1044 17296 : if (auto* section = util::FindKey(m_settings.ro_config, network)) {
1045 17292 : if (auto* values = util::FindKey(*section, "includeconf")) {
1046 108 : for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
1047 48 : conf_file_names.push_back((*values)[i].get_str());
1048 48 : }
1049 60 : num_values = values->size();
1050 60 : }
1051 17292 : }
1052 17296 : return num_values;
1053 17296 : };
1054 :
1055 : // We haven't set m_network yet (that happens in SelectParams()), so manually check
1056 : // for network.includeconf args.
1057 4331 : const size_t chain_includes = add_includes(chain_id);
1058 4331 : const size_t default_includes = add_includes({});
1059 :
1060 4363 : for (const std::string& conf_file_name : conf_file_names) {
1061 46 : std::ifstream conf_file_stream{GetConfigFile(fs::PathFromString(conf_file_name))};
1062 46 : if (conf_file_stream.good()) {
1063 44 : if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
1064 12 : return false;
1065 : }
1066 32 : LogPrintf("Included configuration file %s\n", conf_file_name);
1067 32 : } else {
1068 2 : error = "Failed to include configuration file " + conf_file_name;
1069 2 : return false;
1070 : }
1071 46 : }
1072 :
1073 : // Warn about recursive -includeconf
1074 4317 : conf_file_names.clear();
1075 4317 : add_includes(chain_id, /* skip= */ chain_includes);
1076 4317 : add_includes({}, /* skip= */ default_includes);
1077 4317 : std::string chain_id_final = GetChainName();
1078 4317 : if (chain_id_final != chain_id) {
1079 : // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
1080 0 : add_includes(chain_id_final);
1081 0 : }
1082 4319 : for (const std::string& conf_file_name : conf_file_names) {
1083 2 : tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
1084 : }
1085 4331 : }
1086 4317 : } else {
1087 : // Create an empty dash.conf if it does not exist
1088 0 : std::ofstream configFile{GetConfigFile(conf_path), std::ios_base::app};
1089 0 : if (!configFile.good())
1090 0 : return false;
1091 0 : configFile.close();
1092 0 : return true; // Nothing to read, so just return
1093 0 : }
1094 :
1095 : // If datadir is changed in .conf file:
1096 4317 : gArgs.ClearPathCache();
1097 4317 : if (!CheckDataDirOption()) {
1098 2 : error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
1099 2 : return false;
1100 : }
1101 4315 : return true;
1102 4335 : }
1103 :
1104 18289 : std::string ArgsManager::GetChainName() const
1105 : {
1106 73156 : auto get_net = [&](const std::string& arg, bool interpret_bool = true) {
1107 54867 : LOCK(cs_args);
1108 54867 : util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
1109 : /* ignore_default_section_config= */ false,
1110 : /*ignore_nonpersistent=*/false,
1111 : /* get_chain_name= */ true);
1112 54867 : return value.isNull() ? false : value.isBool() ? value.get_bool() : (!interpret_bool || InterpretBool(value.get_str()));
1113 54867 : };
1114 :
1115 18289 : const bool fRegTest = get_net("-regtest");
1116 18289 : const bool fDevNet = get_net("-devnet", false);
1117 18289 : const bool fTestNet = get_net("-testnet");
1118 18289 : const bool is_chain_arg_set = IsArgSet("-chain");
1119 :
1120 18289 : int nameParamsCount = (fRegTest ? 1 : 0) + (fDevNet ? 1 : 0) + (fTestNet ? 1 : 0) + (is_chain_arg_set ? 1 : 0);
1121 18289 : if (nameParamsCount > 1)
1122 187 : throw std::runtime_error("Only one of -regtest, -testnet, -devnet or -chain can be used.");
1123 :
1124 18102 : if (fRegTest)
1125 16338 : return CBaseChainParams::REGTEST;
1126 1764 : if (fDevNet) {
1127 16 : return CBaseChainParams::DEVNET;
1128 : }
1129 1748 : if (fTestNet)
1130 370 : return CBaseChainParams::TESTNET;
1131 :
1132 1378 : return GetArg("-chain", CBaseChainParams::MAIN);
1133 18102 : }
1134 :
1135 8792 : std::string ArgsManager::GetDevNetName() const
1136 : {
1137 8792 : std::string devNetName = GetArg("-devnet", "");
1138 8792 : return "devnet" + (devNetName.empty() ? "" : "-" + devNetName);
1139 8792 : }
1140 :
1141 :
1142 9072 : void ArgsManager::logArgsPrefix(
1143 : const std::string& prefix,
1144 : const std::string& section,
1145 : const std::map<std::string, std::vector<util::SettingsValue>>& args) const
1146 : {
1147 9072 : std::string section_str = section.empty() ? "" : "[" + section + "] ";
1148 109882 : for (const auto& arg : args) {
1149 211723 : for (const auto& value : arg.second) {
1150 110913 : std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
1151 110913 : if (flags) {
1152 110913 : std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
1153 110913 : LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
1154 110913 : }
1155 : }
1156 : }
1157 9072 : }
1158 :
1159 3024 : void ArgsManager::LogArgs() const
1160 : {
1161 3024 : LOCK(cs_args);
1162 9072 : for (const auto& section : m_settings.ro_config) {
1163 6048 : logArgsPrefix("Config file arg:", section.first, section.second);
1164 : }
1165 3693 : for (const auto& setting : m_settings.rw_settings) {
1166 669 : LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1167 : }
1168 3024 : logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1169 3024 : }
1170 :
1171 11387645 : bool ArgsManager::UseDefaultSection(const std::string& arg) const
1172 : {
1173 11387645 : return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
1174 : }
1175 :
1176 11055157 : util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
1177 : {
1178 11055157 : LOCK(cs_args);
1179 11055157 : return util::GetSetting(
1180 11055157 : m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
1181 : /*ignore_nonpersistent=*/false, /*get_chain_name=*/false);
1182 11055157 : }
1183 :
1184 332488 : std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
1185 : {
1186 332488 : LOCK(cs_args);
1187 332488 : return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
1188 332488 : }
1189 :
1190 15990 : bool RenameOver(fs::path src, fs::path dest)
1191 : {
1192 15990 : std::error_code error;
1193 15990 : fs::rename(src, dest, error);
1194 15990 : return !error;
1195 : }
1196 :
1197 : /**
1198 : * Ignores exceptions thrown by create_directories if the requested directory exists.
1199 : * Specifically handles case where path p exists, but it wasn't possible for the user to
1200 : * write to the parent directory.
1201 : */
1202 27883 : bool TryCreateDirectories(const fs::path& p)
1203 : {
1204 : try
1205 : {
1206 27883 : return fs::create_directories(p);
1207 12 : } catch (const fs::filesystem_error&) {
1208 6 : if (!fs::exists(p) || !fs::is_directory(p))
1209 0 : throw;
1210 6 : }
1211 :
1212 : // create_directories didn't create the directory, it had to have existed already
1213 0 : return false;
1214 27889 : }
1215 :
1216 28732 : bool FileCommit(FILE *file)
1217 : {
1218 28732 : if (fflush(file) != 0) { // harmless if redundantly called
1219 0 : LogPrintf("fflush failed: %s\n", SysErrorString(errno));
1220 0 : return false;
1221 : }
1222 : #ifdef WIN32
1223 : HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1224 : if (FlushFileBuffers(hFile) == 0) {
1225 : LogPrintf("FlushFileBuffers failed: %s\n", Win32ErrorString(GetLastError()));
1226 : return false;
1227 : }
1228 : #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1229 28732 : if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1230 0 : LogPrintf("fcntl F_FULLFSYNC failed: %s\n", SysErrorString(errno));
1231 0 : return false;
1232 : }
1233 : #elif HAVE_FDATASYNC
1234 : if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1235 : LogPrintf("fdatasync failed: %d\n", SysErrorString(errno));
1236 : return false;
1237 : }
1238 : #else
1239 : if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1240 : LogPrintf("fsync failed: %d\n", SysErrorString(errno));
1241 : return false;
1242 : }
1243 : #endif
1244 28732 : return true;
1245 28732 : }
1246 :
1247 15098 : void DirectoryCommit(const fs::path &dirname)
1248 : {
1249 : #ifndef WIN32
1250 15098 : FILE* file = fsbridge::fopen(dirname, "r");
1251 15098 : if (file) {
1252 15098 : fsync(fileno(file));
1253 15098 : fclose(file);
1254 15098 : }
1255 : #endif
1256 15098 : }
1257 :
1258 57 : bool TruncateFile(FILE *file, unsigned int length) {
1259 : #if defined(WIN32)
1260 : return _chsize(_fileno(file), length) == 0;
1261 : #else
1262 57 : return ftruncate(fileno(file), length) == 0;
1263 : #endif
1264 : }
1265 :
1266 : /**
1267 : * this function tries to raise the file descriptor limit to the requested number.
1268 : * It returns the actual file descriptor limit (which may be more or less than nMinFD)
1269 : */
1270 3721 : int RaiseFileDescriptorLimit(int nMinFD) {
1271 : #if defined(WIN32)
1272 : return 2048;
1273 : #else
1274 : struct rlimit limitFD;
1275 3721 : if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1276 3721 : if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1277 0 : limitFD.rlim_cur = nMinFD;
1278 0 : if (limitFD.rlim_cur > limitFD.rlim_max)
1279 0 : limitFD.rlim_cur = limitFD.rlim_max;
1280 0 : setrlimit(RLIMIT_NOFILE, &limitFD);
1281 0 : getrlimit(RLIMIT_NOFILE, &limitFD);
1282 0 : }
1283 3721 : return limitFD.rlim_cur;
1284 : }
1285 0 : return nMinFD; // getrlimit failed, assume it's fine
1286 : #endif
1287 3721 : }
1288 :
1289 : /**
1290 : * this function tries to make a particular range of a file allocated (corresponding to disk space)
1291 : * it is advisory, and the range specified in the arguments will never contain live data
1292 : */
1293 7314 : void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1294 : #if defined(WIN32)
1295 : // Windows-specific version
1296 : HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1297 : LARGE_INTEGER nFileSize;
1298 : int64_t nEndPos = (int64_t)offset + length;
1299 : nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1300 : nFileSize.u.HighPart = nEndPos >> 32;
1301 : SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1302 : SetEndOfFile(hFile);
1303 : #elif defined(MAC_OSX)
1304 : // OSX specific version
1305 : // NOTE: Contrary to other OS versions, the OSX version assumes that
1306 : // NOTE: offset is the size of the file.
1307 : fstore_t fst;
1308 7314 : fst.fst_flags = F_ALLOCATECONTIG;
1309 7314 : fst.fst_posmode = F_PEOFPOSMODE;
1310 7314 : fst.fst_offset = 0;
1311 7314 : fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
1312 7314 : fst.fst_bytesalloc = 0;
1313 7314 : if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1314 0 : fst.fst_flags = F_ALLOCATEALL;
1315 0 : fcntl(fileno(file), F_PREALLOCATE, &fst);
1316 0 : }
1317 7314 : ftruncate(fileno(file), static_cast<off_t>(offset) + length);
1318 : #else
1319 : #if defined(HAVE_POSIX_FALLOCATE)
1320 : // Version using posix_fallocate
1321 : off_t nEndPos = (off_t)offset + length;
1322 : if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1323 : #endif
1324 : // Fallback version
1325 : // TODO: just write one byte per block
1326 : static const char buf[65536] = {};
1327 : if (fseek(file, offset, SEEK_SET)) {
1328 : return;
1329 : }
1330 : while (length > 0) {
1331 : unsigned int now = 65536;
1332 : if (length < now)
1333 : now = length;
1334 : fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1335 : length -= now;
1336 : }
1337 : #endif
1338 7314 : }
1339 :
1340 : #ifdef WIN32
1341 : fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1342 : {
1343 : WCHAR pszPath[MAX_PATH] = L"";
1344 :
1345 : if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1346 : {
1347 : return fs::path(pszPath);
1348 : }
1349 :
1350 : LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1351 : return fs::path("");
1352 : }
1353 : #endif
1354 :
1355 : #ifndef WIN32
1356 80 : std::string ShellEscape(const std::string& arg)
1357 : {
1358 80 : std::string escaped = arg;
1359 80 : ReplaceAll(escaped, "'", "'\"'\"'");
1360 80 : return "'" + escaped + "'";
1361 80 : }
1362 : #endif
1363 :
1364 : #if HAVE_SYSTEM
1365 566 : void runCommand(const std::string& strCommand)
1366 : {
1367 566 : if (strCommand.empty()) return;
1368 : #ifndef WIN32
1369 566 : int nErr = ::system(strCommand.c_str());
1370 : #else
1371 : int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1372 : #endif
1373 566 : if (nErr)
1374 0 : LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1375 566 : }
1376 : #endif
1377 :
1378 4389 : void RenameThreadPool(ctpl::thread_pool& tp, const char* baseName)
1379 : {
1380 4389 : auto cond = std::make_shared<std::condition_variable>();
1381 4389 : auto mutex = std::make_shared<std::mutex>();
1382 4389 : std::atomic<int> doneCnt(0);
1383 4389 : std::map<int, std::future<void> > futures;
1384 :
1385 21945 : for (int i = 0; i < tp.size(); i++) {
1386 35050 : futures[i] = tp.push([baseName, i, cond, mutex, &doneCnt](int threadId) {
1387 17494 : util::ThreadRename(strprintf("%s-%d", baseName, i));
1388 17494 : std::unique_lock<std::mutex> l(*mutex);
1389 17494 : doneCnt++;
1390 17494 : cond->wait(l);
1391 17494 : });
1392 17556 : }
1393 :
1394 4389 : do {
1395 : // Always sleep to let all threads acquire locks
1396 4391 : UninterruptibleSleep(std::chrono::milliseconds{10});
1397 : // `doneCnt` should be at least `futures.size()` if tp size was increased (for whatever reason),
1398 : // or at least `tp.size()` if tp size was decreased and queue was cleared
1399 : // (which can happen on `stop()` if we were not fast enough to get all jobs to their threads).
1400 4391 : } while (uint64_t(doneCnt) < futures.size() && doneCnt < tp.size());
1401 :
1402 4389 : cond->notify_all();
1403 :
1404 : // Make sure no one is left behind, just in case
1405 21945 : for (auto& pair : futures) {
1406 17556 : auto& f = pair.second;
1407 17556 : if (f.valid() && f.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
1408 0 : LogPrintf("%s: %s-%d timed out\n", __func__, baseName, pair.first);
1409 : // Notify everyone again
1410 0 : cond->notify_all();
1411 0 : break;
1412 : }
1413 : }
1414 4389 : }
1415 :
1416 5195 : void SetupEnvironment()
1417 : {
1418 : #ifdef HAVE_MALLOPT_ARENA_MAX
1419 : // glibc-specific: On 32-bit systems set the number of arenas to 1.
1420 : // By default, since glibc 2.10, the C library will create up to two heap
1421 : // arenas per core. This is known to cause excessive virtual address space
1422 : // usage in our usage. Work around it by setting the maximum number of
1423 : // arenas to 1.
1424 : if (sizeof(void*) == 4) {
1425 : mallopt(M_ARENA_MAX, 1);
1426 : }
1427 : #endif
1428 : // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1429 : // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
1430 : #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1431 : try {
1432 : std::locale(""); // Raises a runtime error if current locale is invalid
1433 : } catch (const std::runtime_error&) {
1434 : setenv("LC_ALL", "C.UTF-8", 1);
1435 : }
1436 : #elif defined(WIN32)
1437 : // Set the default input/output charset is utf-8
1438 : SetConsoleCP(CP_UTF8);
1439 : SetConsoleOutputCP(CP_UTF8);
1440 : #endif
1441 :
1442 : #ifndef WIN32
1443 5195 : constexpr mode_t private_umask = 0077;
1444 5195 : umask(private_umask);
1445 : #endif
1446 5195 : }
1447 :
1448 4928 : bool SetupNetworking()
1449 : {
1450 : #ifdef WIN32
1451 : // Initialize Windows Sockets
1452 : WSADATA wsadata;
1453 : int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1454 : if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1455 : return false;
1456 : #endif
1457 4928 : return true;
1458 : }
1459 :
1460 13478 : int GetNumCores()
1461 : {
1462 13478 : return std::thread::hardware_concurrency();
1463 : }
1464 :
1465 : // Obtain the application startup time (used for uptime calculation)
1466 2 : int64_t GetStartupTime()
1467 : {
1468 2 : return nStartupTime;
1469 : }
1470 :
1471 27532 : fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1472 : {
1473 27532 : if (path.is_absolute()) {
1474 60 : return path;
1475 : }
1476 27472 : return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path);
1477 27532 : }
1478 :
1479 2831 : void ScheduleBatchPriority()
1480 : {
1481 : #ifdef SCHED_BATCH
1482 : const static sched_param param{};
1483 : const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, ¶m);
1484 : if (rc != 0) {
1485 : LogPrintf("Failed to pthread_setschedparam: %s\n", SysErrorString(rc));
1486 : }
1487 : #endif
1488 2831 : }
1489 :
1490 : namespace util {
1491 : #ifdef WIN32
1492 : WinCmdLineArgs::WinCmdLineArgs()
1493 : {
1494 : wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1495 : std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1496 : argv = new char*[argc];
1497 : args.resize(argc);
1498 : for (int i = 0; i < argc; i++) {
1499 : args[i] = utf8_cvt.to_bytes(wargv[i]);
1500 : argv[i] = &*args[i].begin();
1501 : }
1502 : LocalFree(wargv);
1503 : }
1504 :
1505 : WinCmdLineArgs::~WinCmdLineArgs()
1506 : {
1507 : delete[] argv;
1508 : }
1509 :
1510 : std::pair<int, char**> WinCmdLineArgs::get()
1511 : {
1512 : return std::make_pair(argc, argv);
1513 : }
1514 : #endif
1515 : } // namespace util
|