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