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