Branch data Line data Source code
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 : :
37 : : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
38 : : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
39 : :
40 : : ArgsManager gArgs;
41 : :
42 : : /**
43 : : * Interpret a string argument as a boolean.
44 : : *
45 : : * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
46 : : * like "foo", return 0. This means that if a user unintentionally supplies a
47 : : * non-integer argument here, the return value is always false. This means that
48 : : * -foo=false does what the user probably expects, but -foo=true is well defined
49 : : * but does not do what they probably expected.
50 : : *
51 : : * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
52 : : * representable as an int.
53 : : *
54 : : * For a more extensive discussion of this topic (and a wide range of opinions
55 : : * on the Right Way to change this code), see PR12713.
56 : : */
57 : 47802 : static bool InterpretBool(const std::string& strValue)
58 : : {
59 [ + + ]: 47802 : if (strValue.empty())
60 : : return true;
61 [ - + ]: 42034 : return (LocaleIndependentAtoi<int>(strValue) != 0);
62 : : }
63 : :
64 : 1617794 : static std::string SettingName(const std::string& arg)
65 : : {
66 [ - + + + : 1790281 : return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
+ + ]
67 : : }
68 : :
69 : : /**
70 : : * Parse "name", "section.name", "noname", "section.noname" settings keys.
71 : : *
72 : : * @note Where an option was negated can be later checked using the
73 : : * IsArgNegated() method. One use case for this is to have a way to disable
74 : : * options that are not normally boolean (e.g. using -nodebuglogfile to request
75 : : * that debug log output is not sent to any file at all).
76 : : */
77 : 204760 : KeyInfo InterpretKey(std::string key)
78 : : {
79 [ + + ]: 204760 : KeyInfo result;
80 : : // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
81 : 204760 : size_t option_index = key.find('.');
82 [ + + ]: 204760 : if (option_index != std::string::npos) {
83 [ + - ]: 5365 : result.section = key.substr(0, option_index);
84 [ + - ]: 5365 : key.erase(0, option_index + 1);
85 : : }
86 [ - + + + ]: 204760 : if (key.starts_with("no")) {
87 [ + - ]: 61320 : key.erase(0, 2);
88 : 61320 : result.negated = true;
89 : : }
90 [ + - ]: 204760 : result.name = key;
91 : 204760 : return result;
92 : 0 : }
93 : :
94 : : /**
95 : : * Interpret settings value based on registered flags.
96 : : *
97 : : * @param[in] key key information to know if key was negated
98 : : * @param[in] value string value of setting to be parsed
99 : : * @param[in] flags ArgsManager registered argument flags
100 : : * @param[out] error Error description if settings value is not valid
101 : : *
102 : : * @return parsed settings value if it is valid, otherwise nullopt accompanied
103 : : * by a descriptive error string
104 : : */
105 : 176953 : std::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 [ + + ]: 176953 : if (key.negated) {
110 [ + + ]: 55240 : if (flags & ArgsManager::DISALLOW_NEGATION) {
111 : 1883 : error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
112 : 1883 : return std::nullopt;
113 : : }
114 : : // Double negatives like -nofoo=0 are supported (but discouraged)
115 [ + + + + ]: 53357 : if (value && !InterpretBool(*value)) {
116 : 13176 : LogWarning("Parsed potentially confusing double-negative -%s=%s", key.name, *value);
117 : 13176 : return true;
118 : : }
119 : 40181 : return false;
120 : : }
121 [ + + + + ]: 121713 : if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
122 : 2141 : error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
123 : 2141 : return std::nullopt;
124 : : }
125 [ + - ]: 119572 : 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.
131 : 2770 : ArgsManager::ArgsManager() = default;
132 [ - + ]: 13850 : ArgsManager::~ArgsManager() = default;
133 : :
134 : 2539 : std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
135 : : {
136 [ + - ]: 2539 : std::set<std::string> unsuitables;
137 : :
138 [ + - ]: 2539 : LOCK(cs_args);
139 : :
140 : : // if there's no section selected, don't worry
141 [ + + ]: 2539 : 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 [ + - + + ]: 1913 : if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
145 : :
146 [ + + ]: 20161 : for (const auto& arg : m_network_only_args) {
147 [ + - + - : 18266 : if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
- + ]
148 [ # # ]: 0 : unsuitables.insert(arg);
149 : : }
150 : : }
151 : 1895 : return unsuitables;
152 : 2539 : }
153 : :
154 : 2539 : std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
155 : : {
156 : : // Section names to be recognized in the config file.
157 : 2539 : static const std::set<std::string> available_sections{
158 : : ChainTypeToString(ChainType::REGTEST),
159 : : ChainTypeToString(ChainType::SIGNET),
160 : : ChainTypeToString(ChainType::TESTNET),
161 : : ChainTypeToString(ChainType::TESTNET4),
162 : : ChainTypeToString(ChainType::MAIN),
163 [ + + + - : 3061 : };
- + + + -
- ]
164 : :
165 : 2539 : LOCK(cs_args);
166 [ + - ]: 2539 : std::list<SectionInfo> unrecognized = m_config_sections;
167 : 2539 : unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.contains(appeared.m_name); });
168 [ + - ]: 2539 : return unrecognized;
169 [ + - + - : 2626 : }
+ - + - +
- - - ]
170 : :
171 : 6023 : void ArgsManager::SelectConfigNetwork(const std::string& network)
172 : : {
173 : 6023 : LOCK(cs_args);
174 [ + - + - ]: 12046 : m_network = network;
175 : 6023 : }
176 : :
177 : 218281 : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
178 : : {
179 : 218281 : LOCK(cs_args);
180 : 218281 : m_settings.command_line_options.clear();
181 : :
182 [ + + ]: 391210 : for (int i = 1; i < argc; i++) {
183 [ + - ]: 356771 : 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 [ + + ]: 356771 : if (key == "-") break; //bitcoin-tx using stdin
194 : 353295 : std::optional<std::string> val;
195 : 353295 : size_t is_index = key.find('=');
196 [ + + ]: 353295 : if (is_index != std::string::npos) {
197 [ + - ]: 92807 : val = key.substr(is_index + 1);
198 [ + - ]: 92807 : key.erase(is_index);
199 : : }
200 : : #ifdef WIN32
201 : : key = ToLower(key);
202 : : if (key[0] == '/')
203 : : key[0] = '-';
204 : : #endif
205 : :
206 [ + + ]: 353295 : if (key[0] != '-') {
207 [ - + - - ]: 148535 : if (!m_accept_any_command && m_command.empty()) {
208 : : // The first non-dash arg is a registered command
209 [ # # ]: 0 : std::optional<unsigned int> flags = GetArgFlags(key);
210 [ # # # # ]: 0 : if (!flags || !(*flags & ArgsManager::COMMAND)) {
211 [ # # ]: 0 : error = strprintf("Invalid command '%s'", argv[i]);
212 : 0 : return false;
213 : : }
214 : : }
215 [ + - ]: 148535 : m_command.push_back(key);
216 [ + + ]: 803555 : while (++i < argc) {
217 : : // The remaining args are command args
218 [ + - ]: 655020 : m_command.emplace_back(argv[i]);
219 : : }
220 : 148535 : break;
221 : : }
222 : :
223 : : // Transform --foo to -foo
224 [ - + + + : 204760 : if (key.length() > 1 && key[1] == '-')
+ + ]
225 [ + - ]: 21787 : key.erase(0, 1);
226 : :
227 : : // Transform -foo to foo
228 [ + - ]: 204760 : key.erase(0, 1);
229 [ - + + - ]: 409520 : KeyInfo keyinfo = InterpretKey(key);
230 [ + - + - ]: 204760 : 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 [ + + + + ]: 204760 : if (!flags || !keyinfo.section.empty()) {
236 [ + - ]: 27807 : error = strprintf("Invalid parameter %s", argv[i]);
237 : 27807 : return false;
238 : : }
239 : :
240 [ + + + - ]: 275398 : std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
241 [ + + ]: 176953 : if (!value) return false;
242 : :
243 [ + - + - ]: 172929 : m_settings.command_line_options[keyinfo.name].push_back(*value);
244 : 714090 : }
245 : :
246 : : // we do not allow -includeconf from command line, only -noincludeconf
247 [ + - + + ]: 186450 : if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
248 : 9852 : const common::SettingsSpan values{*includes};
249 : : // Range may be empty if -noincludeconf was passed
250 [ + - + + ]: 9852 : if (!values.empty()) {
251 [ + - + - : 8995 : error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
+ - ]
252 : 8995 : return false; // pick first value as example
253 : : }
254 : : }
255 : : return true;
256 : 218281 : }
257 : :
258 : 430399 : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
259 : : {
260 : 430399 : LOCK(cs_args);
261 [ + + ]: 1029582 : for (const auto& arg_map : m_available_args) {
262 : 831324 : const auto search = arg_map.second.find(name);
263 [ + + ]: 831324 : if (search != arg_map.second.end()) {
264 : 232141 : return search->second.m_flags;
265 : : }
266 : : }
267 : 198258 : return m_default_flags;
268 : 430399 : }
269 : :
270 : 0 : void ArgsManager::SetDefaultFlags(std::optional<unsigned int> flags)
271 : : {
272 : 0 : LOCK(cs_args);
273 [ # # ]: 0 : m_default_flags = flags;
274 : 0 : }
275 : :
276 : 7713 : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
277 : : {
278 [ + + ]: 7713 : if (IsArgNegated(arg)) return fs::path{};
279 [ + - ]: 7625 : std::string path_str = GetArg(arg, "");
280 [ + + + - ]: 13771 : if (path_str.empty()) return default_value;
281 [ + - + - ]: 18438 : fs::path result = fs::PathFromString(path_str).lexically_normal();
282 : : // Remove trailing slash, if present.
283 [ + - + - : 18438 : return result.has_filename() ? result : result.parent_path();
- - ]
284 : 13771 : }
285 : :
286 : 5555 : fs::path ArgsManager::GetBlocksDirPath() const
287 : : {
288 : 5555 : LOCK(cs_args);
289 : 5555 : 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 [ + + + - ]: 5555 : if (!path.empty()) return path;
294 : :
295 [ + - + - : 3073 : if (IsArgSet("-blocksdir")) {
- + ]
296 [ # # # # : 0 : path = fs::absolute(GetPathArg("-blocksdir"));
# # ]
297 [ # # # # ]: 0 : if (!fs::is_directory(path)) {
298 [ # # ]: 0 : path = "";
299 [ # # ]: 0 : return path;
300 : : }
301 : : } else {
302 [ + - ]: 6146 : path = GetDataDirBase();
303 : : }
304 : :
305 [ + - + - ]: 6146 : path /= fs::PathFromString(BaseParams().DataDir());
306 [ + - ]: 3073 : path /= "blocks";
307 [ + - ]: 3073 : fs::create_directories(path);
308 [ + - + - ]: 5555 : return path;
309 : 5555 : }
310 : :
311 : 65716 : fs::path ArgsManager::GetDataDir(bool net_specific) const
312 : : {
313 : 65716 : LOCK(cs_args);
314 [ + + ]: 65716 : fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
315 : :
316 : : // Used cached path if available
317 [ + + + - : 71862 : if (!path.empty()) return path;
+ - ]
318 : :
319 [ + - + - ]: 12292 : const fs::path datadir{GetPathArg("-datadir")};
320 [ + - ]: 6146 : if (!datadir.empty()) {
321 [ + - ]: 12292 : path = fs::absolute(datadir);
322 [ + - - + ]: 6146 : if (!fs::is_directory(path)) {
323 [ # # ]: 0 : path = "";
324 [ # # ]: 0 : return path;
325 : : }
326 : : } else {
327 [ # # ]: 0 : path = GetDefaultDataDir();
328 : : }
329 : :
330 [ + + + - : 6146 : if (net_specific && !BaseParams().DataDir().empty()) {
+ + ]
331 [ + - + - ]: 9198 : path /= fs::PathFromString(BaseParams().DataDir());
332 : : }
333 : :
334 [ + - ]: 6146 : return path;
335 : 71862 : }
336 : :
337 : 1567 : void ArgsManager::ClearPathCache()
338 : : {
339 : 1567 : LOCK(cs_args);
340 : :
341 : 1567 : m_cached_datadir_path = fs::path();
342 : 1567 : m_cached_network_datadir_path = fs::path();
343 [ + - ]: 3134 : m_cached_blocks_path = fs::path();
344 : 1567 : }
345 : :
346 : 0 : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
347 : : {
348 [ # # ]: 0 : Command ret;
349 [ # # ]: 0 : LOCK(cs_args);
350 [ # # ]: 0 : auto it = m_command.begin();
351 [ # # ]: 0 : if (it == m_command.end()) {
352 : : // No command was passed
353 : 0 : return std::nullopt;
354 : : }
355 [ # # ]: 0 : if (!m_accept_any_command) {
356 : : // The registered command
357 [ # # ]: 0 : ret.command = *(it++);
358 : : }
359 [ # # ]: 0 : while (it != m_command.end()) {
360 : : // The unregistered command and args (if any)
361 [ # # ]: 0 : ret.args.push_back(*(it++));
362 : : }
363 : 0 : return ret;
364 : 0 : }
365 : :
366 : 367397 : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
367 : : {
368 : 367397 : std::vector<std::string> result;
369 [ + - + + ]: 375963 : for (const common::SettingsValue& value : GetSettingsList(strArg)) {
370 [ - + - - : 25461 : result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
+ + + - +
- - + +
- ]
371 : : }
372 : 367397 : return result;
373 : 0 : }
374 : :
375 : 144551 : bool ArgsManager::IsArgSet(const std::string& strArg) const
376 : : {
377 : 144551 : return !GetSetting(strArg).isNull();
378 : : }
379 : :
380 : 0 : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
381 : : {
382 [ # # # # ]: 0 : fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
383 [ # # ]: 0 : if (settings.empty()) {
384 : : return false;
385 : : }
386 [ # # ]: 0 : if (backup) {
387 [ # # ]: 0 : settings += ".bak";
388 : : }
389 [ # # ]: 0 : if (filepath) {
390 [ # # # # : 0 : *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
# # # # #
# # # ]
391 : : }
392 : : return true;
393 : 0 : }
394 : :
395 : 0 : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
396 : : {
397 [ # # ]: 0 : for (const auto& error : errors) {
398 [ # # ]: 0 : if (error_out) {
399 : 0 : error_out->emplace_back(error);
400 : : } else {
401 : 0 : LogWarning("%s", error);
402 : : }
403 : : }
404 : 0 : }
405 : :
406 : 0 : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
407 : : {
408 : 0 : fs::path path;
409 [ # # # # ]: 0 : if (!GetSettingsPath(&path, /* temp= */ false)) {
410 : : return true; // Do nothing if settings file disabled.
411 : : }
412 : :
413 [ # # ]: 0 : LOCK(cs_args);
414 : 0 : m_settings.rw_settings.clear();
415 : 0 : std::vector<std::string> read_errors;
416 [ # # # # ]: 0 : if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
417 [ # # # # ]: 0 : SaveErrors(read_errors, errors);
418 : 0 : return false;
419 : : }
420 [ # # ]: 0 : for (const auto& setting : m_settings.rw_settings) {
421 [ # # # # ]: 0 : KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
422 [ # # # # : 0 : if (!GetArgFlags('-' + key.name)) {
# # ]
423 [ # # ]: 0 : LogWarning("Ignoring unknown rw_settings value %s", setting.first);
424 : : }
425 : 0 : }
426 : : return true;
427 [ # # ]: 0 : }
428 : :
429 : 0 : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
430 : : {
431 : 0 : fs::path path, path_tmp;
432 [ # # # # : 0 : if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
# # # # ]
433 [ # # ]: 0 : throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
434 : : }
435 : :
436 [ # # ]: 0 : LOCK(cs_args);
437 : 0 : std::vector<std::string> write_errors;
438 [ # # # # ]: 0 : if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
439 [ # # # # ]: 0 : SaveErrors(write_errors, errors);
440 : 0 : return false;
441 : : }
442 [ # # # # : 0 : if (!RenameOver(path_tmp, path)) {
# # # # ]
443 [ # # # # : 0 : SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
# # # # #
# ]
444 : 0 : return false;
445 : : }
446 : : return true;
447 [ # # # # : 0 : }
# # ]
448 : :
449 : 0 : common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
450 : : {
451 : 0 : LOCK(cs_args);
452 [ # # # # : 0 : return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
# # ]
453 [ # # ]: 0 : /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
454 : 0 : }
455 : :
456 : 10252 : bool ArgsManager::IsArgNegated(const std::string& strArg) const
457 : : {
458 : 10252 : return GetSetting(strArg).isFalse();
459 : : }
460 : :
461 : 68077 : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
462 : : {
463 [ + - ]: 136154 : return GetArg(strArg).value_or(strDefault);
464 : : }
465 : :
466 : 166901 : std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
467 : : {
468 : 166901 : const common::SettingsValue value = GetSetting(strArg);
469 [ + - ]: 333802 : return SettingToString(value);
470 : 166901 : }
471 : :
472 : 166901 : std::optional<std::string> SettingToString(const common::SettingsValue& value)
473 : : {
474 [ + + ]: 166901 : if (value.isNull()) return std::nullopt;
475 [ + + ]: 6707 : if (value.isFalse()) return "0";
476 [ + + ]: 6673 : if (value.isTrue()) return "1";
477 [ - + - - ]: 6641 : if (value.isNum()) return value.getValStr();
478 [ - + ]: 13282 : return value.get_str();
479 : : }
480 : :
481 : 0 : std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
482 : : {
483 [ # # ]: 0 : return SettingToString(value).value_or(strDefault);
484 : : }
485 : :
486 : : template <std::integral Int>
487 : 484191 : Int ArgsManager::GetArg(const std::string& strArg, Int nDefault) const
488 : : {
489 [ + + ]: 484191 : return GetArg<Int>(strArg).value_or(nDefault);
490 : : }
491 : :
492 : : template <std::integral Int>
493 : 586707 : std::optional<Int> ArgsManager::GetArg(const std::string& strArg) const
494 : : {
495 : 586707 : const common::SettingsValue value = GetSetting(strArg);
496 [ + - ]: 1173414 : return SettingTo<Int>(value);
497 : 586707 : }
498 : :
499 : : template <std::integral Int>
500 [ + + ]: 586707 : std::optional<Int> SettingTo(const common::SettingsValue& value)
501 : : {
502 [ + + ]: 586707 : if (value.isNull()) return std::nullopt;
503 [ + + ]: 48005 : if (value.isFalse()) return 0;
504 [ + + ]: 47974 : if (value.isTrue()) return 1;
505 [ - + ]: 47944 : if (value.isNum()) return value.getInt<Int>();
506 [ - + ]: 47944 : return LocaleIndependentAtoi<Int>(value.get_str());
507 : : }
508 : :
509 : : template <std::integral Int>
510 : 0 : Int SettingTo(const common::SettingsValue& value, Int nDefault)
511 : : {
512 [ # # ]: 0 : return SettingTo<Int>(value).value_or(nDefault);
513 : : }
514 : :
515 : 173362 : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
516 : : {
517 [ + + ]: 173362 : return GetBoolArg(strArg).value_or(fDefault);
518 : : }
519 : :
520 : 182870 : std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
521 : : {
522 : 182870 : const common::SettingsValue value = GetSetting(strArg);
523 [ + - ]: 365740 : return SettingToBool(value);
524 : 182870 : }
525 : :
526 : 182870 : std::optional<bool> SettingToBool(const common::SettingsValue& value)
527 : : {
528 [ + + ]: 182870 : if (value.isNull()) return std::nullopt;
529 [ + + ]: 7305 : if (value.isBool()) return value.get_bool();
530 : 7241 : return InterpretBool(value.get_str());
531 : : }
532 : :
533 : 0 : bool SettingToBool(const common::SettingsValue& value, bool fDefault)
534 : : {
535 [ # # ]: 0 : return SettingToBool(value).value_or(fDefault);
536 : : }
537 : :
538 : : #define INSTANTIATE_INT_TYPE(Type) \
539 : : template Type ArgsManager::GetArg<Type>(const std::string&, Type) const; \
540 : : template std::optional<Type> ArgsManager::GetArg<Type>(const std::string&) const; \
541 : : template Type SettingTo<Type>(const common::SettingsValue&, Type); \
542 : : template std::optional<Type> SettingTo<Type>(const common::SettingsValue&)
543 : :
544 : : INSTANTIATE_INT_TYPE(int8_t);
545 : : INSTANTIATE_INT_TYPE(uint8_t);
546 : : INSTANTIATE_INT_TYPE(int16_t);
547 : : INSTANTIATE_INT_TYPE(uint16_t);
548 : : INSTANTIATE_INT_TYPE(int32_t);
549 : : INSTANTIATE_INT_TYPE(uint32_t);
550 : : INSTANTIATE_INT_TYPE(int64_t);
551 : : INSTANTIATE_INT_TYPE(uint64_t);
552 : :
553 : : #undef INSTANTIATE_INT_TYPE
554 : :
555 : 126139 : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
556 : : {
557 : 126139 : LOCK(cs_args);
558 [ + - + + ]: 126139 : if (IsArgSet(strArg)) return false;
559 [ + - ]: 71491 : ForceSetArg(strArg, strValue);
560 : : return true;
561 : 126139 : }
562 : :
563 : 92089 : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
564 : : {
565 [ + + ]: 92089 : if (fValue)
566 [ + - ]: 67199 : return SoftSetArg(strArg, std::string("1"));
567 : : else
568 [ + - ]: 24890 : return SoftSetArg(strArg, std::string("0"));
569 : : }
570 : :
571 : 130694 : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
572 : : {
573 : 130694 : LOCK(cs_args);
574 [ + - + - : 130694 : m_settings.forced_settings[SettingName(strArg)] = strValue;
+ - + - ]
575 : 130694 : }
576 : :
577 : 0 : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
578 : : {
579 [ # # ]: 0 : Assert(cmd.find('=') == std::string::npos);
580 [ # # ]: 0 : Assert(cmd.at(0) != '-');
581 : :
582 : 0 : LOCK(cs_args);
583 : 0 : m_accept_any_command = false; // latch to false
584 [ # # ]: 0 : std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
585 [ # # # # : 0 : auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
# # ]
586 [ # # # # ]: 0 : Assert(ret.second); // Fail on duplicate commands
587 : 0 : }
588 : :
589 : 439236 : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
590 : : {
591 [ - + ]: 439236 : Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
592 : :
593 : : // Split arg name from its help param
594 : 439236 : size_t eq_index = name.find('=');
595 [ + + ]: 439236 : if (eq_index == std::string::npos) {
596 [ - + ]: 276268 : eq_index = name.size();
597 : : }
598 : 439236 : std::string arg_name = name.substr(0, eq_index);
599 : :
600 [ + - ]: 439236 : LOCK(cs_args);
601 [ + - ]: 439236 : std::map<std::string, Arg>& arg_map = m_available_args[cat];
602 [ - + + - : 878472 : auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
- + + - ]
603 [ - + ]: 439236 : assert(ret.second); // Make sure an insertion actually happened
604 : :
605 [ + + ]: 439236 : if (flags & ArgsManager::NETWORK_ONLY) {
606 [ + - ]: 31864 : m_network_only_args.emplace(arg_name);
607 : : }
608 : 439236 : }
609 : :
610 : 29032 : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
611 : : {
612 [ + + ]: 167554 : for (const std::string& name : names) {
613 [ + - ]: 277044 : AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
614 : : }
615 : 29032 : }
616 : :
617 : 23306 : void ArgsManager::ClearArgs()
618 : : {
619 : 23306 : LOCK(cs_args);
620 : 23306 : m_settings = {};
621 : 23306 : m_available_args.clear();
622 [ + - ]: 23306 : m_network_only_args.clear();
623 : 23306 : }
624 : :
625 : 0 : void ArgsManager::CheckMultipleCLIArgs() const
626 : : {
627 : 0 : LOCK(cs_args);
628 : 0 : std::vector<std::string> found{};
629 : 0 : auto cmds = m_available_args.find(OptionsCategory::CLI_COMMANDS);
630 [ # # ]: 0 : if (cmds != m_available_args.end()) {
631 [ # # # # ]: 0 : for (const auto& [cmd, argspec] : cmds->second) {
632 [ # # # # ]: 0 : if (IsArgSet(cmd)) {
633 [ # # ]: 0 : found.push_back(cmd);
634 : : }
635 : : }
636 [ # # # # ]: 0 : if (found.size() > 1) {
637 [ # # # # : 0 : throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
# # ]
638 : : }
639 : : }
640 [ # # ]: 0 : }
641 : :
642 : 972 : std::string ArgsManager::GetHelpMessage() const
643 : : {
644 [ + - ]: 972 : const bool show_debug = GetBoolArg("-help-debug", false);
645 : :
646 [ + - ]: 972 : std::string usage;
647 [ + - ]: 972 : LOCK(cs_args);
648 [ + + ]: 2792 : for (const auto& arg_map : m_available_args) {
649 [ + + + + : 2592 : switch(arg_map.first) {
+ + + + +
+ + + + +
+ + ]
650 : 645 : case OptionsCategory::OPTIONS:
651 [ + - + - ]: 1290 : usage += HelpMessageGroup("Options:");
652 : 645 : break;
653 : 78 : case OptionsCategory::CONNECTION:
654 [ + - + - ]: 156 : usage += HelpMessageGroup("Connection options:");
655 : 78 : break;
656 : 74 : case OptionsCategory::ZMQ:
657 [ + - + - ]: 148 : usage += HelpMessageGroup("ZeroMQ notification options:");
658 : 74 : break;
659 : 84 : case OptionsCategory::DEBUG_TEST:
660 [ + - + - ]: 168 : usage += HelpMessageGroup("Debugging/Testing options:");
661 : 84 : break;
662 : 42 : case OptionsCategory::NODE_RELAY:
663 [ + - + - ]: 84 : usage += HelpMessageGroup("Node relay options:");
664 : 42 : break;
665 : 45 : case OptionsCategory::BLOCK_CREATION:
666 [ + - + - ]: 90 : usage += HelpMessageGroup("Block creation options:");
667 : 45 : break;
668 : 87 : case OptionsCategory::RPC:
669 [ + - + - ]: 174 : usage += HelpMessageGroup("RPC server options:");
670 : 87 : break;
671 : 26 : case OptionsCategory::IPC:
672 [ + - + - ]: 52 : usage += HelpMessageGroup("IPC interprocess connection options:");
673 : 26 : break;
674 : 100 : case OptionsCategory::WALLET:
675 [ + - + - ]: 200 : usage += HelpMessageGroup("Wallet options:");
676 : 100 : break;
677 : 116 : case OptionsCategory::WALLET_DEBUG_TEST:
678 [ + + + - : 152 : if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
+ - ]
679 : : break;
680 : 68 : case OptionsCategory::CHAINPARAMS:
681 [ + - + - ]: 136 : usage += HelpMessageGroup("Chain selection options:");
682 : 68 : break;
683 : 46 : case OptionsCategory::GUI:
684 [ + - + - ]: 92 : usage += HelpMessageGroup("UI Options:");
685 : 46 : break;
686 : 127 : case OptionsCategory::COMMANDS:
687 [ + - + - ]: 254 : usage += HelpMessageGroup("Commands:");
688 : 127 : break;
689 : 121 : case OptionsCategory::REGISTER_COMMANDS:
690 [ + - + - ]: 242 : usage += HelpMessageGroup("Register Commands:");
691 : 121 : break;
692 : 161 : case OptionsCategory::CLI_COMMANDS:
693 [ + - + - ]: 322 : usage += HelpMessageGroup("CLI Commands:");
694 : 161 : break;
695 : : default:
696 : : break;
697 : : }
698 : :
699 : : // When we get to the hidden options, stop
700 [ + + ]: 2592 : if (arg_map.first == OptionsCategory::HIDDEN) break;
701 : :
702 [ + + ]: 11063 : for (const auto& arg : arg_map.second) {
703 [ + + + + ]: 9243 : if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
704 [ + - ]: 5724 : std::string name;
705 [ + - ]: 5724 : if (arg.second.m_help_param.empty()) {
706 [ + - ]: 5724 : name = arg.first;
707 : : } else {
708 [ # # ]: 0 : name = arg.first + arg.second.m_help_param;
709 : : }
710 [ + - ]: 11448 : usage += HelpMessageOpt(name, arg.second.m_help_text);
711 : 5724 : }
712 : : }
713 : : }
714 [ + - ]: 972 : return usage;
715 : 972 : }
716 : :
717 : 972 : bool HelpRequested(const ArgsManager& args)
718 : : {
719 [ + - + - : 4229 : return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
+ + + - +
- + + + -
+ - + + +
- + - + +
+ + + + -
- - - -
- ]
720 : : }
721 : :
722 : 2300 : void SetupHelpOptions(ArgsManager& args)
723 : : {
724 [ + - + - ]: 4600 : args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
725 [ + - ]: 2300 : args.AddHiddenArgs({"-h", "-?"});
726 : 2300 : }
727 : :
728 : : static const int screenWidth = 79;
729 : : static const int optIndent = 2;
730 : : static const int msgIndent = 7;
731 : :
732 : 3365 : std::string HelpMessageGroup(const std::string &message) {
733 [ + - ]: 10095 : return std::string(message) + std::string("\n\n");
734 : : }
735 : :
736 : 7349 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
737 [ + - + - ]: 14698 : return std::string(optIndent,' ') + std::string(option) +
738 [ + - + - : 29396 : std::string("\n") + std::string(msgIndent,' ') +
+ - ]
739 [ + - + - ]: 22047 : FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
740 [ + - ]: 22047 : std::string("\n\n");
741 : : }
742 : :
743 : : const std::vector<std::string> TEST_OPTIONS_DOC{
744 : : "addrman (use deterministic addrman)",
745 : : "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
746 : : "bip94 (enforce BIP94 consensus rules)",
747 : : };
748 : :
749 : 3144 : bool HasTestOption(const ArgsManager& args, const std::string& test_option)
750 : : {
751 [ + - ]: 3144 : const auto options = args.GetArgs("-test");
752 [ - + - + : 37728 : return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
- + + - -
+ + - - +
+ - - + +
- ]
753 [ # # ]: 0 : return option == test_option;
754 : 3144 : });
755 : 3144 : }
756 : :
757 : 0 : fs::path GetDefaultDataDir()
758 : : {
759 : : // Windows:
760 : : // old: C:\Users\Username\AppData\Roaming\Bitcoin
761 : : // new: C:\Users\Username\AppData\Local\Bitcoin
762 : : // macOS: ~/Library/Application Support/Bitcoin
763 : : // Unix-like: ~/.bitcoin
764 : : #ifdef WIN32
765 : : // Windows
766 : : // Check for existence of datadir in old location and keep it there
767 : : fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
768 : : if (fs::exists(legacy_path)) return legacy_path;
769 : :
770 : : // Otherwise, fresh installs can start in the new, "proper" location
771 : : return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
772 : : #else
773 : 0 : fs::path pathRet;
774 : 0 : char* pszHome = getenv("HOME");
775 [ # # # # ]: 0 : if (pszHome == nullptr || strlen(pszHome) == 0)
776 [ # # ]: 0 : pathRet = fs::path("/");
777 : : else
778 [ # # ]: 0 : pathRet = fs::path(pszHome);
779 : : #ifdef __APPLE__
780 : : // macOS
781 : : return pathRet / "Library/Application Support/Bitcoin";
782 : : #else
783 : : // Unix-like
784 [ # # # # ]: 0 : return pathRet / ".bitcoin";
785 : : #endif
786 : : #endif
787 : 0 : }
788 : :
789 : 0 : bool CheckDataDirOption(const ArgsManager& args)
790 : : {
791 [ # # # # ]: 0 : const fs::path datadir{args.GetPathArg("-datadir")};
792 [ # # # # : 0 : return datadir.empty() || fs::is_directory(fs::absolute(datadir));
# # # # ]
793 : 0 : }
794 : :
795 : 0 : fs::path ArgsManager::GetConfigFilePath() const
796 : : {
797 : 0 : LOCK(cs_args);
798 [ # # # # : 0 : return *Assert(m_config_path);
# # ]
799 : 0 : }
800 : :
801 : 0 : void ArgsManager::SetConfigFilePath(fs::path path)
802 : : {
803 : 0 : LOCK(cs_args);
804 [ # # ]: 0 : assert(!m_config_path);
805 [ # # ]: 0 : m_config_path = path;
806 : 0 : }
807 : :
808 : 1567 : ChainType ArgsManager::GetChainType() const
809 : : {
810 : 1567 : std::variant<ChainType, std::string> arg = GetChainArg();
811 [ + - ]: 1567 : if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
812 [ # # # # : 0 : throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
# # ]
813 : 1567 : }
814 : :
815 : 972 : std::string ArgsManager::GetChainTypeString() const
816 : : {
817 : 972 : auto arg = GetChainArg();
818 [ + + + - ]: 953 : if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
819 [ - + - + ]: 989 : return std::get<std::string>(arg);
820 : 953 : }
821 : :
822 : 2539 : std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
823 : : {
824 : 12695 : auto get_net = [&](const std::string& arg) {
825 : 10156 : LOCK(cs_args);
826 [ + - + - ]: 20312 : common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
827 : : /* ignore_default_section_config= */ false,
828 : : /*ignore_nonpersistent=*/false,
829 [ + - ]: 10156 : /* get_chain_type= */ true);
830 [ + + + + : 10156 : return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
+ - + - +
- ]
831 [ + - ]: 20312 : };
832 : :
833 [ + - ]: 2539 : const bool fRegTest = get_net("-regtest");
834 [ + - ]: 2539 : const bool fSigNet = get_net("-signet");
835 [ + - ]: 2539 : const bool fTestNet = get_net("-testnet");
836 [ + - ]: 2539 : const bool fTestNet4 = get_net("-testnet4");
837 [ + - ]: 2539 : const auto chain_arg = GetArg("-chain");
838 : :
839 [ + + ]: 2539 : if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
840 [ + - ]: 19 : throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
841 : : }
842 [ + + ]: 2520 : if (chain_arg) {
843 [ - + + - : 44 : if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
+ + ]
844 : : // Not a known string, so return original string
845 [ - + ]: 72 : return *chain_arg;
846 : : }
847 [ + + ]: 2476 : if (fRegTest) return ChainType::REGTEST;
848 [ + + ]: 2464 : if (fSigNet) return ChainType::SIGNET;
849 [ + + ]: 2457 : if (fTestNet) return ChainType::TESTNET;
850 [ + + ]: 2452 : if (fTestNet4) return ChainType::TESTNET4;
851 : 2446 : return ChainType::MAIN;
852 : 2520 : }
853 : :
854 : 1458678 : bool ArgsManager::UseDefaultSection(const std::string& arg) const
855 : : {
856 [ + + + + ]: 1458678 : return m_network == ChainTypeToString(ChainType::MAIN) || !m_network_only_args.contains(arg);
857 : : }
858 : :
859 : 1091281 : common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
860 : : {
861 : 1091281 : LOCK(cs_args);
862 : 1091281 : return common::GetSetting(
863 [ + - + - ]: 2182562 : m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
864 [ + - + - ]: 1091281 : /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
865 : 1091281 : }
866 : :
867 : 367397 : std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
868 : : {
869 : 367397 : LOCK(cs_args);
870 [ + - + - : 734794 : return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
+ - + - ]
871 : 367397 : }
872 : :
873 : 0 : void ArgsManager::logArgsPrefix(
874 : : const std::string& prefix,
875 : : const std::string& section,
876 : : const std::map<std::string, std::vector<common::SettingsValue>>& args) const
877 : : {
878 [ # # # # ]: 0 : std::string section_str = section.empty() ? "" : "[" + section + "] ";
879 [ # # ]: 0 : for (const auto& arg : args) {
880 [ # # ]: 0 : for (const auto& value : arg.second) {
881 [ # # # # ]: 0 : std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
882 [ # # ]: 0 : if (flags) {
883 [ # # # # : 0 : std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
# # ]
884 [ # # ]: 0 : LogInfo("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
885 : 0 : }
886 : : }
887 : : }
888 : 0 : }
889 : :
890 : 0 : void ArgsManager::LogArgs() const
891 : : {
892 : 0 : LOCK(cs_args);
893 [ # # ]: 0 : for (const auto& section : m_settings.ro_config) {
894 [ # # # # ]: 0 : logArgsPrefix("Config file arg:", section.first, section.second);
895 : : }
896 [ # # ]: 0 : for (const auto& setting : m_settings.rw_settings) {
897 [ # # # # ]: 0 : LogInfo("Setting file arg: %s = %s\n", setting.first, setting.second.write());
898 : : }
899 [ # # # # : 0 : logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
# # # # ]
900 : 0 : }
|