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 <codecvt>
23 : : #include <shellapi.h>
24 : : #include <shlobj.h>
25 : : #endif
26 : :
27 : : #include <algorithm>
28 : : #include <cassert>
29 : : #include <cstdint>
30 : : #include <cstdlib>
31 : : #include <cstring>
32 : : #include <map>
33 : : #include <optional>
34 : : #include <stdexcept>
35 : : #include <string>
36 : : #include <utility>
37 : : #include <variant>
38 : :
39 : : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
40 : : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
41 : :
42 : : ArgsManager gArgs;
43 : :
44 : : /**
45 : : * Interpret a string argument as a boolean.
46 : : *
47 : : * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
48 : : * like "foo", return 0. This means that if a user unintentionally supplies a
49 : : * non-integer argument here, the return value is always false. This means that
50 : : * -foo=false does what the user probably expects, but -foo=true is well defined
51 : : * but does not do what they probably expected.
52 : : *
53 : : * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
54 : : * representable as an int.
55 : : *
56 : : * For a more extensive discussion of this topic (and a wide range of opinions
57 : : * on the Right Way to change this code), see PR12713.
58 : : */
59 : 340369 : static bool InterpretBool(const std::string& strValue)
60 : : {
61 [ + + ]: 340369 : if (strValue.empty())
62 : : return true;
63 [ - + ]: 332109 : return (LocaleIndependentAtoi<int>(strValue) != 0);
64 : : }
65 : :
66 : 1409780 : static std::string SettingName(const std::string& arg)
67 : : {
68 [ - + + - : 1410995 : return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
+ + ]
69 : : }
70 : :
71 : : /**
72 : : * Parse "name", "section.name", "noname", "section.noname" settings keys.
73 : : *
74 : : * @note Where an option was negated can be later checked using the
75 : : * IsArgNegated() method. One use case for this is to have a way to disable
76 : : * options that are not normally boolean (e.g. using -nodebuglogfile to request
77 : : * that debug log output is not sent to any file at all).
78 : : */
79 : 384092 : KeyInfo InterpretKey(std::string key)
80 : : {
81 [ + + ]: 384092 : KeyInfo result;
82 : : // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
83 : 384092 : size_t option_index = key.find('.');
84 [ + + ]: 384092 : if (option_index != std::string::npos) {
85 [ + - ]: 137998 : result.section = key.substr(0, option_index);
86 [ + - ]: 137998 : key.erase(0, option_index + 1);
87 : : }
88 [ - + + + ]: 384092 : if (key.starts_with("no")) {
89 [ + - ]: 105598 : key.erase(0, 2);
90 : 105598 : result.negated = true;
91 : : }
92 [ + - ]: 384092 : result.name = key;
93 : 384092 : return result;
94 : 0 : }
95 : :
96 : : /**
97 : : * Interpret settings value based on registered flags.
98 : : *
99 : : * @param[in] key key information to know if key was negated
100 : : * @param[in] value string value of setting to be parsed
101 : : * @param[in] flags ArgsManager registered argument flags
102 : : * @param[out] error Error description if settings value is not valid
103 : : *
104 : : * @return parsed settings value if it is valid, otherwise nullopt accompanied
105 : : * by a descriptive error string
106 : : */
107 : 362802 : std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
108 : : unsigned int flags, std::string& error)
109 : : {
110 : : // Return negated settings as false values.
111 [ + + ]: 362802 : if (key.negated) {
112 [ - + ]: 105597 : if (flags & ArgsManager::DISALLOW_NEGATION) {
113 : 0 : error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
114 : 0 : return std::nullopt;
115 : : }
116 : : // Double negatives like -nofoo=0 are supported (but discouraged)
117 [ + + + + ]: 105597 : if (value && !InterpretBool(*value)) {
118 : 11 : LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
119 : 11 : return true;
120 : : }
121 : 105586 : return false;
122 : : }
123 [ + + + + ]: 257205 : if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
124 : 1 : error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
125 : 1 : return std::nullopt;
126 : : }
127 [ + - ]: 257204 : return value ? *value : "";
128 : : }
129 : :
130 : : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
131 : : // #include class definitions for all members.
132 : : // For example, m_settings has an internal dependency on univalue.
133 : 52084 : ArgsManager::ArgsManager() = default;
134 [ + + ]: 260415 : ArgsManager::~ArgsManager() = default;
135 : :
136 : 49251 : std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
137 : : {
138 [ + - ]: 49251 : std::set<std::string> unsuitables;
139 : :
140 [ + - ]: 49251 : LOCK(cs_args);
141 : :
142 : : // if there's no section selected, don't worry
143 [ - + ]: 49251 : if (m_network.empty()) return std::set<std::string> {};
144 : :
145 : : // if it's okay to use the default section for this network, don't worry
146 [ + - + + ]: 49251 : if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
147 : :
148 [ + + ]: 64440 : for (const auto& arg : m_network_only_args) {
149 [ + - + - : 27600 : if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
+ + ]
150 [ + - ]: 1753 : unsuitables.insert(arg);
151 : : }
152 : : }
153 : 36840 : return unsuitables;
154 : 49251 : }
155 : :
156 : 1762 : std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
157 : : {
158 : : // Section names to be recognized in the config file.
159 : 1762 : static const std::set<std::string> available_sections{
160 : : ChainTypeToString(ChainType::REGTEST),
161 : : ChainTypeToString(ChainType::SIGNET),
162 : : ChainTypeToString(ChainType::TESTNET),
163 : : ChainTypeToString(ChainType::TESTNET4),
164 : : ChainTypeToString(ChainType::MAIN),
165 [ + + + - : 9268 : };
- + + + -
- ]
166 : :
167 : 1762 : LOCK(cs_args);
168 [ + - ]: 1762 : std::list<SectionInfo> unrecognized = m_config_sections;
169 : 2894 : unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
170 [ + - ]: 1762 : return unrecognized;
171 [ + - + - : 3013 : }
+ - + - +
- - - ]
172 : :
173 : 3409 : void ArgsManager::SelectConfigNetwork(const std::string& network)
174 : : {
175 : 3409 : LOCK(cs_args);
176 [ + - + - ]: 6818 : m_network = network;
177 : 3409 : }
178 : :
179 : 52012 : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
180 : : {
181 : 52012 : LOCK(cs_args);
182 : 52012 : m_settings.command_line_options.clear();
183 : :
184 [ + + ]: 201752 : for (int i = 1; i < argc; i++) {
185 [ + - ]: 151256 : std::string key(argv[i]);
186 : :
187 : : #ifdef __APPLE__
188 : : // At the first time when a user gets the "App downloaded from the
189 : : // internet" warning, and clicks the Open button, macOS passes
190 : : // a unique process serial number (PSN) as -psn_... command-line
191 : : // argument, which we filter out.
192 : : if (key.starts_with("-psn_")) continue;
193 : : #endif
194 : :
195 [ + + ]: 151256 : if (key == "-") break; //bitcoin-tx using stdin
196 : 151244 : std::optional<std::string> val;
197 : 151244 : size_t is_index = key.find('=');
198 [ + + ]: 151244 : if (is_index != std::string::npos) {
199 [ + - ]: 138216 : val = key.substr(is_index + 1);
200 [ + - ]: 138216 : key.erase(is_index);
201 : : }
202 : : #ifdef WIN32
203 : : key = ToLower(key);
204 : : if (key[0] == '/')
205 : : key[0] = '-';
206 : : #endif
207 : :
208 [ + + ]: 151244 : if (key[0] != '-') {
209 [ + + + - ]: 1493 : if (!m_accept_any_command && m_command.empty()) {
210 : : // The first non-dash arg is a registered command
211 [ + - ]: 40 : std::optional<unsigned int> flags = GetArgFlags(key);
212 [ + + - + ]: 40 : if (!flags || !(*flags & ArgsManager::COMMAND)) {
213 [ + - ]: 4 : error = strprintf("Invalid command '%s'", argv[i]);
214 : 4 : return false;
215 : : }
216 : : }
217 [ + - ]: 1489 : m_command.push_back(key);
218 [ + + ]: 2545 : while (++i < argc) {
219 : : // The remaining args are command args
220 [ + - ]: 1056 : m_command.emplace_back(argv[i]);
221 : : }
222 : 1489 : break;
223 : : }
224 : :
225 : : // Transform --foo to -foo
226 [ - + + - : 149751 : if (key.length() > 1 && key[1] == '-')
+ + ]
227 [ + - ]: 6 : key.erase(0, 1);
228 : :
229 : : // Transform -foo to foo
230 [ + - ]: 149751 : key.erase(0, 1);
231 [ - + + - ]: 299502 : KeyInfo keyinfo = InterpretKey(key);
232 [ + - + - ]: 149751 : std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
233 : :
234 : : // Unknown command line options and command line options with dot
235 : : // characters (which are returned from InterpretKey with nonempty
236 : : // section strings) are not valid.
237 [ + + + + ]: 149751 : if (!flags || !keyinfo.section.empty()) {
238 [ + - ]: 10 : error = strprintf("Invalid parameter %s", argv[i]);
239 : 10 : return false;
240 : : }
241 : :
242 [ + + + - ]: 161354 : std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
243 [ + + ]: 149741 : if (!value) return false;
244 : :
245 [ + - + - ]: 149740 : m_settings.command_line_options[keyinfo.name].push_back(*value);
246 : 302497 : }
247 : :
248 : : // we do not allow -includeconf from command line, only -noincludeconf
249 [ + - + + ]: 51997 : if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
250 : 5 : const common::SettingsSpan values{*includes};
251 : : // Range may be empty if -noincludeconf was passed
252 [ + - + + ]: 5 : if (!values.empty()) {
253 [ + - + - : 4 : error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
+ - ]
254 : 4 : return false; // pick first value as example
255 : : }
256 : : }
257 : : return true;
258 : 52012 : }
259 : :
260 : 424068 : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
261 : : {
262 : 424068 : LOCK(cs_args);
263 [ + + ]: 863788 : for (const auto& arg_map : m_available_args) {
264 : 842627 : const auto search = arg_map.second.find(name);
265 [ + + ]: 842627 : if (search != arg_map.second.end()) {
266 : 402907 : return search->second.m_flags;
267 : : }
268 : : }
269 : 21161 : return m_default_flags;
270 : 424068 : }
271 : :
272 : 0 : void ArgsManager::SetDefaultFlags(std::optional<unsigned int> flags)
273 : : {
274 : 0 : LOCK(cs_args);
275 [ # # ]: 0 : m_default_flags = flags;
276 : 0 : }
277 : :
278 : 29638 : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
279 : : {
280 [ + + ]: 29638 : if (IsArgNegated(arg)) return fs::path{};
281 [ + - ]: 29628 : std::string path_str = GetArg(arg, "");
282 [ + + + - ]: 42593 : if (path_str.empty()) return default_value;
283 [ + - + - ]: 38895 : fs::path result = fs::PathFromString(path_str).lexically_normal();
284 : : // Remove trailing slash, if present.
285 [ + + + - : 38895 : return result.has_filename() ? result : result.parent_path();
+ - ]
286 : 42593 : }
287 : :
288 : 8374 : fs::path ArgsManager::GetBlocksDirPath() const
289 : : {
290 : 8374 : LOCK(cs_args);
291 : 8374 : fs::path& path = m_cached_blocks_path;
292 : :
293 : : // Cache the path to avoid calling fs::create_directories on every call of
294 : : // this function
295 [ + + + - ]: 8374 : if (!path.empty()) return path;
296 : :
297 [ + - + - : 1943 : if (IsArgSet("-blocksdir")) {
+ + ]
298 [ + - + - : 12 : path = fs::absolute(GetPathArg("-blocksdir"));
+ - ]
299 [ + - + + ]: 3 : if (!fs::is_directory(path)) {
300 [ + - ]: 1 : path = "";
301 [ + - ]: 1 : return path;
302 : : }
303 : : } else {
304 [ + - ]: 3880 : path = GetDataDirBase();
305 : : }
306 : :
307 [ + - + - ]: 3884 : path /= fs::PathFromString(BaseParams().DataDir());
308 [ + - ]: 1942 : path /= "blocks";
309 [ + - ]: 1942 : fs::create_directories(path);
310 [ + - + - ]: 8374 : return path;
311 : 8374 : }
312 : :
313 : 41837 : fs::path ArgsManager::GetDataDir(bool net_specific) const
314 : : {
315 : 41837 : LOCK(cs_args);
316 [ + + ]: 41837 : fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
317 : :
318 : : // Used cached path if available
319 [ + + + - : 49100 : if (!path.empty()) return path;
+ - ]
320 : :
321 [ + - + - ]: 14526 : const fs::path datadir{GetPathArg("-datadir")};
322 [ + + ]: 7263 : if (!datadir.empty()) {
323 [ + - ]: 14516 : path = fs::absolute(datadir);
324 [ + - - + ]: 7258 : if (!fs::is_directory(path)) {
325 [ # # ]: 0 : path = "";
326 [ # # ]: 0 : return path;
327 : : }
328 : : } else {
329 [ + - ]: 15 : path = GetDefaultDataDir();
330 : : }
331 : :
332 [ + + + - : 7263 : if (net_specific && !BaseParams().DataDir().empty()) {
+ + ]
333 [ + - + - ]: 7179 : path /= fs::PathFromString(BaseParams().DataDir());
334 : : }
335 : :
336 [ + - ]: 7263 : return path;
337 : 49100 : }
338 : :
339 : 2846 : void ArgsManager::ClearPathCache()
340 : : {
341 : 2846 : LOCK(cs_args);
342 : :
343 : 2846 : m_cached_datadir_path = fs::path();
344 : 2846 : m_cached_network_datadir_path = fs::path();
345 [ + - ]: 5692 : m_cached_blocks_path = fs::path();
346 : 2846 : }
347 : :
348 : 37 : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
349 : : {
350 [ + - ]: 37 : Command ret;
351 [ + - ]: 37 : LOCK(cs_args);
352 [ + + ]: 37 : auto it = m_command.begin();
353 [ + + ]: 37 : if (it == m_command.end()) {
354 : : // No command was passed
355 : 1 : return std::nullopt;
356 : : }
357 [ + - ]: 36 : if (!m_accept_any_command) {
358 : : // The registered command
359 [ + - ]: 36 : ret.command = *(it++);
360 : : }
361 [ + + ]: 46 : while (it != m_command.end()) {
362 : : // The unregistered command and args (if any)
363 [ + - ]: 10 : ret.args.push_back(*(it++));
364 : : }
365 : 36 : return ret;
366 : 74 : }
367 : :
368 : 175335 : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
369 : : {
370 : 175335 : std::vector<std::string> result;
371 [ + - + + ]: 270971 : for (const common::SettingsValue& value : GetSettingsList(strArg)) {
372 [ - + - - : 286904 : result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
+ + + - +
- - + +
- ]
373 : : }
374 : 175335 : return result;
375 : 0 : }
376 : :
377 : 131255 : bool ArgsManager::IsArgSet(const std::string& strArg) const
378 : : {
379 : 131255 : return !GetSetting(strArg).isNull();
380 : : }
381 : :
382 : 4966 : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
383 : : {
384 [ + - + - ]: 9932 : fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
385 [ + + ]: 4966 : if (settings.empty()) {
386 : : return false;
387 : : }
388 [ - + ]: 4963 : if (backup) {
389 [ # # ]: 0 : settings += ".bak";
390 : : }
391 [ + + ]: 4963 : if (filepath) {
392 [ + + + - : 25580 : *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
+ - + - +
+ - - ]
393 : : }
394 : : return true;
395 : 4966 : }
396 : :
397 : 4 : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
398 : : {
399 [ + + ]: 8 : for (const auto& error : errors) {
400 [ + + ]: 4 : if (error_out) {
401 : 3 : error_out->emplace_back(error);
402 : : } else {
403 : 1 : LogPrintf("%s\n", error);
404 : : }
405 : : }
406 : 4 : }
407 : :
408 : 1146 : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
409 : : {
410 : 1146 : fs::path path;
411 [ + - + - ]: 1146 : if (!GetSettingsPath(&path, /* temp= */ false)) {
412 : : return true; // Do nothing if settings file disabled.
413 : : }
414 : :
415 [ + - ]: 1146 : LOCK(cs_args);
416 : 1146 : m_settings.rw_settings.clear();
417 : 1146 : std::vector<std::string> read_errors;
418 [ + - + + ]: 1146 : if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
419 [ + - + - ]: 3 : SaveErrors(read_errors, errors);
420 : 3 : return false;
421 : : }
422 [ + + ]: 1280 : for (const auto& setting : m_settings.rw_settings) {
423 [ - + + - ]: 274 : KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
424 [ + - + - : 137 : if (!GetArgFlags('-' + key.name)) {
+ + ]
425 [ + - ]: 7 : LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
426 : : }
427 : 137 : }
428 : : return true;
429 [ + - ]: 3438 : }
430 : :
431 : 1336 : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
432 : : {
433 : 1336 : fs::path path, path_tmp;
434 [ + - + - : 1336 : if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
+ - - + ]
435 [ # # ]: 0 : throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
436 : : }
437 : :
438 [ + - ]: 1336 : LOCK(cs_args);
439 : 1336 : std::vector<std::string> write_errors;
440 [ + - - + ]: 1336 : if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
441 [ # # # # ]: 0 : SaveErrors(write_errors, errors);
442 : 0 : return false;
443 : : }
444 [ + - + - : 4008 : if (!RenameOver(path_tmp, path)) {
+ - + + ]
445 [ - + + - : 4 : SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
+ - + + -
- ]
446 : 1 : return false;
447 : : }
448 : : return true;
449 [ - + + - : 5346 : }
+ - ]
450 : :
451 : 0 : common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
452 : : {
453 : 0 : LOCK(cs_args);
454 [ # # # # : 0 : return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
# # ]
455 [ # # ]: 0 : /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
456 : 0 : }
457 : :
458 : 82268 : bool ArgsManager::IsArgNegated(const std::string& strArg) const
459 : : {
460 : 82268 : return GetSetting(strArg).isFalse();
461 : : }
462 : :
463 : 91456 : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
464 : : {
465 [ + - ]: 182910 : return GetArg(strArg).value_or(strDefault);
466 : : }
467 : :
468 : 168593 : std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
469 : : {
470 : 168593 : const common::SettingsValue value = GetSetting(strArg);
471 [ + + ]: 337184 : return SettingToString(value);
472 : 168593 : }
473 : :
474 : 168593 : std::optional<std::string> SettingToString(const common::SettingsValue& value)
475 : : {
476 [ + + ]: 168593 : if (value.isNull()) return std::nullopt;
477 [ + + ]: 65232 : if (value.isFalse()) return "0";
478 [ + + ]: 53520 : if (value.isTrue()) return "1";
479 [ + + - + ]: 53515 : if (value.isNum()) return value.getValStr();
480 [ - + ]: 107016 : return value.get_str();
481 : : }
482 : :
483 : 0 : std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
484 : : {
485 [ # # ]: 0 : return SettingToString(value).value_or(strDefault);
486 : : }
487 : :
488 : 171741 : int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
489 : : {
490 [ + + ]: 171741 : return GetIntArg(strArg).value_or(nDefault);
491 : : }
492 : :
493 : 203801 : std::optional<int64_t> ArgsManager::GetIntArg(const std::string& strArg) const
494 : : {
495 : 203801 : const common::SettingsValue value = GetSetting(strArg);
496 [ + + ]: 407599 : return SettingToInt(value);
497 : 203801 : }
498 : :
499 : 203801 : std::optional<int64_t> SettingToInt(const common::SettingsValue& value)
500 : : {
501 [ + + ]: 203801 : if (value.isNull()) return std::nullopt;
502 [ + + ]: 11833 : if (value.isFalse()) return 0;
503 [ + + ]: 11828 : if (value.isTrue()) return 1;
504 [ + + ]: 11825 : if (value.isNum()) return value.getInt<int64_t>();
505 [ - + ]: 11822 : return LocaleIndependentAtoi<int64_t>(value.get_str());
506 : : }
507 : :
508 : 0 : int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
509 : : {
510 [ # # ]: 0 : return SettingToInt(value).value_or(nDefault);
511 : : }
512 : :
513 : 509841 : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
514 : : {
515 [ + + ]: 509841 : return GetBoolArg(strArg).value_or(fDefault);
516 : : }
517 : :
518 : 529009 : std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
519 : : {
520 : 529009 : const common::SettingsValue value = GetSetting(strArg);
521 [ + + ]: 1058008 : return SettingToBool(value);
522 : 529009 : }
523 : :
524 : 529009 : std::optional<bool> SettingToBool(const common::SettingsValue& value)
525 : : {
526 [ + + ]: 529009 : if (value.isNull()) return std::nullopt;
527 [ + + ]: 228864 : if (value.isBool()) return value.get_bool();
528 : 227268 : return InterpretBool(value.get_str());
529 : : }
530 : :
531 : 0 : bool SettingToBool(const common::SettingsValue& value, bool fDefault)
532 : : {
533 [ # # ]: 0 : return SettingToBool(value).value_or(fDefault);
534 : : }
535 : :
536 : 52204 : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
537 : : {
538 : 52204 : LOCK(cs_args);
539 [ + - + + ]: 52204 : if (IsArgSet(strArg)) return false;
540 [ + - ]: 1938 : ForceSetArg(strArg, strValue);
541 : : return true;
542 : 52204 : }
543 : :
544 : 4708 : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
545 : : {
546 [ + + ]: 4708 : if (fValue)
547 [ + - ]: 2256 : return SoftSetArg(strArg, std::string("1"));
548 : : else
549 [ + - ]: 2452 : return SoftSetArg(strArg, std::string("0"));
550 : : }
551 : :
552 : 51345 : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
553 : : {
554 : 51345 : LOCK(cs_args);
555 [ + - + - : 51345 : m_settings.forced_settings[SettingName(strArg)] = strValue;
+ - + - ]
556 : 51345 : }
557 : :
558 : 147 : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
559 : : {
560 : 147 : Assert(cmd.find('=') == std::string::npos);
561 : 147 : Assert(cmd.at(0) != '-');
562 : :
563 : 147 : LOCK(cs_args);
564 : 147 : m_accept_any_command = false; // latch to false
565 [ + - ]: 147 : std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
566 [ + - - + : 294 : auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
+ - ]
567 [ + - ]: 147 : Assert(ret.second); // Fail on duplicate commands
568 : 147 : }
569 : :
570 : 434431 : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
571 : : {
572 : 434431 : Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
573 : :
574 : : // Split arg name from its help param
575 : 434431 : size_t eq_index = name.find('=');
576 [ + + ]: 434431 : if (eq_index == std::string::npos) {
577 [ - + ]: 224475 : eq_index = name.size();
578 : : }
579 : 434431 : std::string arg_name = name.substr(0, eq_index);
580 : :
581 [ + - ]: 434431 : LOCK(cs_args);
582 [ + - ]: 434431 : std::map<std::string, Arg>& arg_map = m_available_args[cat];
583 [ - + + - : 868862 : auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
- + + - ]
584 [ - + ]: 434431 : assert(ret.second); // Make sure an insertion actually happened
585 : :
586 [ + + ]: 434431 : if (flags & ArgsManager::NETWORK_ONLY) {
587 [ + - ]: 15532 : m_network_only_args.emplace(arg_name);
588 : : }
589 : 434431 : }
590 : :
591 : 4815 : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
592 : : {
593 [ + + ]: 25275 : for (const std::string& name : names) {
594 [ + - ]: 40920 : AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
595 : : }
596 : 4815 : }
597 : :
598 : 625 : void ArgsManager::ClearArgs()
599 : : {
600 : 625 : LOCK(cs_args);
601 : 625 : m_settings = {};
602 : 625 : m_available_args.clear();
603 [ + - ]: 625 : m_network_only_args.clear();
604 : 625 : }
605 : :
606 : 1057 : void ArgsManager::CheckMultipleCLIArgs() const
607 : : {
608 : 1057 : LOCK(cs_args);
609 : 1057 : std::vector<std::string> found{};
610 : 1057 : auto cmds = m_available_args.find(OptionsCategory::CLI_COMMANDS);
611 [ + - ]: 1057 : if (cmds != m_available_args.end()) {
612 [ + - + + ]: 5285 : for (const auto& [cmd, argspec] : cmds->second) {
613 [ + - + + ]: 4228 : if (IsArgSet(cmd)) {
614 [ + - ]: 42 : found.push_back(cmd);
615 : : }
616 : : }
617 [ - + + + ]: 1057 : if (found.size() > 1) {
618 [ + - + - : 2 : throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
+ - ]
619 : : }
620 : : }
621 [ + - ]: 2113 : }
622 : :
623 : 1 : std::string ArgsManager::GetHelpMessage() const
624 : : {
625 [ + - ]: 1 : const bool show_debug = GetBoolArg("-help-debug", false);
626 : :
627 [ + - ]: 1 : std::string usage;
628 [ + - ]: 1 : LOCK(cs_args);
629 [ + - ]: 11 : for (const auto& arg_map : m_available_args) {
630 [ + + + + : 11 : switch(arg_map.first) {
+ + + - +
+ + - - -
- + ]
631 : 1 : case OptionsCategory::OPTIONS:
632 [ + - + - ]: 2 : usage += HelpMessageGroup("Options:");
633 : 1 : break;
634 : 1 : case OptionsCategory::CONNECTION:
635 [ + - + - ]: 2 : usage += HelpMessageGroup("Connection options:");
636 : 1 : break;
637 : 1 : case OptionsCategory::ZMQ:
638 [ + - + - ]: 2 : usage += HelpMessageGroup("ZeroMQ notification options:");
639 : 1 : break;
640 : 1 : case OptionsCategory::DEBUG_TEST:
641 [ + - + - ]: 2 : usage += HelpMessageGroup("Debugging/Testing options:");
642 : 1 : break;
643 : 1 : case OptionsCategory::NODE_RELAY:
644 [ + - + - ]: 2 : usage += HelpMessageGroup("Node relay options:");
645 : 1 : break;
646 : 1 : case OptionsCategory::BLOCK_CREATION:
647 [ + - + - ]: 2 : usage += HelpMessageGroup("Block creation options:");
648 : 1 : break;
649 : 1 : case OptionsCategory::RPC:
650 [ + - + - ]: 2 : usage += HelpMessageGroup("RPC server options:");
651 : 1 : break;
652 : 0 : case OptionsCategory::IPC:
653 [ # # # # ]: 0 : usage += HelpMessageGroup("IPC interprocess connection options:");
654 : 0 : break;
655 : 1 : case OptionsCategory::WALLET:
656 [ + - + - ]: 2 : usage += HelpMessageGroup("Wallet options:");
657 : 1 : break;
658 : 1 : case OptionsCategory::WALLET_DEBUG_TEST:
659 [ - + - - : 1 : if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
- - ]
660 : : break;
661 : 1 : case OptionsCategory::CHAINPARAMS:
662 [ + - + - ]: 2 : usage += HelpMessageGroup("Chain selection options:");
663 : 1 : break;
664 : 0 : case OptionsCategory::GUI:
665 [ # # # # ]: 0 : usage += HelpMessageGroup("UI Options:");
666 : 0 : break;
667 : 0 : case OptionsCategory::COMMANDS:
668 [ # # # # ]: 0 : usage += HelpMessageGroup("Commands:");
669 : 0 : break;
670 : 0 : case OptionsCategory::REGISTER_COMMANDS:
671 [ # # # # ]: 0 : usage += HelpMessageGroup("Register Commands:");
672 : 0 : break;
673 : 0 : case OptionsCategory::CLI_COMMANDS:
674 [ # # # # ]: 0 : usage += HelpMessageGroup("CLI Commands:");
675 : 0 : break;
676 : : default:
677 : : break;
678 : : }
679 : :
680 : : // When we get to the hidden options, stop
681 [ + + ]: 11 : if (arg_map.first == OptionsCategory::HIDDEN) break;
682 : :
683 [ + + ]: 190 : for (const auto& arg : arg_map.second) {
684 [ + - + + ]: 180 : if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
685 [ + + ]: 139 : std::string name;
686 [ + + ]: 139 : if (arg.second.m_help_param.empty()) {
687 [ + - ]: 57 : name = arg.first;
688 : : } else {
689 [ + - ]: 82 : name = arg.first + arg.second.m_help_param;
690 : : }
691 [ + - ]: 278 : usage += HelpMessageOpt(name, arg.second.m_help_text);
692 : 139 : }
693 : : }
694 : : }
695 [ + - ]: 1 : return usage;
696 : 1 : }
697 : :
698 : 2342 : bool HelpRequested(const ArgsManager& args)
699 : : {
700 [ + - + - : 11708 : return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
+ - + - +
- + + + -
+ - + - +
- + - + -
+ + + - -
- - - -
- ]
701 : : }
702 : :
703 : 3010 : void SetupHelpOptions(ArgsManager& args)
704 : : {
705 [ + - + - ]: 6020 : args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
706 [ + - ]: 3010 : args.AddHiddenArgs({"-h", "-?"});
707 : 3010 : }
708 : :
709 : : static const int screenWidth = 79;
710 : : static const int optIndent = 2;
711 : : static const int msgIndent = 7;
712 : :
713 : 9 : std::string HelpMessageGroup(const std::string &message) {
714 [ + - ]: 27 : return std::string(message) + std::string("\n\n");
715 : : }
716 : :
717 : 139 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
718 [ + - + - ]: 278 : return std::string(optIndent,' ') + std::string(option) +
719 [ + - + - : 556 : std::string("\n") + std::string(msgIndent,' ') +
+ - ]
720 [ + - + - ]: 417 : FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
721 [ + - ]: 417 : std::string("\n\n");
722 : : }
723 : :
724 : : const std::vector<std::string> TEST_OPTIONS_DOC{
725 : : "addrman (use deterministic addrman)",
726 : : "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
727 : : "bip94 (enforce BIP94 consensus rules)",
728 : : };
729 : :
730 : 4237 : bool HasTestOption(const ArgsManager& args, const std::string& test_option)
731 : : {
732 [ + - ]: 4237 : const auto options = args.GetArgs("-test");
733 [ - + - + : 50844 : return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
- + + - -
+ + - - +
+ - - + +
- ]
734 [ + + ]: 25 : return option == test_option;
735 : 4237 : });
736 : 4237 : }
737 : :
738 : 1115 : fs::path GetDefaultDataDir()
739 : : {
740 : : // Windows:
741 : : // old: C:\Users\Username\AppData\Roaming\Bitcoin
742 : : // new: C:\Users\Username\AppData\Local\Bitcoin
743 : : // macOS: ~/Library/Application Support/Bitcoin
744 : : // Unix-like: ~/.bitcoin
745 : : #ifdef WIN32
746 : : // Windows
747 : : // Check for existence of datadir in old location and keep it there
748 : : fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
749 : : if (fs::exists(legacy_path)) return legacy_path;
750 : :
751 : : // Otherwise, fresh installs can start in the new, "proper" location
752 : : return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
753 : : #else
754 : 1115 : fs::path pathRet;
755 : 1115 : char* pszHome = getenv("HOME");
756 [ + - - + ]: 1115 : if (pszHome == nullptr || strlen(pszHome) == 0)
757 [ # # ]: 0 : pathRet = fs::path("/");
758 : : else
759 [ + - ]: 2230 : pathRet = fs::path(pszHome);
760 : : #ifdef __APPLE__
761 : : // macOS
762 : : return pathRet / "Library/Application Support/Bitcoin";
763 : : #else
764 : : // Unix-like
765 [ + - + - ]: 3345 : return pathRet / ".bitcoin";
766 : : #endif
767 : : #endif
768 : 1115 : }
769 : :
770 : 4473 : bool CheckDataDirOption(const ArgsManager& args)
771 : : {
772 [ + - + - ]: 8946 : const fs::path datadir{args.GetPathArg("-datadir")};
773 [ + + + - : 8941 : return datadir.empty() || fs::is_directory(fs::absolute(datadir));
+ - + + ]
774 : 4473 : }
775 : :
776 : 3339 : fs::path ArgsManager::GetConfigFilePath() const
777 : : {
778 : 3339 : LOCK(cs_args);
779 [ + - + - : 3339 : return *Assert(m_config_path);
+ - ]
780 : 3339 : }
781 : :
782 : 1 : void ArgsManager::SetConfigFilePath(fs::path path)
783 : : {
784 : 1 : LOCK(cs_args);
785 [ - + ]: 1 : assert(!m_config_path);
786 [ + - ]: 1 : m_config_path = path;
787 : 1 : }
788 : :
789 : 4119 : ChainType ArgsManager::GetChainType() const
790 : : {
791 : 4119 : std::variant<ChainType, std::string> arg = GetChainArg();
792 [ + - ]: 4119 : if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
793 [ # # # # : 0 : throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
# # ]
794 : 4119 : }
795 : :
796 : 5829 : std::string ArgsManager::GetChainTypeString() const
797 : : {
798 : 5829 : auto arg = GetChainArg();
799 [ + - + - ]: 5642 : if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
800 [ - - - - ]: 5642 : return std::get<std::string>(arg);
801 : 5642 : }
802 : :
803 : 9948 : std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
804 : : {
805 : 49740 : auto get_net = [&](const std::string& arg) {
806 : 39792 : LOCK(cs_args);
807 [ + - + - ]: 79584 : common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
808 : : /* ignore_default_section_config= */ false,
809 : : /*ignore_nonpersistent=*/false,
810 [ + - ]: 39792 : /* get_chain_type= */ true);
811 [ + + - + : 39792 : return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
- - + - +
- ]
812 [ + - ]: 79584 : };
813 : :
814 [ + - ]: 9948 : const bool fRegTest = get_net("-regtest");
815 [ + - ]: 9948 : const bool fSigNet = get_net("-signet");
816 [ + - ]: 9948 : const bool fTestNet = get_net("-testnet");
817 [ + - ]: 9948 : const bool fTestNet4 = get_net("-testnet4");
818 [ + - ]: 9948 : const auto chain_arg = GetArg("-chain");
819 : :
820 [ + + ]: 9948 : if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
821 [ + - ]: 187 : throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
822 : : }
823 [ + + ]: 9761 : if (chain_arg) {
824 [ - + + - : 28 : if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
+ - ]
825 : : // Not a known string, so return original string
826 [ # # ]: 0 : return *chain_arg;
827 : : }
828 [ + + ]: 9733 : if (fRegTest) return ChainType::REGTEST;
829 [ + + ]: 1777 : if (fSigNet) return ChainType::SIGNET;
830 [ + + ]: 1650 : if (fTestNet) return ChainType::TESTNET;
831 [ + + ]: 1642 : if (fTestNet4) return ChainType::TESTNET4;
832 : 1304 : return ChainType::MAIN;
833 : 9761 : }
834 : :
835 : 1291043 : bool ArgsManager::UseDefaultSection(const std::string& arg) const
836 : : {
837 [ + + + + ]: 1291043 : return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
838 : : }
839 : :
840 : 1114952 : common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
841 : : {
842 : 1114952 : LOCK(cs_args);
843 : 1114952 : return common::GetSetting(
844 [ + - + - ]: 2229904 : m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
845 [ + - + - ]: 1114952 : /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
846 : 1114952 : }
847 : :
848 : 176091 : std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
849 : : {
850 : 176091 : LOCK(cs_args);
851 [ + - + - : 352182 : return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
+ - + - ]
852 : 176091 : }
853 : :
854 : 3323 : void ArgsManager::logArgsPrefix(
855 : : const std::string& prefix,
856 : : const std::string& section,
857 : : const std::map<std::string, std::vector<common::SettingsValue>>& args) const
858 : : {
859 [ + + + - ]: 4428 : std::string section_str = section.empty() ? "" : "[" + section + "] ";
860 [ + + ]: 40868 : for (const auto& arg : args) {
861 [ + + ]: 77481 : for (const auto& value : arg.second) {
862 [ + - + - ]: 39936 : std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
863 [ + - ]: 39936 : if (flags) {
864 [ + + + - : 39936 : std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
+ - ]
865 [ + - ]: 39936 : LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
866 : 39936 : }
867 : : }
868 : : }
869 : 3323 : }
870 : :
871 : 1111 : void ArgsManager::LogArgs() const
872 : : {
873 : 1111 : LOCK(cs_args);
874 [ + + ]: 3323 : for (const auto& section : m_settings.ro_config) {
875 [ + - + - ]: 4424 : logArgsPrefix("Config file arg:", section.first, section.second);
876 : : }
877 [ + + ]: 1243 : for (const auto& setting : m_settings.rw_settings) {
878 [ + - + - ]: 264 : LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
879 : : }
880 [ + - + - : 2222 : logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
+ - + - ]
881 : 1111 : }
882 : :
883 : : namespace common {
884 : : #ifdef WIN32
885 : : WinCmdLineArgs::WinCmdLineArgs()
886 : : {
887 : : wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
888 : : std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
889 : : argv = new char*[argc];
890 : : args.resize(argc);
891 : : for (int i = 0; i < argc; i++) {
892 : : args[i] = utf8_cvt.to_bytes(wargv[i]);
893 : : argv[i] = &*args[i].begin();
894 : : }
895 : : LocalFree(wargv);
896 : : }
897 : :
898 : : WinCmdLineArgs::~WinCmdLineArgs()
899 : : {
900 : : delete[] argv;
901 : : }
902 : :
903 : : std::pair<int, char**> WinCmdLineArgs::get()
904 : : {
905 : : return std::make_pair(argc, argv);
906 : : }
907 : : #endif
908 : : } // namespace common
|