Bitcoin Core 30.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 <logging.h>
11#include <sync.h>
12#include <tinyformat.h>
13#include <univalue.h>
14#include <util/chaintype.h>
15#include <util/check.h>
16#include <util/fs.h>
17#include <util/fs_helpers.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 LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", 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
166 std::list<SectionInfo> unrecognized = m_config_sections;
167 unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
168 return unrecognized;
169}
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{
260 LOCK(cs_args);
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
270void ArgsManager::SetDefaultFlags(std::optional<unsigned int> flags)
271{
272 LOCK(cs_args);
273 m_default_flags = flags;
274}
275
276fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
277{
278 if (IsArgNegated(arg)) return fs::path{};
279 std::string path_str = GetArg(arg, "");
280 if (path_str.empty()) return default_value;
281 fs::path result = fs::PathFromString(path_str).lexically_normal();
282 // Remove trailing slash, if present.
283 return result.has_filename() ? result : result.parent_path();
284}
285
287{
288 LOCK(cs_args);
289 fs::path& path = m_cached_blocks_path;
290
291 // Cache the path to avoid calling fs::create_directories on every call of
292 // this function
293 if (!path.empty()) return path;
294
295 if (IsArgSet("-blocksdir")) {
296 path = fs::absolute(GetPathArg("-blocksdir"));
297 if (!fs::is_directory(path)) {
298 path = "";
299 return path;
300 }
301 } else {
302 path = GetDataDirBase();
303 }
304
305 path /= fs::PathFromString(BaseParams().DataDir());
306 path /= "blocks";
308 return path;
309}
310
311fs::path ArgsManager::GetDataDir(bool net_specific) const
312{
313 LOCK(cs_args);
314 fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
315
316 // Used cached path if available
317 if (!path.empty()) return path;
318
319 const fs::path datadir{GetPathArg("-datadir")};
320 if (!datadir.empty()) {
321 path = fs::absolute(datadir);
322 if (!fs::is_directory(path)) {
323 path = "";
324 return path;
325 }
326 } else {
327 path = GetDefaultDataDir();
328 }
329
330 if (net_specific && !BaseParams().DataDir().empty()) {
331 path /= fs::PathFromString(BaseParams().DataDir());
332 }
333
334 return path;
335}
336
338{
339 LOCK(cs_args);
340
341 m_cached_datadir_path = fs::path();
342 m_cached_network_datadir_path = fs::path();
343 m_cached_blocks_path = fs::path();
344}
345
346std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
347{
348 Command ret;
349 LOCK(cs_args);
350 auto it = m_command.begin();
351 if (it == m_command.end()) {
352 // No command was passed
353 return std::nullopt;
354 }
355 if (!m_accept_any_command) {
356 // The registered command
357 ret.command = *(it++);
358 }
359 while (it != m_command.end()) {
360 // The unregistered command and args (if any)
361 ret.args.push_back(*(it++));
362 }
363 return ret;
364}
365
366std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
367{
368 std::vector<std::string> result;
369 for (const common::SettingsValue& value : GetSettingsList(strArg)) {
370 result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
371 }
372 return result;
373}
374
375bool ArgsManager::IsArgSet(const std::string& strArg) const
376{
377 return !GetSetting(strArg).isNull();
378}
379
380bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
381{
382 fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
383 if (settings.empty()) {
384 return false;
385 }
386 if (backup) {
387 settings += ".bak";
388 }
389 if (filepath) {
390 *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
391 }
392 return true;
393}
394
395static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
396{
397 for (const auto& error : errors) {
398 if (error_out) {
399 error_out->emplace_back(error);
400 } else {
401 LogPrintf("%s\n", error);
402 }
403 }
404}
405
406bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
407{
408 fs::path path;
409 if (!GetSettingsPath(&path, /* temp= */ false)) {
410 return true; // Do nothing if settings file disabled.
411 }
412
413 LOCK(cs_args);
414 m_settings.rw_settings.clear();
415 std::vector<std::string> read_errors;
416 if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
417 SaveErrors(read_errors, errors);
418 return false;
419 }
420 for (const auto& setting : m_settings.rw_settings) {
421 KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
422 if (!GetArgFlags('-' + key.name)) {
423 LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
424 }
425 }
426 return true;
427}
428
429bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
430{
431 fs::path path, path_tmp;
432 if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
433 throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
434 }
435
436 LOCK(cs_args);
437 std::vector<std::string> write_errors;
438 if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
439 SaveErrors(write_errors, errors);
440 return false;
441 }
442 if (!RenameOver(path_tmp, path)) {
443 SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
444 return false;
445 }
446 return true;
447}
448
450{
451 LOCK(cs_args);
452 return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
453 /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
454}
455
456bool ArgsManager::IsArgNegated(const std::string& strArg) const
457{
458 return GetSetting(strArg).isFalse();
459}
460
461std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
462{
463 return GetArg(strArg).value_or(strDefault);
464}
465
466std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
467{
468 const common::SettingsValue value = GetSetting(strArg);
469 return SettingToString(value);
470}
471
472std::optional<std::string> SettingToString(const common::SettingsValue& value)
473{
474 if (value.isNull()) return std::nullopt;
475 if (value.isFalse()) return "0";
476 if (value.isTrue()) return "1";
477 if (value.isNum()) return value.getValStr();
478 return value.get_str();
479}
480
481std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
482{
483 return SettingToString(value).value_or(strDefault);
484}
485
486int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
487{
488 return GetIntArg(strArg).value_or(nDefault);
489}
490
491std::optional<int64_t> ArgsManager::GetIntArg(const std::string& strArg) const
492{
493 const common::SettingsValue value = GetSetting(strArg);
494 return SettingToInt(value);
495}
496
497std::optional<int64_t> SettingToInt(const common::SettingsValue& value)
498{
499 if (value.isNull()) return std::nullopt;
500 if (value.isFalse()) return 0;
501 if (value.isTrue()) return 1;
502 if (value.isNum()) return value.getInt<int64_t>();
503 return LocaleIndependentAtoi<int64_t>(value.get_str());
504}
505
506int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
507{
508 return SettingToInt(value).value_or(nDefault);
509}
510
511bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
512{
513 return GetBoolArg(strArg).value_or(fDefault);
514}
515
516std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
517{
518 const common::SettingsValue value = GetSetting(strArg);
519 return SettingToBool(value);
520}
521
522std::optional<bool> SettingToBool(const common::SettingsValue& value)
523{
524 if (value.isNull()) return std::nullopt;
525 if (value.isBool()) return value.get_bool();
526 return InterpretBool(value.get_str());
527}
528
529bool SettingToBool(const common::SettingsValue& value, bool fDefault)
530{
531 return SettingToBool(value).value_or(fDefault);
532}
533
534bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
535{
536 LOCK(cs_args);
537 if (IsArgSet(strArg)) return false;
538 ForceSetArg(strArg, strValue);
539 return true;
540}
541
542bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
543{
544 if (fValue)
545 return SoftSetArg(strArg, std::string("1"));
546 else
547 return SoftSetArg(strArg, std::string("0"));
548}
549
550void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
551{
552 LOCK(cs_args);
553 m_settings.forced_settings[SettingName(strArg)] = strValue;
554}
555
556void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
557{
558 Assert(cmd.find('=') == std::string::npos);
559 Assert(cmd.at(0) != '-');
560
561 LOCK(cs_args);
562 m_accept_any_command = false; // latch to false
563 std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
564 auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
565 Assert(ret.second); // Fail on duplicate commands
566}
567
568void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
569{
570 Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
571
572 // Split arg name from its help param
573 size_t eq_index = name.find('=');
574 if (eq_index == std::string::npos) {
575 eq_index = name.size();
576 }
577 std::string arg_name = name.substr(0, eq_index);
578
579 LOCK(cs_args);
580 std::map<std::string, Arg>& arg_map = m_available_args[cat];
581 auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
582 assert(ret.second); // Make sure an insertion actually happened
583
585 m_network_only_args.emplace(arg_name);
586 }
587}
588
589void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
590{
591 for (const std::string& name : names) {
593 }
594}
595
597{
598 LOCK(cs_args);
599 m_settings = {};
600 m_available_args.clear();
601 m_network_only_args.clear();
602}
603
605{
606 LOCK(cs_args);
607 std::vector<std::string> found{};
608 auto cmds = m_available_args.find(OptionsCategory::CLI_COMMANDS);
609 if (cmds != m_available_args.end()) {
610 for (const auto& [cmd, argspec] : cmds->second) {
611 if (IsArgSet(cmd)) {
612 found.push_back(cmd);
613 }
614 }
615 if (found.size() > 1) {
616 throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
617 }
618 }
619}
620
622{
623 const bool show_debug = GetBoolArg("-help-debug", false);
624
625 std::string usage;
626 LOCK(cs_args);
627 for (const auto& arg_map : m_available_args) {
628 switch(arg_map.first) {
630 usage += HelpMessageGroup("Options:");
631 break;
633 usage += HelpMessageGroup("Connection options:");
634 break;
636 usage += HelpMessageGroup("ZeroMQ notification options:");
637 break;
639 usage += HelpMessageGroup("Debugging/Testing options:");
640 break;
642 usage += HelpMessageGroup("Node relay options:");
643 break;
645 usage += HelpMessageGroup("Block creation options:");
646 break;
648 usage += HelpMessageGroup("RPC server options:");
649 break;
651 usage += HelpMessageGroup("IPC interprocess connection options:");
652 break;
654 usage += HelpMessageGroup("Wallet options:");
655 break;
657 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
658 break;
660 usage += HelpMessageGroup("Chain selection options:");
661 break;
663 usage += HelpMessageGroup("UI Options:");
664 break;
666 usage += HelpMessageGroup("Commands:");
667 break;
669 usage += HelpMessageGroup("Register Commands:");
670 break;
672 usage += HelpMessageGroup("CLI Commands:");
673 break;
674 default:
675 break;
676 }
677
678 // When we get to the hidden options, stop
679 if (arg_map.first == OptionsCategory::HIDDEN) break;
680
681 for (const auto& arg : arg_map.second) {
682 if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
683 std::string name;
684 if (arg.second.m_help_param.empty()) {
685 name = arg.first;
686 } else {
687 name = arg.first + arg.second.m_help_param;
688 }
689 usage += HelpMessageOpt(name, arg.second.m_help_text);
690 }
691 }
692 }
693 return usage;
694}
695
697{
698 return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
699}
700
702{
703 args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
704 args.AddHiddenArgs({"-h", "-?"});
705}
706
707static const int screenWidth = 79;
708static const int optIndent = 2;
709static const int msgIndent = 7;
710
711std::string HelpMessageGroup(const std::string &message) {
712 return std::string(message) + std::string("\n\n");
713}
714
715std::string HelpMessageOpt(const std::string &option, const std::string &message) {
716 return std::string(optIndent,' ') + std::string(option) +
717 std::string("\n") + std::string(msgIndent,' ') +
719 std::string("\n\n");
720}
721
722const std::vector<std::string> TEST_OPTIONS_DOC{
723 "addrman (use deterministic addrman)",
724 "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
725 "bip94 (enforce BIP94 consensus rules)",
726};
727
728bool HasTestOption(const ArgsManager& args, const std::string& test_option)
729{
730 const auto options = args.GetArgs("-test");
731 return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
732 return option == test_option;
733 });
734}
735
737{
738 // Windows:
739 // old: C:\Users\Username\AppData\Roaming\Bitcoin
740 // new: C:\Users\Username\AppData\Local\Bitcoin
741 // macOS: ~/Library/Application Support/Bitcoin
742 // Unix-like: ~/.bitcoin
743#ifdef WIN32
744 // Windows
745 // Check for existence of datadir in old location and keep it there
746 fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
747 if (fs::exists(legacy_path)) return legacy_path;
748
749 // Otherwise, fresh installs can start in the new, "proper" location
750 return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
751#else
752 fs::path pathRet;
753 char* pszHome = getenv("HOME");
754 if (pszHome == nullptr || strlen(pszHome) == 0)
755 pathRet = fs::path("/");
756 else
757 pathRet = fs::path(pszHome);
758#ifdef __APPLE__
759 // macOS
760 return pathRet / "Library/Application Support/Bitcoin";
761#else
762 // Unix-like
763 return pathRet / ".bitcoin";
764#endif
765#endif
766}
767
769{
770 const fs::path datadir{args.GetPathArg("-datadir")};
771 return datadir.empty() || fs::is_directory(fs::absolute(datadir));
772}
773
775{
776 LOCK(cs_args);
777 return *Assert(m_config_path);
778}
779
781{
782 LOCK(cs_args);
783 assert(!m_config_path);
784 m_config_path = path;
785}
786
788{
789 std::variant<ChainType, std::string> arg = GetChainArg();
790 if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
791 throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
792}
793
795{
796 auto arg = GetChainArg();
797 if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
798 return std::get<std::string>(arg);
799}
800
801std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
802{
803 auto get_net = [&](const std::string& arg) {
804 LOCK(cs_args);
805 common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
806 /* ignore_default_section_config= */ false,
807 /*ignore_nonpersistent=*/false,
808 /* get_chain_type= */ true);
809 return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
810 };
811
812 const bool fRegTest = get_net("-regtest");
813 const bool fSigNet = get_net("-signet");
814 const bool fTestNet = get_net("-testnet");
815 const bool fTestNet4 = get_net("-testnet4");
816 const auto chain_arg = GetArg("-chain");
817
818 if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
819 throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
820 }
821 if (chain_arg) {
822 if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
823 // Not a known string, so return original string
824 return *chain_arg;
825 }
826 if (fRegTest) return ChainType::REGTEST;
827 if (fSigNet) return ChainType::SIGNET;
828 if (fTestNet) return ChainType::TESTNET;
829 if (fTestNet4) return ChainType::TESTNET4;
830 return ChainType::MAIN;
831}
832
833bool ArgsManager::UseDefaultSection(const std::string& arg) const
834{
835 return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
836}
837
839{
840 LOCK(cs_args);
841 return common::GetSetting(
842 m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
843 /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
844}
845
846std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
847{
848 LOCK(cs_args);
849 return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
850}
851
853 const std::string& prefix,
854 const std::string& section,
855 const std::map<std::string, std::vector<common::SettingsValue>>& args) const
856{
857 std::string section_str = section.empty() ? "" : "[" + section + "] ";
858 for (const auto& arg : args) {
859 for (const auto& value : arg.second) {
860 std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
861 if (flags) {
862 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
863 LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
864 }
865 }
866 }
867}
868
870{
871 LOCK(cs_args);
872 for (const auto& section : m_settings.ro_config) {
873 logArgsPrefix("Config file arg:", section.first, section.second);
874 }
875 for (const auto& setting : m_settings.rw_settings) {
876 LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
877 }
878 logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
879}
const std::vector< std::string > TEST_OPTIONS_DOC
Definition: args.cpp:722
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:696
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:701
fs::path GetDefaultDataDir()
Definition: args.cpp:736
static const int msgIndent
Definition: args.cpp:709
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: args.cpp:395
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:768
std::optional< bool > SettingToBool(const common::SettingsValue &value)
Definition: args.cpp:522
std::optional< std::string > SettingToString(const common::SettingsValue &value)
Definition: args.cpp:472
static const int screenWidth
Definition: args.cpp:707
ArgsManager gArgs
Definition: args.cpp:40
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:728
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:711
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::optional< int64_t > SettingToInt(const common::SettingsValue &value)
Definition: args.cpp:497
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: args.cpp:57
static const int optIndent
Definition: args.cpp:708
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: args.cpp:715
OptionsCategory
Definition: args.h:52
int ret
int flags
Definition: bitcoin-tx.cpp:529
const auto cmd
ArgsManager & args
Definition: bitcoind.cpp:277
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::optional< ChainType > ChainTypeFromString(std::string_view chain)
Definition: chaintype.cpp:28
std::string ChainTypeToString(ChainType chain)
Definition: chaintype.cpp:11
ChainType
Definition: chaintype.h:11
#define Assert(val)
Identity function.
Definition: check.h:115
std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: args.cpp:134
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:346
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: args.cpp:456
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< common::SettingsValue > > &args) const
Definition: args.cpp:852
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: args.cpp:154
@ NETWORK_ONLY
Definition: args.h:120
@ ALLOW_ANY
disable validation
Definition: args.h:106
@ DISALLOW_NEGATION
disallow -nofoo syntax
Definition: args.h:111
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
Definition: args.h:112
@ DEBUG_ONLY
Definition: args.h:114
@ COMMAND
Definition: args.h:123
@ SENSITIVE
Definition: args.h:122
common::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: args.cpp:838
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: args.cpp:406
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:787
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:550
std::string GetChainTypeString() const
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:794
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:177
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:366
void CheckMultipleCLIArgs() const
Check CLI command args.
Definition: args.cpp:604
void SetDefaultFlags(std::optional< unsigned int >)
Set default flags to return for an unknown arg.
Definition: args.cpp:270
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:235
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: args.cpp:258
void SetConfigFilePath(fs::path)
Definition: args.cpp:780
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false, bool backup=false) const
Get settings file path, or return false if read-write settings were disabled with -nosettings.
Definition: args.cpp:380
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: args.cpp:534
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: args.cpp:171
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:621
void ClearPathCache()
Clear cached directory paths.
Definition: args.cpp:337
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:375
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: args.cpp:429
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:486
void ClearArgs()
Clear available arguments.
Definition: args.cpp:596
fs::path GetDataDirBase() const
Get data directory path.
Definition: args.h:228
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:286
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition: args.cpp:774
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:846
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: args.cpp:556
std::variant< ChainType, std::string > GetChainArg() const
Return -regtest/-signet/-testnet/-testnet4/-chain= setting as a ChainType enum if a recognized chain ...
Definition: args.cpp:801
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: args.cpp:869
fs::path GetDataDir(bool net_specific) const
Get data directory path.
Definition: args.cpp:311
RecursiveMutex cs_args
Definition: args.h:134
common::SettingsValue GetPersistentSetting(const std::string &name) const
Get current setting from config file or read/write settings file, ignoring nonpersistent command line...
Definition: args.cpp:449
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:833
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:461
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:542
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:511
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:589
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:568
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:276
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:88
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:196
static bool exists(const path &p)
Definition: fs.h:95
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:157
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:180
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:243
#define LogPrintf(...)
Definition: logging.h:373
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:34
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:204
CRPCCommand m_command
Definition: interfaces.cpp:543
const char * prefix
Definition: rest.cpp:1117
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 RPCHelpMan help()
Definition: server.cpp:119
Definition: args.h:72
std::string name
Definition: args.h:73
bool negated
Definition: args.h:75
std::string section
Definition: args.h:74
std::string m_name
Definition: args.h:84
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:90
#define LOCK(cs)
Definition: sync.h:259
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
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.
assert(!tx.IsCoinBase())