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