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