Branch data Line data Source code
1 : : // Copyright (c) 2023-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_COMMON_ARGS_H
6 : : #define BITCOIN_COMMON_ARGS_H
7 : :
8 : : #include <common/settings.h>
9 : : #include <sync.h>
10 : : #include <util/chaintype.h>
11 : : #include <util/fs.h>
12 : :
13 : : #include <concepts>
14 : : #include <cstdint>
15 : : #include <iosfwd>
16 : : #include <list>
17 : : #include <map>
18 : : #include <optional>
19 : : #include <set>
20 : : #include <string>
21 : : #include <string_view>
22 : : #include <variant>
23 : : #include <vector>
24 : :
25 : : class ArgsManager;
26 : :
27 : : extern const char * const BITCOIN_CONF_FILENAME;
28 : : extern const char * const BITCOIN_SETTINGS_FILENAME;
29 : :
30 : : // Return true if -datadir option points to a valid directory or is not specified.
31 : : bool CheckDataDirOption(const ArgsManager& args);
32 : :
33 : : /**
34 : : * Most paths passed as configuration arguments are treated as relative to
35 : : * the datadir if they are not absolute.
36 : : *
37 : : * @param args Parsed arguments and settings.
38 : : * @param path The path to be conditionally prefixed with datadir.
39 : : * @param net_specific Use network specific datadir variant
40 : : * @return The normalized path.
41 : : */
42 : : fs::path AbsPathForConfigVal(const ArgsManager& args, const fs::path& path, bool net_specific = true);
43 : :
44 : : inline bool IsSwitchChar(char c)
45 : : {
46 : : #ifdef WIN32
47 : : return c == '-' || c == '/';
48 : : #else
49 : : return c == '-';
50 : : #endif
51 : : }
52 : :
53 : : enum class OptionsCategory {
54 : : OPTIONS,
55 : : CONNECTION,
56 : : WALLET,
57 : : WALLET_DEBUG_TEST,
58 : : ZMQ,
59 : : DEBUG_TEST,
60 : : CHAINPARAMS,
61 : : NODE_RELAY,
62 : : BLOCK_CREATION,
63 : : RPC,
64 : : GUI,
65 : : COMMANDS,
66 : : REGISTER_COMMANDS,
67 : : CLI_COMMANDS,
68 : : IPC,
69 : :
70 : : // Specific to one or more commands (OptionsCategory::COMMANDS)
71 : : // These are only included in help with their associated commands.
72 : : COMMAND_OPTIONS,
73 : :
74 : : HIDDEN // Always the last option to avoid printing these in the help
75 : : };
76 : :
77 [ + + ]: 165596 : struct KeyInfo {
78 : : std::string name;
79 : : std::string section;
80 : : bool negated{false};
81 : : };
82 : :
83 : : KeyInfo InterpretKey(std::string key);
84 : :
85 : : std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
86 : : unsigned int flags, std::string& error);
87 : :
88 [ # # ]: 0 : struct SectionInfo {
89 : : std::string m_name;
90 : : std::string m_file;
91 : : int m_line;
92 : : };
93 : :
94 : : std::optional<std::string> SettingToString(const common::SettingsValue&);
95 : :
96 : : template <std::integral Int>
97 : : std::optional<Int> SettingTo(const common::SettingsValue&);
98 : :
99 : : std::optional<bool> SettingToBool(const common::SettingsValue&);
100 : :
101 : : class ArgsManager
102 : : {
103 : : public:
104 : : /**
105 : : * Flags controlling how config and command line arguments are validated and
106 : : * interpreted.
107 : : */
108 : : enum Flags : uint32_t {
109 : : ALLOW_ANY = 0x01, //!< disable validation
110 : : // ALLOW_BOOL = 0x02, //!< unimplemented, draft implementation in #16545
111 : : // ALLOW_INT = 0x04, //!< unimplemented, draft implementation in #16545
112 : : // ALLOW_STRING = 0x08, //!< unimplemented, draft implementation in #16545
113 : : // ALLOW_LIST = 0x10, //!< unimplemented, draft implementation in #16545
114 : : DISALLOW_NEGATION = 0x20, //!< disallow -nofoo syntax
115 : : DISALLOW_ELISION = 0x40, //!< disallow -foo syntax that doesn't assign any value
116 : :
117 : : DEBUG_ONLY = 0x100,
118 : : /* Some options would cause cross-contamination if values for
119 : : * mainnet were used while running on regtest/testnet (or vice-versa).
120 : : * Setting them as NETWORK_ONLY ensures that sharing a config file
121 : : * between mainnet and regtest/testnet won't cause problems due to these
122 : : * parameters by accident. */
123 : : NETWORK_ONLY = 0x200,
124 : : // This argument's value is sensitive (such as a password).
125 : : SENSITIVE = 0x400,
126 : : COMMAND = 0x800,
127 : : };
128 : :
129 : : private:
130 [ - + + + ]: 421223 : struct Arg
131 : : {
132 : : std::string m_help_param;
133 : : std::string m_help_text;
134 : : unsigned int m_flags;
135 : : };
136 : :
137 : : mutable Mutex cs_args;
138 : : common::Settings m_settings GUARDED_BY(cs_args);
139 : : std::vector<std::string> m_command GUARDED_BY(cs_args);
140 : : std::string m_network GUARDED_BY(cs_args);
141 : : std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
142 : : std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args);
143 : : std::optional<unsigned int> m_default_flags GUARDED_BY(cs_args){};
144 : : std::map<std::string, std::set<std::string>> m_command_args GUARDED_BY(cs_args);
145 : : bool m_accept_any_command GUARDED_BY(cs_args){true};
146 : : std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
147 : : std::optional<fs::path> m_config_path GUARDED_BY(cs_args);
148 : : mutable fs::path m_cached_blocks_path GUARDED_BY(cs_args);
149 : : mutable fs::path m_cached_datadir_path GUARDED_BY(cs_args);
150 : : mutable fs::path m_cached_network_datadir_path GUARDED_BY(cs_args);
151 : :
152 : : /**
153 : : * Returns true if settings values from the default section should be used,
154 : : * depending on the current network and whether the setting is
155 : : * network-specific.
156 : : */
157 : : bool UseDefaultSection(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
158 : :
159 : : protected:
160 : : [[nodiscard]] bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
161 : : [[nodiscard]] bool ReadConfigString(const std::string& str_config) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
162 : :
163 : : public:
164 : : /**
165 : : * Get setting value.
166 : : *
167 : : * Result will be null if setting was unset, true if "-setting" argument was passed
168 : : * false if "-nosetting" argument was passed, and a string if a "-setting=value"
169 : : * argument was passed.
170 : : */
171 : : common::SettingsValue GetSetting(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
172 : :
173 : : /**
174 : : * Get list of setting values.
175 : : */
176 : : std::vector<common::SettingsValue> GetSettingsList(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
177 : :
178 : : ArgsManager();
179 : : ~ArgsManager();
180 : :
181 : : /**
182 : : * Select the network in use
183 : : */
184 : : void SelectConfigNetwork(const std::string& network) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
185 : :
186 : : [[nodiscard]] bool ParseParameters(int argc, const char* const argv[], std::string& error) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
187 : :
188 : : /**
189 : : * Return config file path (read-only)
190 : : */
191 : : fs::path GetConfigFilePath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
192 : : void SetConfigFilePath(fs::path) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
193 : : [[nodiscard]] bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
194 : :
195 : : /**
196 : : * Log warnings for options in m_section_only_args when
197 : : * they are specified in the default section but not overridden
198 : : * on the command line or in a network-specific section in the
199 : : * config file.
200 : : */
201 : : std::set<std::string> GetUnsuitableSectionOnlyArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
202 : :
203 : : /**
204 : : * Log warnings for unrecognized section names in the config file.
205 : : */
206 : : std::list<SectionInfo> GetUnrecognizedSections() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
207 : :
208 [ + - ]: 2137 : struct Command {
209 : : /** The command (if one has been registered with AddCommand), or empty */
210 : : std::string command;
211 : : /**
212 : : * If command is non-empty: Any args that followed it
213 : : * If command is empty: The unregistered command and any args that followed it
214 : : */
215 : : std::vector<std::string> args;
216 : : };
217 : : /**
218 : : * Get the command and command args (returns std::nullopt if no command provided)
219 : : */
220 : : std::optional<const Command> GetCommand() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
221 : :
222 : : /**
223 : : * Check that any command-specific options the user specified are valid
224 : : * for the given command.
225 : : *
226 : : * @param[in] command The command being run.
227 : : * @param[out] errors If non-null, populated with a message for each invalid option.
228 : : * @return false if any command-specific options were specified that are not valid for this command
229 : : */
230 : : bool CheckCommandOptions(const std::string& command, std::vector<std::string>* errors = nullptr) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
231 : :
232 : : /**
233 : : * Get blocks directory path
234 : : *
235 : : * @return Blocks path which is network specific
236 : : */
237 : : fs::path GetBlocksDirPath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
238 : :
239 : : /**
240 : : * Get data directory path
241 : : *
242 : : * @return Absolute path on success, otherwise an empty path when a non-directory path would be returned
243 : : */
244 : : fs::path GetDataDirBase() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
245 : :
246 : : /**
247 : : * Get data directory path with appended network identifier
248 : : *
249 : : * @return Absolute path on success, otherwise an empty path when a non-directory path would be returned
250 : : */
251 : : fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
252 : :
253 : : /**
254 : : * Clear cached directory paths
255 : : */
256 : : void ClearPathCache() EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
257 : :
258 : : /**
259 : : * Return a vector of strings of the given argument
260 : : *
261 : : * @param strArg Argument to get (e.g. "-foo")
262 : : * @return command-line arguments
263 : : */
264 : : std::vector<std::string> GetArgs(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
265 : :
266 : : /**
267 : : * Return true if the given argument has been manually set
268 : : *
269 : : * @param strArg Argument to get (e.g. "-foo")
270 : : * @return true if the argument has been set
271 : : */
272 : : bool IsArgSet(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
273 : :
274 : : /**
275 : : * Return true if the argument was originally passed as a negated option,
276 : : * i.e. -nofoo.
277 : : *
278 : : * @param strArg Argument to get (e.g. "-foo")
279 : : * @return true if the argument was passed negated
280 : : */
281 : : bool IsArgNegated(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
282 : :
283 : : /**
284 : : * Return string argument or default value
285 : : *
286 : : * @param strArg Argument to get (e.g. "-foo")
287 : : * @param strDefault (e.g. "1")
288 : : * @return command-line argument or default value
289 : : */
290 : : std::string GetArg(const std::string& strArg, const std::string& strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
291 : : std::optional<std::string> GetArg(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
292 : :
293 : : /**
294 : : * Return path argument or default value
295 : : *
296 : : * @param arg Argument to get a path from (e.g., "-datadir", "-blocksdir" or "-walletdir")
297 : : * @param default_value Optional default value to return instead of the empty path.
298 : : * @return normalized path if argument is set, with redundant "." and ".."
299 : : * path components and trailing separators removed (see patharg unit test
300 : : * for examples or implementation for details). If argument is empty or not
301 : : * set, default_value is returned unchanged.
302 : : */
303 : : fs::path GetPathArg(std::string arg, const fs::path& default_value = {}) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
304 : :
305 : : /**
306 : : * Return integer argument or default value
307 : : *
308 : : * @param strArg Argument to get (e.g. "-foo")
309 : : * @param nDefault (e.g. 1)
310 : : * @return command-line argument (0 if invalid number) or default value
311 : : */
312 : : template <std::integral Int>
313 : : Int GetArg(const std::string& strArg, Int nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
314 : :
315 : : template <std::integral Int>
316 : : std::optional<Int> GetArg(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
317 : :
318 [ + - ]: 769260 : int64_t GetIntArg(const std::string& strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args) { return GetArg<int64_t>(strArg, nDefault); }
[ # # # # ]
[ + - + -
+ - ][ + -
+ - + - +
- + - ]
[ - - - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - - - ]
319 [ + - ]: 89612 : std::optional<int64_t> GetIntArg(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args) { return GetArg<int64_t>(strArg); }
[ + - + - ]
[ + - + -
+ - ]
320 : :
321 : : /**
322 : : * Return boolean argument or default value
323 : : *
324 : : * @param strArg Argument to get (e.g. "-foo")
325 : : * @param fDefault (true or false)
326 : : * @return command-line argument or default value
327 : : */
328 : : bool GetBoolArg(const std::string& strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
329 : : std::optional<bool> GetBoolArg(const std::string& strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
330 : :
331 : : /**
332 : : * Set an argument if it doesn't already have a value
333 : : *
334 : : * @param strArg Argument to set (e.g. "-foo")
335 : : * @param strValue Value (e.g. "1")
336 : : * @return true if argument gets set, false if it already had a value
337 : : */
338 : : bool SoftSetArg(const std::string& strArg, const std::string& strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
339 : :
340 : : /**
341 : : * Set a boolean argument if it doesn't already have a value
342 : : *
343 : : * @param strArg Argument to set (e.g. "-foo")
344 : : * @param fValue Value (e.g. false)
345 : : * @return true if argument gets set, false if it already had a value
346 : : */
347 : : bool SoftSetBoolArg(const std::string& strArg, bool fValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
348 : :
349 : : // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
350 : : // been set. Also called directly in testing.
351 : : void ForceSetArg(const std::string& strArg, const std::string& strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
352 : :
353 : : /**
354 : : * Returns the appropriate chain type from the program arguments.
355 : : * @return ChainType::MAIN by default; raises runtime error if an invalid
356 : : * combination, or unknown chain is given.
357 : : */
358 : : ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
359 : :
360 : : /**
361 : : * Returns the appropriate chain type string from the program arguments.
362 : : * @return ChainType::MAIN string by default; raises runtime error if an
363 : : * invalid combination is given.
364 : : */
365 : : std::string GetChainTypeString() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
366 : :
367 : : /**
368 : : * Add argument
369 : : */
370 : : void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
371 : :
372 : : /**
373 : : * Add command
374 : : */
375 : : void AddCommand(const std::string& cmd, const std::string& help, std::set<std::string> options = {}) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
376 : :
377 : : /**
378 : : * Add many hidden arguments
379 : : */
380 : : void AddHiddenArgs(const std::vector<std::string>& args) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
381 : :
382 : : /**
383 : : * Clear available arguments
384 : : */
385 : : void ClearArgs() EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
386 : :
387 : : /**
388 : : * Check CLI command args
389 : : *
390 : : * @throws std::runtime_error when multiple CLI_COMMAND arguments are specified
391 : : */
392 : : void CheckMultipleCLIArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
393 : :
394 : : /**
395 : : * Get the help string
396 : : */
397 : : std::string GetHelpMessage() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
398 : :
399 : : /**
400 : : * Return Flags for known arg.
401 : : * Return default flags for unknown arg.
402 : : */
403 : : std::optional<unsigned int> GetArgFlags(const std::string& name) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
404 : :
405 : : /**
406 : : * Set default flags to return for an unknown arg.
407 : : */
408 : : void SetDefaultFlags(std::optional<unsigned int>) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
409 : :
410 : : /**
411 : : * Get settings file path, or return false if read-write settings were
412 : : * disabled with -nosettings.
413 : : */
414 : : bool GetSettingsPath(fs::path* filepath = nullptr, bool temp = false, bool backup = false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
415 : :
416 : : /**
417 : : * Read settings file. Push errors to vector, or log them if null.
418 : : */
419 : : bool ReadSettingsFile(std::vector<std::string>* errors = nullptr) EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
420 : :
421 : : /**
422 : : * Write settings file or backup settings file. Push errors to vector, or
423 : : * log them if null.
424 : : */
425 : : bool WriteSettingsFile(std::vector<std::string>* errors = nullptr, bool backup = false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
426 : :
427 : : /**
428 : : * Get current setting from config file or read/write settings file,
429 : : * ignoring nonpersistent command line or forced settings values.
430 : : */
431 : : common::SettingsValue GetPersistentSetting(const std::string& name) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
432 : :
433 : : /**
434 : : * Access settings with lock held.
435 : : */
436 : : template <typename Fn>
437 : 0 : void LockSettings(Fn&& fn) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
438 : : {
439 : 0 : LOCK(cs_args);
440 [ # # ][ # # ]: 0 : fn(m_settings);
441 : 0 : }
442 : :
443 : : /**
444 : : * Log the config file options and the command line arguments,
445 : : * useful for troubleshooting.
446 : : */
447 : : void LogArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
448 : :
449 : : private:
450 : : // Internal helpers, for use by callers that already hold `cs_args`.
451 : : common::SettingsValue GetSetting_(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
452 : : std::optional<unsigned int> GetArgFlags_(const std::string& name) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
453 : : fs::path GetPathArg_(std::string arg, const fs::path& default_value = {}) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
454 : :
455 : : /**
456 : : * Get data directory path
457 : : *
458 : : * @param net_specific Append network identifier to the returned path
459 : : * @return Absolute path on success, otherwise an empty path when a non-directory path would be returned
460 : : */
461 : : fs::path GetDataDir(bool net_specific) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
462 : :
463 : : /**
464 : : * Return -regtest/-signet/-testnet/-testnet4/-chain= setting as a ChainType enum if a
465 : : * recognized chain type was set, or as a string if an unrecognized chain
466 : : * name was set. Raise an exception if an invalid combination of flags was
467 : : * provided.
468 : : */
469 : : std::variant<ChainType, std::string> GetChainArg() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args);
470 : :
471 : : // Helper function for LogArgs().
472 : : void logArgsPrefix(
473 : : const std::string& prefix,
474 : : const std::string& section,
475 : : const std::map<std::string, std::vector<common::SettingsValue>>& args) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
476 : : };
477 : :
478 : : extern ArgsManager gArgs;
479 : :
480 : : /**
481 : : * @return true if help has been requested via a command-line arg
482 : : */
483 : : bool HelpRequested(const ArgsManager& args);
484 : :
485 : : /** Add help options to the args manager */
486 : : void SetupHelpOptions(ArgsManager& args);
487 : :
488 : : extern const std::vector<std::string> TEST_OPTIONS_DOC;
489 : :
490 : : /** Checks if a particular test option is present in -test command-line arg options */
491 : : bool HasTestOption(const ArgsManager& args, const std::string& test_option);
492 : :
493 : : /**
494 : : * Format a string to be used as group of options in help messages
495 : : *
496 : : * @param message Group name (e.g. "RPC server options:")
497 : : * @return the formatted string
498 : : */
499 : : std::string HelpMessageGroup(const std::string& message);
500 : :
501 : : /**
502 : : * Format a string to be used as option description in help messages
503 : : *
504 : : * @param option Option name (e.g. "-rpcuser")
505 : : * @param help_param Help parameter (e.g. "=<user>" or "")
506 : : * @param message Option description (e.g. "Username for JSON-RPC connections")
507 : : * @param subopt True if this is a suboption, instead of a top-level option.
508 : : * @return the formatted string
509 : : */
510 : : std::string HelpMessageOpt(std::string_view option, std::string_view help_param, std::string_view message, bool subopt = false);
511 : :
512 : : #endif // BITCOIN_COMMON_ARGS_H
|