Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
args.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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.
5
6#include <common/args.h>
7
8#include <chainparamsbase.h>
9#include <common/settings.h>
10#include <sync.h>
11#include <tinyformat.h>
12#include <univalue.h>
13#include <util/chaintype.h>
14#include <util/check.h>
15#include <util/fs.h>
16#include <util/fs_helpers.h>
17#include <util/log.h>
18#include <util/strencodings.h>
19#include <util/string.h>
20
21#ifdef WIN32
22#include <shlobj.h>
23#endif
24
25#include <algorithm>
26#include <cstdlib>
27#include <cstring>
28#include <list>
29#include <map>
30#include <optional>
31#include <stdexcept>
32#include <string>
33#include <utility>
34#include <variant>
35
36const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
37const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
38
40
56static bool InterpretBool(const std::string& strValue)
57{
58 if (strValue.empty())
59 return true;
61}
62
63static std::string SettingName(const std::string& arg)
64{
65 return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
66}
67
76KeyInfo InterpretKey(std::string key)
77{
78 KeyInfo result;
79 // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
80 size_t option_index = key.find('.');
81 if (option_index != std::string::npos) {
82 result.section = key.substr(0, option_index);
83 key.erase(0, option_index + 1);
84 }
85 if (key.starts_with("no")) {
86 key.erase(0, 2);
87 result.negated = true;
88 }
89 result.name = key;
90 return result;
91}
92
104std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
105 unsigned int flags, std::string& error)
106{
107 // Return negated settings as false values.
108 if (key.negated) {
110 error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
111 return std::nullopt;
112 }
113 // Double negatives like -nofoo=0 are supported (but discouraged)
114 if (value && !InterpretBool(*value)) {
115 LogWarning("Parsed potentially confusing double-negative -%s=%s", key.name, *value);
116 return true;
117 }
118 return false;
119 }
120 if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
121 error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
122 return std::nullopt;
123 }
124 return value ? *value : "";
125}
126
127// Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
128// #include class definitions for all members.
129// For example, m_settings has an internal dependency on univalue.
130ArgsManager::ArgsManager() = default;
131ArgsManager::~ArgsManager() = default;
132
133std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
134{
135 std::set<std::string> unsuitables;
136
137 LOCK(cs_args);
138
139 // if there's no section selected, don't worry
140 if (m_network.empty()) return std::set<std::string> {};
141
142 // if it's okay to use the default section for this network, don't worry
143 if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
144
145 for (const auto& arg : m_network_only_args) {
146 if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
147 unsuitables.insert(arg);
148 }
149 }
150 return unsuitables;
151}
152
153std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
154{
155 // Section names to be recognized in the config file.
156 static const std::set<std::string> available_sections{
162 };
163
164 LOCK(cs_args);
165 std::list<SectionInfo> unrecognized = m_config_sections;
166 std::erase_if(unrecognized, [](const SectionInfo& appeared) { return available_sections.contains(appeared.m_name); });
167 return unrecognized;
168}
169
170void ArgsManager::SelectConfigNetwork(const std::string& network)
171{
172 LOCK(cs_args);
173 m_network = network;
174}
175
176bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
177{
178 LOCK(cs_args);
179 m_settings.command_line_options.clear();
180
181 for (int i = 1; i < argc; i++) {
182 std::string key(argv[i]);
183
184#ifdef __APPLE__
185 // At the first time when a user gets the "App downloaded from the
186 // internet" warning, and clicks the Open button, macOS passes
187 // a unique process serial number (PSN) as -psn_... command-line
188 // argument, which we filter out.
189 if (key.starts_with("-psn_")) continue;
190#endif
191
192 if (key == "-") break; //bitcoin-tx using stdin
193 std::optional<std::string> val;
194 size_t is_index = key.find('=');
195 if (is_index != std::string::npos) {
196 val = key.substr(is_index + 1);
197 key.erase(is_index);
198 }
199#ifdef WIN32
200 key = ToLower(key);
201 if (key[0] == '/')
202 key[0] = '-';
203#endif
204
205 if (key[0] != '-') {
206 if (!m_accept_any_command && m_command.empty()) {
207 // The first non-dash arg is a registered command
208 std::optional<unsigned int> flags = GetArgFlags_(key);
209 if (!flags || !(*flags & ArgsManager::COMMAND)) {
210 error = strprintf("Invalid command '%s'", argv[i]);
211 return false;
212 }
213 }
214 m_command.push_back(key);
215 while (++i < argc) {
216 // The remaining args are command args
217 m_command.emplace_back(argv[i]);
218 }
219 break;
220 }
221
222 // Transform --foo to -foo
223 if (key.length() > 1 && key[1] == '-')
224 key.erase(0, 1);
225
226 // Transform -foo to foo
227 key.erase(0, 1);
229 std::optional<unsigned int> flags = GetArgFlags_('-' + keyinfo.name);
230
231 // Unknown command line options and command line options with dot
232 // characters (which are returned from InterpretKey with nonempty
233 // section strings) are not valid.
234 if (!flags || !keyinfo.section.empty()) {
235 error = strprintf("Invalid parameter %s", argv[i]);
236 return false;
237 }
238
239 std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
240 if (!value) return false;
241
242 m_settings.command_line_options[keyinfo.name].push_back(*value);
243 }
244
245 // we do not allow -includeconf from command line, only -noincludeconf
246 if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
248 // Range may be empty if -noincludeconf was passed
249 if (!values.empty()) {
250 error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
251 return false; // pick first value as example
252 }
253 }
254 return true;
255}
256
257std::optional<unsigned int> ArgsManager::GetArgFlags_(const std::string& name) const
258{
260 for (const auto& arg_map : m_available_args) {
261 const auto search = arg_map.second.find(name);
262 if (search != arg_map.second.end()) {
263 return search->second.m_flags;
264 }
265 }
266 return m_default_flags;
267}
268
269std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
270{
271 LOCK(cs_args);
272 return GetArgFlags_(name);
273}
274
275void ArgsManager::SetDefaultFlags(std::optional<unsigned int> flags)
276{
277 LOCK(cs_args);
279}
280
281fs::path ArgsManager::GetPathArg_(std::string arg, const fs::path& default_value) const
282{
284 const auto value = GetSetting_(arg);
285 if (value.isFalse()) return {};
286 std::string path_str = SettingToString(value).value_or("");
287 if (path_str.empty()) return default_value;
288 fs::path result = fs::PathFromString(path_str).lexically_normal();
289 // Remove trailing slash, if present.
290 return result.has_filename() ? result : result.parent_path();
291}
292
293fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
294{
295 LOCK(cs_args);
296 return GetPathArg_(std::move(arg), default_value);
297}
298
300{
301 LOCK(cs_args);
302 fs::path& path = m_cached_blocks_path;
303
304 // Cache the path to avoid calling fs::create_directories on every call of
305 // this function
306 if (!path.empty()) return path;
307
308 if (!GetSetting_("-blocksdir").isNull()) {
309 path = fs::absolute(GetPathArg_("-blocksdir"));
310 if (!fs::is_directory(path)) {
311 path = "";
312 return path;
313 }
314 } else {
315 path = GetDataDir(/*net_specific=*/false);
316 }
317
318 path /= fs::PathFromString(BaseParams().DataDir());
319 path /= "blocks";
320 fs::create_directories(path);
321 return path;
322}
323
325 LOCK(cs_args);
326 return GetDataDir(/*net_specific=*/false);
327}
328
330 LOCK(cs_args);
331 return GetDataDir(/*net_specific=*/true);
332}
333
335{
338
339 // Used cached path if available
340 if (!path.empty()) return path;
341
342 const fs::path datadir{GetPathArg_("-datadir")};
343 if (!datadir.empty()) {
344 path = fs::absolute(datadir);
345 if (!fs::is_directory(path)) {
346 path = "";
347 return path;
348 }
349 } else {
350 path = GetDefaultDataDir();
351 }
352
353 if (net_specific && !BaseParams().DataDir().empty()) {
354 path /= fs::PathFromString(BaseParams().DataDir());
355 }
356
357 return path;
358}
359
361{
362 LOCK(cs_args);
363
364 m_cached_datadir_path = fs::path();
366 m_cached_blocks_path = fs::path();
367}
368
369std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
370{
371 Command ret;
372 LOCK(cs_args);
373 auto it = m_command.begin();
374 if (it == m_command.end()) {
375 // No command was passed
376 return std::nullopt;
377 }
379 // The registered command
380 ret.command = *(it++);
381 }
382 while (it != m_command.end()) {
383 // The unregistered command and args (if any)
384 ret.args.push_back(*(it++));
385 }
386 return ret;
387}
388
389bool ArgsManager::CheckCommandOptions(const std::string& command, std::vector<std::string>* errors) const
390{
391 LOCK(cs_args);
392
394 if (command_options == m_available_args.end()) {
395 // There are no command-specific options at all, so everything is fine
396 return true;
397 }
398
399 const auto command_args = m_command_args.find(command);
400 auto is_valid_opt = [&](const auto& opt) EXCLUSIVE_LOCKS_REQUIRED(cs_args) -> bool {
401 if (command_args == m_command_args.end()) {
402 // Caller may not have checked that command actually exists
403 // before calling this function. In that case, treat it as
404 // having no valid command-specific options.
405 return false;
406 } else {
407 return command_args->second.contains(opt);
408 }
409 };
410
411 bool ok = true;
412 for (const auto& [arg, _] : command_options->second) {
413 if (!GetSetting_(arg).isNull() && !is_valid_opt(arg)) {
414 ok = false;
415 if (errors != nullptr) {
416 errors->emplace_back(strprintf("The %s option cannot be used with the '%s' command.", arg, command));
417 }
418 }
419 }
420 return ok;
421}
422
423std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
424{
425 std::vector<std::string> result;
426 for (const common::SettingsValue& value : GetSettingsList(strArg)) {
427 result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
428 }
429 return result;
430}
431
432bool ArgsManager::IsArgSet(const std::string& strArg) const
433{
434 return !GetSetting(strArg).isNull();
435}
436
437bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
438{
439 fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
440 if (settings.empty()) {
441 return false;
442 }
443 if (backup) {
444 settings += ".bak";
445 }
446 if (filepath) {
448 }
449 return true;
450}
451
452static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
453{
454 for (const auto& error : errors) {
455 if (error_out) {
456 error_out->emplace_back(error);
457 } else {
458 LogWarning("%s", error);
459 }
460 }
461}
462
463bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
464{
465 fs::path path;
466 if (!GetSettingsPath(&path, /* temp= */ false)) {
467 return true; // Do nothing if settings file disabled.
468 }
469
470 LOCK(cs_args);
471 m_settings.rw_settings.clear();
472 std::vector<std::string> read_errors;
473 if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
475 return false;
476 }
477 for (const auto& setting : m_settings.rw_settings) {
478 KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
479 if (!GetArgFlags_('-' + key.name)) {
480 LogWarning("Ignoring unknown rw_settings value %s", setting.first);
481 }
482 }
483 return true;
484}
485
486bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
487{
488 fs::path path, path_tmp;
489 if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
490 throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
491 }
492
493 LOCK(cs_args);
494 std::vector<std::string> write_errors;
497 return false;
498 }
499 if (!RenameOver(path_tmp, path)) {
500 SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
501 return false;
502 }
503 return true;
504}
505
507{
508 LOCK(cs_args);
509 return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
510 /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
511}
512
513bool ArgsManager::IsArgNegated(const std::string& strArg) const
514{
515 return GetSetting(strArg).isFalse();
516}
517
518std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
519{
520 return GetArg(strArg).value_or(strDefault);
521}
522
523std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
524{
526 return SettingToString(value);
527}
528
529std::optional<std::string> SettingToString(const common::SettingsValue& value)
530{
531 if (value.isNull()) return std::nullopt;
532 if (value.isFalse()) return "0";
533 if (value.isTrue()) return "1";
534 if (value.isNum()) return value.getValStr();
535 return value.get_str();
536}
537
538template <std::integral Int>
539Int ArgsManager::GetArg(const std::string& strArg, Int nDefault) const
540{
541 return GetArg<Int>(strArg).value_or(nDefault);
542}
543
544template <std::integral Int>
545std::optional<Int> ArgsManager::GetArg(const std::string& strArg) const
546{
548 return SettingTo<Int>(value);
549}
550
551template <std::integral Int>
552std::optional<Int> SettingTo(const common::SettingsValue& value)
553{
554 if (value.isNull()) return std::nullopt;
555 if (value.isFalse()) return 0;
556 if (value.isTrue()) return 1;
557 if (value.isNum()) return value.getInt<Int>();
558 return LocaleIndependentAtoi<Int>(value.get_str());
559}
560
561bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
562{
563 return GetBoolArg(strArg).value_or(fDefault);
564}
565
566std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
567{
569 return SettingToBool(value);
570}
571
572std::optional<bool> SettingToBool(const common::SettingsValue& value)
573{
574 if (value.isNull()) return std::nullopt;
575 if (value.isBool()) return value.get_bool();
576 return InterpretBool(value.get_str());
577}
578
579#define INSTANTIATE_INT_TYPE(Type) \
580 template Type ArgsManager::GetArg<Type>(const std::string&, Type) const; \
581 template std::optional<Type> ArgsManager::GetArg<Type>(const std::string&) const; \
582 template std::optional<Type> SettingTo<Type>(const common::SettingsValue&)
583
592
593#undef INSTANTIATE_INT_TYPE
594
595bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
596{
597 LOCK(cs_args);
598 if (!GetSetting_(strArg).isNull()) return false;
599 m_settings.forced_settings[SettingName(strArg)] = strValue;
600 return true;
601}
602
603bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
604{
605 if (fValue)
606 return SoftSetArg(strArg, std::string("1"));
607 else
608 return SoftSetArg(strArg, std::string("0"));
609}
610
611void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
612{
613 LOCK(cs_args);
614 m_settings.forced_settings[SettingName(strArg)] = strValue;
615}
616
617void ArgsManager::AddCommand(const std::string& cmd, const std::string& help, std::set<std::string> options)
618{
619 Assert(cmd.find('=') == std::string::npos);
620 Assert(cmd.at(0) != '-');
621
622 LOCK(cs_args);
623 m_accept_any_command = false; // latch to false
624 std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
625 auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
626 if (!options.empty()) {
629 for (const auto& opt : options) {
630 if (!cmdopts.contains(opt)) {
632 }
633 }
635
636 m_command_args.try_emplace(cmd, std::move(options));
637 }
638 Assert(ret.second); // Fail on duplicate commands
639}
640
641void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
642{
643 Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
644
645 // Split arg name from its help param
646 size_t eq_index = name.find('=');
647 if (eq_index == std::string::npos) {
648 eq_index = name.size();
649 }
650 std::string arg_name = name.substr(0, eq_index);
651
652 LOCK(cs_args);
653
654 // Allow duplicates involving HIDDEN — it is used as a placeholder for args
655 // unavailable in this binary but tolerated for shared config files (see #13441).
656 for (const auto& arg_map : m_available_args) {
657 if (arg_map.first == OptionsCategory::HIDDEN || cat == OptionsCategory::HIDDEN) continue;
658 Assert(!arg_map.second.contains(arg_name));
659 }
660
661 std::map<std::string, Arg>& arg_map = m_available_args[cat];
662 auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
663 assert(ret.second); // Make sure an insertion actually happened
664
667 }
668}
669
670void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
671{
672 for (const std::string& name : names) {
674 }
675}
676
678{
679 LOCK(cs_args);
680 m_settings = {};
681 m_available_args.clear();
682 m_command_args.clear();
683 m_network_only_args.clear();
684 m_config_sections.clear();
685}
686
688{
689 LOCK(cs_args);
690 std::vector<std::string> found{};
692 if (cmds != m_available_args.end()) {
693 for (const auto& [cmd, argspec] : cmds->second) {
694 if (!GetSetting_(cmd).isNull()) {
695 found.push_back(cmd);
696 }
697 }
698 if (found.size() > 1) {
699 throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
700 }
701 }
702}
703
705{
706 const bool show_debug = GetBoolArg("-help-debug", false);
707
708 std::string usage;
709 LOCK(cs_args);
710
712 const auto for_matching_cmd_opts = [&](const std::set<std::string>& select, auto&& fn) EXCLUSIVE_LOCKS_REQUIRED(cs_args) {
713 if (select.empty()) return;
714 if (command_options == m_available_args.end()) return;
715 for (const auto& [name, info] : command_options->second) {
716 if (!show_debug && (info.m_flags & ArgsManager::DEBUG_ONLY)) continue;
717 if (!select.contains(name)) continue;
718 fn(name, info);
719 }
720 };
721
722 for (const auto& [category, category_args] : m_available_args) {
723 switch(category) {
725 usage += HelpMessageGroup("Options:");
726 break;
728 usage += HelpMessageGroup("Connection options:");
729 break;
731 usage += HelpMessageGroup("ZeroMQ notification options:");
732 break;
734 usage += HelpMessageGroup("Debugging/Testing options:");
735 break;
737 usage += HelpMessageGroup("Node relay options:");
738 break;
740 usage += HelpMessageGroup("Block creation options:");
741 break;
743 usage += HelpMessageGroup("RPC server options:");
744 break;
746 usage += HelpMessageGroup("IPC interprocess connection options:");
747 break;
749 usage += HelpMessageGroup("Wallet options:");
750 break;
752 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
753 break;
755 usage += HelpMessageGroup("Chain selection options:");
756 break;
758 usage += HelpMessageGroup("UI Options:");
759 break;
761 usage += HelpMessageGroup("Commands:");
762 break;
764 usage += HelpMessageGroup("Register Commands:");
765 break;
767 usage += HelpMessageGroup("CLI Commands:");
768 break;
771 break;
772 } // no default case, so the compiler can warn about missing cases
773
774 if (category == OptionsCategory::COMMAND_OPTIONS) continue;
775
776 // When we get to the hidden options, stop
777 if (category == OptionsCategory::HIDDEN) break;
778
779 for (const auto& [arg_name, arg_info] : category_args) {
780 if (show_debug || !(arg_info.m_flags & ArgsManager::DEBUG_ONLY)) {
781 usage += HelpMessageOpt(arg_name, arg_info.m_help_param, arg_info.m_help_text);
782
783 if (category == OptionsCategory::COMMANDS) {
784 const auto cmd_args = m_command_args.find(arg_name);
785 if (cmd_args == m_command_args.end()) continue;
786 for_matching_cmd_opts(cmd_args->second, [&](const auto& cmdopt_name, const auto& cmdopt_info) {
787 usage += HelpMessageOpt(cmdopt_name, cmdopt_info.m_help_param, cmdopt_info.m_help_text, /*subopt=*/true);
788 });
789 }
790 }
791 }
792 }
793 return usage;
794}
795
797{
798 return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
799}
800
802{
803 args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
804 args.AddHiddenArgs({"-h", "-?"});
805}
806
807std::string HelpMessageGroup(const std::string &message) {
808 return std::string(message) + std::string("\n\n");
809}
810
811std::string HelpMessageOpt(std::string_view option, std::string_view help_param, std::string_view message, bool subopt)
812{
813 constexpr int screen_width = 79;
814 int opt_indent = 2;
815 int msg_indent = 7;
816
817 if (subopt) {
818 int bump = msg_indent - opt_indent;
819 opt_indent += bump; // opt_indent now at the old msg_indent level
820 msg_indent += bump; // indent by the same amount
821 }
823
824 return strprintf("%*s%s%s\n%*s%s\n\n",
827}
828
829const std::vector<std::string> TEST_OPTIONS_DOC{
830 "addrman (use deterministic addrman)",
831 "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
832 "bip94 (enforce BIP94 consensus rules)",
833};
834
835bool HasTestOption(const ArgsManager& args, const std::string& test_option)
836{
837 const auto options = args.GetArgs("-test");
838 return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
839 return option == test_option;
840 });
841}
842
844{
845 // Windows:
846 // old: C:\Users\Username\AppData\Roaming\Bitcoin
847 // new: C:\Users\Username\AppData\Local\Bitcoin
848 // macOS: ~/Library/Application Support/Bitcoin
849 // Unix-like: ~/.bitcoin
850#ifdef WIN32
851 // Windows
852 // Check for existence of datadir in old location and keep it there
853 fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
855
856 // Otherwise, fresh installs can start in the new, "proper" location
857 return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
858#else
859 fs::path pathRet;
860 char* pszHome = getenv("HOME");
861 if (pszHome == nullptr || strlen(pszHome) == 0)
862 pathRet = fs::path("/");
863 else
864 pathRet = fs::path(pszHome);
865#ifdef __APPLE__
866 // macOS
867 return pathRet / "Library/Application Support/Bitcoin";
868#else
869 // Unix-like
870 return pathRet / ".bitcoin";
871#endif
872#endif
873}
874
876{
877 const fs::path datadir{args.GetPathArg("-datadir")};
878 return datadir.empty() || fs::is_directory(fs::absolute(datadir));
879}
880
882{
883 LOCK(cs_args);
884 return *Assert(m_config_path);
885}
886
888{
889 LOCK(cs_args);
891 m_config_path = path;
892}
893
895{
896 std::variant<ChainType, std::string> arg = GetChainArg();
897 if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
898 throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
899}
900
902{
903 auto arg = GetChainArg();
904 if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
905 return std::get<std::string>(arg);
906}
907
908std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
909{
910 auto get_net = [&](const std::string& arg) {
911 LOCK(cs_args);
912 common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
913 /* ignore_default_section_config= */ false,
914 /*ignore_nonpersistent=*/false,
915 /* get_chain_type= */ true);
916 return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
917 };
918
919 const bool fRegTest = get_net("-regtest");
920 const bool fSigNet = get_net("-signet");
921 const bool fTestNet = get_net("-testnet");
922 const bool fTestNet4 = get_net("-testnet4");
923 const auto chain_arg = GetArg("-chain");
924
925 if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
926 throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
927 }
928 if (chain_arg) {
929 if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
930 // Not a known string, so return original string
931 return *chain_arg;
932 }
933 if (fRegTest) return ChainType::REGTEST;
934 if (fSigNet) return ChainType::SIGNET;
935 if (fTestNet) return ChainType::TESTNET;
936 if (fTestNet4) return ChainType::TESTNET4;
937 return ChainType::MAIN;
938}
939
940bool ArgsManager::UseDefaultSection(const std::string& arg) const
941{
943 return m_network == ChainTypeToString(ChainType::MAIN) || !m_network_only_args.contains(arg);
944}
945
947{
949 return common::GetSetting(
950 m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
951 /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
952}
953
955{
956 LOCK(cs_args);
957 return GetSetting_(arg);
958}
959
960std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
961{
962 LOCK(cs_args);
963 return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
964}
965
967 const std::string& prefix,
968 const std::string& section,
969 const std::map<std::string, std::vector<common::SettingsValue>>& args) const
970{
972 std::string section_str = section.empty() ? "" : "[" + section + "] ";
973 for (const auto& arg : args) {
974 for (const auto& value : arg.second) {
975 std::optional<unsigned int> flags = GetArgFlags_('-' + arg.first);
976 if (flags) {
977 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
978 LogInfo("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
979 }
980 }
981 }
982}
983
985{
986 LOCK(cs_args);
987 for (const auto& section : m_settings.ro_config) {
988 logArgsPrefix("Config file arg:", section.first, section.second);
989 }
990 for (const auto& setting : m_settings.rw_settings) {
991 LogInfo("Setting file arg: %s = %s\n", setting.first, setting.second.write());
992 }
993 logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
994}
const std::vector< std::string > TEST_OPTIONS_DOC
Definition args.cpp:829
#define INSTANTIATE_INT_TYPE(Type)
Definition args.cpp:579
bool HelpRequested(const ArgsManager &args)
Definition args.cpp:796
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition args.cpp:801
fs::path GetDefaultDataDir()
Definition args.cpp:843
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition args.cpp:452
std::optional< common::SettingsValue > InterpretValue(const KeyInfo &key, const std::string *value, unsigned int flags, std::string &error)
Interpret settings value based on registered flags.
Definition args.cpp:104
const char *const BITCOIN_SETTINGS_FILENAME
Definition args.cpp:37
bool CheckDataDirOption(const ArgsManager &args)
Definition args.cpp:875
std::optional< bool > SettingToBool(const common::SettingsValue &value)
Definition args.cpp:572
std::optional< std::string > SettingToString(const common::SettingsValue &value)
Definition args.cpp:529
ArgsManager gArgs
Definition args.cpp:39
std::optional< Int > SettingTo(const common::SettingsValue &value)
Definition args.cpp:552
bool HasTestOption(const ArgsManager &args, const std::string &test_option)
Checks if a particular test option is present in -test command-line arg options.
Definition args.cpp:835
static std::string SettingName(const std::string &arg)
Definition args.cpp:63
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition args.cpp:807
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition args.cpp:76
const char *const BITCOIN_CONF_FILENAME
Definition args.cpp:36
std::string HelpMessageOpt(std::string_view option, std::string_view help_param, std::string_view message, bool subopt)
Format a string to be used as option description in help messages.
Definition args.cpp:811
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition args.cpp:56
std::optional< bool > SettingToBool(const common::SettingsValue &)
Definition args.cpp:572
std::string HelpMessageOpt(std::string_view option, std::string_view help_param, std::string_view message, bool subopt=false)
Format a string to be used as option description in help messages.
Definition args.cpp:811
std::optional< std::string > SettingToString(const common::SettingsValue &)
Definition args.cpp:529
std::optional< common::SettingsValue > InterpretValue(const KeyInfo &key, const std::string *value, unsigned int flags, std::string &error)
Interpret settings value based on registered flags.
Definition args.cpp:104
OptionsCategory
Definition args.h:53
const char *const BITCOIN_SETTINGS_FILENAME
Definition args.cpp:37
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition args.cpp:807
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition args.cpp:76
int ret
int flags
const auto cmd
const auto command
ArgsManager & args
Definition bitcoind.cpp:280
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::optional< ChainType > ChainTypeFromString(std::string_view chain)
Definition chaintype.cpp:29
std::string ChainTypeToString(ChainType chain)
Definition chaintype.cpp:12
ChainType
Definition chaintype.h:12
#define Assert(val)
Identity function.
Definition check.h:119
bool ParseParameters(int argc, const char *const argv[], std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition args.cpp:176
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get list of setting values.
Definition args.cpp:960
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
Definition args.cpp:423
ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type from the program arguments.
Definition args.cpp:894
void CheckMultipleCLIArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Check CLI command args.
Definition args.cpp:687
@ NETWORK_ONLY
Definition args.h:123
@ ALLOW_ANY
disable validation
Definition args.h:109
@ DISALLOW_NEGATION
disallow -nofoo syntax
Definition args.h:114
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
Definition args.h:115
@ DEBUG_ONLY
Definition args.h:117
@ COMMAND
Definition args.h:126
@ SENSITIVE
Definition args.h:125
std::list< SectionInfo > GetUnrecognizedSections() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Log warnings for unrecognized section names in the config file.
Definition args.cpp:153
common::SettingsValue GetSetting(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get setting value.
Definition args.cpp:954
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false, bool backup=false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get settings file path, or return false if read-write settings were disabled with -nosettings.
Definition args.cpp:437
bool CheckCommandOptions(const std::string &command, std::vector< std::string > *errors=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Check that any command-specific options the user specified are valid for the given command.
Definition args.cpp:389
fs::path GetBlocksDirPath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get blocks directory path.
Definition args.cpp:299
fs::path GetDataDirBase() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path.
Definition args.cpp:324
fs::path GetConfigFilePath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return config file path (read-only)
Definition args.cpp:881
void SetDefaultFlags(std::optional< unsigned int >) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Set default flags to return for an unknown arg.
Definition args.cpp:275
void AddCommand(const std::string &cmd, const std::string &help, std::set< std::string > options={}) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add command.
Definition args.cpp:617
bool SoftSetArg(const std::string &strArg, const std::string &strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Set an argument if it doesn't already have a value.
Definition args.cpp:595
std::set< std::string > GetUnsuitableSectionOnlyArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition args.cpp:133
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add argument.
Definition args.cpp:641
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Write settings file or backup settings file.
Definition args.cpp:486
fs::path GetPathArg_(std::string arg, const fs::path &default_value={}) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition args.cpp:281
void ClearPathCache() EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Clear cached directory paths.
Definition args.cpp:360
fs::path GetDataDir(bool net_specific) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Get data directory path.
Definition args.cpp:334
void SetConfigFilePath(fs::path) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition args.cpp:887
common::SettingsValue GetPersistentSetting(const std::string &name) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get current setting from config file or read/write settings file, ignoring nonpersistent command line...
Definition args.cpp:506
void ForceSetArg(const std::string &strArg, const std::string &strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition args.cpp:611
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return path argument or default value.
Definition args.cpp:293
void LogArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Log the config file options and the command line arguments, useful for troubleshooting.
Definition args.cpp:984
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
Definition args.cpp:518
void AddHiddenArgs(const std::vector< std::string > &args) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add many hidden arguments.
Definition args.cpp:670
std::variant< ChainType, std::string > GetChainArg() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return -regtest/-signet/-testnet/-testnet4/-chain= setting as a ChainType enum if a recognized chain ...
Definition args.cpp:908
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< common::SettingsValue > > &args) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition args.cpp:966
std::string GetChainTypeString() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type string from the program arguments.
Definition args.cpp:901
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Read settings file.
Definition args.cpp:463
void ClearArgs() EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Clear available arguments.
Definition args.cpp:677
bool IsArgSet(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return true if the given argument has been manually set.
Definition args.cpp:432
Mutex cs_args
Definition args.h:137
std::optional< const Command > GetCommand() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get the command and command args (returns std::nullopt if no command provided)
Definition args.cpp:369
bool SoftSetBoolArg(const std::string &strArg, bool fValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Set a boolean argument if it doesn't already have a value.
Definition args.cpp:603
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition args.cpp:329
bool IsArgNegated(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return true if the argument was originally passed as a negated option, i.e.
Definition args.cpp:513
common::SettingsValue GetSetting_(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition args.cpp:946
std::optional< unsigned int > GetArgFlags(const std::string &name) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return Flags for known arg.
Definition args.cpp:269
std::optional< unsigned int > GetArgFlags_(const std::string &name) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition args.cpp:257
bool UseDefaultSection(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Returns true if settings values from the default section should be used, depending on the current net...
Definition args.cpp:940
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition args.cpp:561
void SelectConfigNetwork(const std::string &network) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Select the network in use.
Definition args.cpp:170
std::string GetHelpMessage() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get the help string.
Definition args.cpp:704
const std::string & get_str() const
bool isTrue() const
Definition univalue.h:82
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition univalue.h:81
const std::string & getValStr() const
Definition univalue.h:68
bool isBool() const
Definition univalue.h:84
Int getInt() const
Definition univalue.h:143
bool isNum() const
Definition univalue.h:86
bool isFalse() const
Definition univalue.h:83
bool get_bool() const
static path absolute(const path &p)
Definition fs.h:87
static bool exists(const path &p)
Definition fs.h:94
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition fs.h:160
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition fs.h:183
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
#define LogWarning(...)
Definition log.h:137
#define LogInfo(...)
Definition log.h:136
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition settings.cpp:122
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition settings.cpp:71
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool ignore_nonpersistent, bool get_chain_type)
Get settings value from combined sources: forced settings, command line arguments,...
Definition settings.cpp:153
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition settings.h:109
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times,...
Definition settings.cpp:210
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition fs.cpp:32
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition string.h:209
CRPCCommand m_command
const char * prefix
Definition rest.cpp:1201
const char * name
Definition rest.cpp:71
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
static RPCMethod help()
Definition server.cpp:128
Utilities for converting data from/to strings.
Definition args.h:77
std::string name
Definition args.h:78
bool negated
Definition args.h:80
std::string section
Definition args.h:79
Accessor for list of settings that skips negated values when iterated over.
Definition settings.h:92
const SettingsValue * begin() const
Pointer to first non-negated value.
Definition settings.cpp:271
#define LOCK(cs)
Definition sync.h:268
#define AssertLockHeld(cs)
Definition sync.h:144
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
consteval auto _(util::TranslatedLiteral str)
Definition translation.h:79
static struct ArgMap arg_map[]
Definition unit_test.c:50
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())