Bitcoin Core 31.99.0
P2P Digital Currency
settings.cpp
Go to the documentation of this file.
1// Copyright (c) 2019-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#include <bitcoin-build-config.h> // IWYU pragma: keep
6
7#include <common/settings.h>
8
9#include <tinyformat.h>
10#include <univalue.h>
11#include <util/fs.h>
12
13#include <fstream>
14#include <iterator>
15#include <map>
16#include <string>
17#include <utility>
18#include <vector>
19
20namespace common {
21namespace {
22
23enum class Source {
24 FORCED,
25 COMMAND_LINE,
26 RW_SETTINGS,
27 CONFIG_FILE_NETWORK_SECTION,
28 CONFIG_FILE_DEFAULT_SECTION
29};
30
31// Json object key for the auto-generated warning comment
32const std::string SETTINGS_WARN_MSG_KEY{"_warning_"};
33
39template <typename Fn>
40static void MergeSettings(const Settings& settings, const std::string& section, const std::string& name, Fn&& fn)
41{
42 // Merge in the forced settings
43 if (auto* value = FindKey(settings.forced_settings, name)) {
44 fn(SettingsSpan(*value), Source::FORCED);
45 }
46 // Merge in the command-line options
47 if (auto* values = FindKey(settings.command_line_options, name)) {
48 fn(SettingsSpan(*values), Source::COMMAND_LINE);
49 }
50 // Merge in the read-write settings
51 if (const SettingsValue* value = FindKey(settings.rw_settings, name)) {
52 fn(SettingsSpan(*value), Source::RW_SETTINGS);
53 }
54 // Merge in the network-specific section of the config file
55 if (!section.empty()) {
56 if (auto* map = FindKey(settings.ro_config, section)) {
57 if (auto* values = FindKey(*map, name)) {
58 fn(SettingsSpan(*values), Source::CONFIG_FILE_NETWORK_SECTION);
59 }
60 }
61 }
62 // Merge in the default section of the config file
63 if (auto* map = FindKey(settings.ro_config, "")) {
64 if (auto* values = FindKey(*map, name)) {
65 fn(SettingsSpan(*values), Source::CONFIG_FILE_DEFAULT_SECTION);
66 }
67 }
68}
69} // namespace
70
71bool ReadSettings(const fs::path& path, std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors)
72{
73 values.clear();
74 errors.clear();
75
76 // Ok for file to not exist
77 if (!fs::exists(path)) return true;
78
79 std::ifstream file;
80 file.open(path.std_path());
81 if (!file.is_open()) {
82 errors.emplace_back(strprintf("%s. Please check permissions.", fs::PathToString(path)));
83 return false;
84 }
85
87 if (!in.read(std::string{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()})) {
88 errors.emplace_back(strprintf("Settings file %s does not contain valid JSON. This may be caused by a crash, power loss, full disk, or storage error, "
89 "and can be fixed by removing the file, which will reset settings to default values.",
90 fs::PathToString(path)));
91 return false;
92 }
93
94 if (file.fail()) {
95 errors.emplace_back(strprintf("Failed reading settings file %s", fs::PathToString(path)));
96 return false;
97 }
98 file.close(); // Done with file descriptor. Release while copying data.
99
100 if (!in.isObject()) {
101 errors.emplace_back(strprintf("Found non-object value %s in settings file %s", in.write(), fs::PathToString(path)));
102 return false;
103 }
104
105 const std::vector<std::string>& in_keys = in.getKeys();
106 const std::vector<SettingsValue>& in_values = in.getValues();
107 for (size_t i = 0; i < in_keys.size(); ++i) {
108 auto inserted = values.emplace(in_keys[i], in_values[i]);
109 if (!inserted.second) {
110 errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path)));
111 values.clear();
112 break;
113 }
114 }
115
116 // Remove auto-generated warning comment from the accessible settings.
117 values.erase(SETTINGS_WARN_MSG_KEY);
118
119 return errors.empty();
120}
121
122bool WriteSettings(const fs::path& path,
123 const std::map<std::string, SettingsValue>& values,
124 std::vector<std::string>& errors)
125{
127 // Add auto-generated warning comment
128 out.pushKV(SETTINGS_WARN_MSG_KEY, strprintf("This file is automatically generated and updated by %s. Please do not edit this file while the node "
129 "is running, as any changes might be ignored or overwritten.", CLIENT_NAME));
130 // Push settings values
131 for (const auto& value : values) {
132 out.pushKVEnd(value.first, value.second);
133 }
134 std::ofstream file;
135 file.open(path.std_path());
136 if (file.fail()) {
137 errors.emplace_back(strprintf("Error: Unable to open settings file %s for writing", fs::PathToString(path)));
138 return false;
139 }
140 file << out.write(/* prettyIndent= */ 4, /* indentLevel= */ 1) << std::endl;
141 if (file.fail()) {
142 errors.emplace_back(strprintf("Error: Unable to write settings file %s", fs::PathToString(path)));
143 return false;
144 }
145 file.close();
146 if (file.fail()) {
147 errors.emplace_back(strprintf("Error: Unable to close settings file %s", fs::PathToString(path)));
148 return false;
149 }
150 return true;
151}
152
154 const std::string& section,
155 const std::string& name,
156 bool ignore_default_section_config,
157 bool ignore_nonpersistent,
158 bool get_chain_type)
159{
160 SettingsValue result;
161 bool done = false; // Done merging any more settings sources.
162 MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
163 // Weird behavior preserved for backwards compatibility: Apply negated
164 // setting even if non-negated setting would be ignored. A negated
165 // value in the default section is applied to network specific options,
166 // even though normal non-negated values there would be ignored.
167 const bool never_ignore_negated_setting = span.last_negated();
168
169 // Weird behavior preserved for backwards compatibility: Take first
170 // assigned value instead of last. In general, later settings take
171 // precedence over early settings, but for backwards compatibility in
172 // the config file the precedence is reversed for all settings except
173 // chain type settings.
174 const bool reverse_precedence =
175 (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
176 !get_chain_type;
177
178 // Weird behavior preserved for backwards compatibility: Negated
179 // -regtest and -testnet arguments which you would expect to override
180 // values set in the configuration file are currently accepted but
181 // silently ignored. It would be better to apply these just like other
182 // negated values, or at least warn they are ignored.
183 const bool skip_negated_command_line = get_chain_type;
184
185 if (done) return;
186
187 // Ignore settings in default config section if requested.
188 if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION &&
189 !never_ignore_negated_setting) {
190 return;
191 }
192
193 // Ignore nonpersistent settings if requested.
194 if (ignore_nonpersistent && (source == Source::COMMAND_LINE || source == Source::FORCED)) return;
195
196 // Skip negated command line settings.
197 if (skip_negated_command_line && span.last_negated()) return;
198
199 if (!span.empty()) {
200 result = reverse_precedence ? span.begin()[0] : span.end()[-1];
201 done = true;
202 } else if (span.last_negated()) {
203 result = false;
204 done = true;
205 }
206 });
207 return result;
208}
209
210std::vector<SettingsValue> GetSettingsList(const Settings& settings,
211 const std::string& section,
212 const std::string& name,
213 bool ignore_default_section_config)
214{
215 std::vector<SettingsValue> result;
216 bool done = false; // Done merging any more settings sources.
217 bool prev_negated_empty = false;
218 MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
219 // Weird behavior preserved for backwards compatibility: Apply config
220 // file settings even if negated on command line. Negating a setting on
221 // command line will ignore earlier settings on the command line and
222 // ignore settings in the config file, unless the negated command line
223 // value is followed by non-negated value, in which case config file
224 // settings will be brought back from the dead (but earlier command
225 // line settings will still be ignored).
226 const bool add_zombie_config_values =
227 (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
228 !prev_negated_empty;
229
230 // Ignore settings in default config section if requested.
231 if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION) return;
232
233 // Add new settings to the result if isn't already complete, or if the
234 // values are zombies.
235 if (!done || add_zombie_config_values) {
236 for (const auto& value : span) {
237 if (value.isArray()) {
238 result.insert(result.end(), value.getValues().begin(), value.getValues().end());
239 } else {
240 result.push_back(value);
241 }
242 }
243 }
244
245 // If a setting was negated, or if a setting was forced, set
246 // done to true to ignore any later lower priority settings.
247 done |= span.negated() > 0 || source == Source::FORCED;
248
249 // Update the negated and empty state used for the zombie values check.
250 prev_negated_empty |= span.last_negated() && result.empty();
251 });
252 return result;
253}
254
255bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name)
256{
257 bool has_default_section_setting = false;
258 bool has_other_setting = false;
259 MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
260 if (span.empty()) return;
261 else if (source == Source::CONFIG_FILE_DEFAULT_SECTION) has_default_section_setting = true;
262 else has_other_setting = true;
263 });
264 // If a value is set in the default section and not explicitly overwritten by the
265 // user on the command line or in a different section, then we want to enable
266 // warnings about the value being ignored.
267 return has_default_section_setting && !has_other_setting;
268}
269
270SettingsSpan::SettingsSpan(const std::vector<SettingsValue>& vec) noexcept : SettingsSpan(vec.data(), vec.size()) {}
271const SettingsValue* SettingsSpan::begin() const { return data + negated(); }
272const SettingsValue* SettingsSpan::end() const { return data + size; }
273bool SettingsSpan::empty() const { return size == 0 || last_negated(); }
274bool SettingsSpan::last_negated() const { return size > 0 && data[size - 1].isFalse(); }
276{
277 for (size_t i = size; i > 0; --i) {
278 if (data[i - 1].isFalse()) return i; // Return number of negated values (position of last false value)
279 }
280 return 0;
281}
282
283} // namespace common
if(!SetupNetworking())
@ VOBJ
Definition: univalue.h:24
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
bool read(std::string_view raw)
bool isFalse() const
Definition: univalue.h:83
bool isObject() const
Definition: univalue.h:88
static bool exists(const path &p)
Definition: fs.h:96
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:162
Definition: init.cpp:17
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:122
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:71
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool ignore_nonpersistent, bool get_chain_type)
Get settings value from combined sources: forced settings, command line arguments,...
Definition: settings.cpp:153
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:109
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times,...
Definition: settings.cpp:210
bool OnlyHasDefaultSectionSetting(const Settings &settings, const std::string &section, const std::string &name)
Return true if a setting is set in the default config file section, and not overridden by a higher pr...
Definition: settings.cpp:255
UniValue SettingsValue
Settings value type (string/integer/boolean/null variant).
Definition: settings.h:30
const char * name
Definition: rest.cpp:56
const char * source
Definition: rpcconsole.cpp:63
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Stored settings.
Definition: settings.h:34
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:92
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:274
const SettingsValue * begin() const
Pointer to first non-negated value.
Definition: settings.cpp:271
const SettingsValue * end() const
Pointer to end of values.
Definition: settings.cpp:272
bool empty() const
True if there are any non-negated values.
Definition: settings.cpp:273
size_t negated() const
Number of negated values.
Definition: settings.cpp:275
const SettingsValue * data
Definition: settings.h:103
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172