Skip to content

Commit 66b08e7

Browse files
committed
Merge bitcoin/bitcoin#27302: init: Error if ignored bitcoin.conf file is found
eefe569 bugfix: Fix incorrect debug.log config file path (Ryan Ofsky) 3746f00 init: Error if ignored bitcoin.conf file is found (Ryan Ofsky) 398c371 lint: Fix lint-format-strings false positives when format specifiers have argument positions (Ryan Ofsky) Pull request description: Show an error on startup if a bitcoin datadir that is being used contains a `bitcoin.conf` file that is ignored. There are two cases where this could happen: - One case reported in [#27246 (comment)](bitcoin/bitcoin#27246 (comment)) happens when a `bitcoin.conf` file in the default datadir (e.g. `$HOME/.bitcoin/bitcoin.conf`) has a `datadir=/path` line that sets different datadir containing a second `bitcoin.conf` file. Currently the second `bitcoin.conf` file is ignored with no warning. - Another way this could happen is if a `-conf=` command line argument points to a configuration file with a `datadir=/path` line and that path contains a `bitcoin.conf` file, which is currently ignored. This change only adds an error message and doesn't change anything about way settings are applied. It also doesn't trigger errors if there are redundant `-datadir` or `-conf` settings pointing at the same configuration file, only if they are pointing at different files and one file is being ignored. ACKs for top commit: pinheadmz: re-ACK eefe569 willcl-ark: re-ACK eefe569 TheCharlatan: ACK eefe569 Tree-SHA512: 939a98a4b271b5263d64a2df3054c56fcde94784edf6f010d78693a371c38aa03138ae9cebb026b6164bbd898d8fd0845a61a454fd996e328fd7bcf51c580c2b
2 parents 4d13fe4 + eefe569 commit 66b08e7

File tree

11 files changed

+189
-20
lines changed

11 files changed

+189
-20
lines changed

doc/release-notes-27302.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Configuration
2+
---
3+
4+
- `bitcoind` and `bitcoin-qt` will now raise an error on startup if a datadir that is being used contains a bitcoin.conf file that will be ignored, which can happen when a datadir= line is used in a bitcoin.conf file. The error message is just a diagnostic intended to prevent accidental misconfiguration, and it can be disabled to restore the previous behavior of using the datadir while ignoring the bitcoin.conf contained in it.

src/common/args.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,7 +716,8 @@ bool CheckDataDirOption(const ArgsManager& args)
716716

717717
fs::path ArgsManager::GetConfigFilePath() const
718718
{
719-
return GetConfigFile(*this, GetPathArg("-conf", BITCOIN_CONF_FILENAME));
719+
LOCK(cs_args);
720+
return *Assert(m_config_path);
720721
}
721722

722723
ChainType ArgsManager::GetChainType() const

src/common/args.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ extern const char * const BITCOIN_SETTINGS_FILENAME;
2828

2929
// Return true if -datadir option points to a valid directory or is not specified.
3030
bool CheckDataDirOption(const ArgsManager& args);
31-
fs::path GetConfigFile(const ArgsManager& args, const fs::path& configuration_file_path);
3231

3332
/**
3433
* Most paths passed as configuration arguments are treated as relative to
@@ -138,6 +137,7 @@ class ArgsManager
138137
std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args);
139138
bool m_accept_any_command GUARDED_BY(cs_args){true};
140139
std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
140+
std::optional<fs::path> m_config_path GUARDED_BY(cs_args);
141141
mutable fs::path m_cached_blocks_path GUARDED_BY(cs_args);
142142
mutable fs::path m_cached_datadir_path GUARDED_BY(cs_args);
143143
mutable fs::path m_cached_network_datadir_path GUARDED_BY(cs_args);

src/common/config.cpp

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,6 @@
2727
#include <utility>
2828
#include <vector>
2929

30-
fs::path GetConfigFile(const ArgsManager& args, const fs::path& configuration_file_path)
31-
{
32-
return AbsPathForConfigVal(args, configuration_file_path, /*net_specific=*/false);
33-
}
34-
3530
static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
3631
{
3732
std::string str, prefix;
@@ -126,6 +121,7 @@ bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
126121
LOCK(cs_args);
127122
m_settings.ro_config.clear();
128123
m_config_sections.clear();
124+
m_config_path = AbsPathForConfigVal(*this, GetPathArg("-conf", BITCOIN_CONF_FILENAME), /*net_specific=*/false);
129125
}
130126

131127
const auto conf_path{GetConfigFilePath()};
@@ -176,7 +172,7 @@ bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
176172
const size_t default_includes = add_includes({});
177173

178174
for (const std::string& conf_file_name : conf_file_names) {
179-
std::ifstream conf_file_stream{GetConfigFile(*this, fs::PathFromString(conf_file_name))};
175+
std::ifstream conf_file_stream{AbsPathForConfigVal(*this, fs::PathFromString(conf_file_name), /*net_specific=*/false)};
180176
if (conf_file_stream.good()) {
181177
if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
182178
return false;

src/common/init.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <chainparams.h>
66
#include <common/args.h>
77
#include <common/init.h>
8+
#include <logging.h>
89
#include <tinyformat.h>
910
#include <util/fs.h>
1011
#include <util/translation.h>
@@ -20,6 +21,19 @@ std::optional<ConfigError> InitConfig(ArgsManager& args, SettingsAbortFn setting
2021
if (!CheckDataDirOption(args)) {
2122
return ConfigError{ConfigStatus::FAILED, strprintf(_("Specified data directory \"%s\" does not exist."), args.GetArg("-datadir", ""))};
2223
}
24+
25+
// Record original datadir and config paths before parsing the config
26+
// file. It is possible for the config file to contain a datadir= line
27+
// that changes the datadir path after it is parsed. This is useful for
28+
// CLI tools to let them use a different data storage location without
29+
// needing to pass it every time on the command line. (It is not
30+
// possible for the config file to cause another configuration to be
31+
// used, though. Specifying a conf= option in the config file causes a
32+
// parse error, and specifying a datadir= location containing another
33+
// bitcoin.conf file just ignores the other file.)
34+
const fs::path orig_datadir_path{args.GetDataDirBase()};
35+
const fs::path orig_config_path{AbsPathForConfigVal(args, args.GetPathArg("-conf", BITCOIN_CONF_FILENAME), /*net_specific=*/false)};
36+
2337
std::string error;
2438
if (!args.ReadConfigFiles(error, true)) {
2539
return ConfigError{ConfigStatus::FAILED, strprintf(_("Error reading configuration file: %s"), error)};
@@ -48,6 +62,32 @@ std::optional<ConfigError> InitConfig(ArgsManager& args, SettingsAbortFn setting
4862
fs::create_directories(net_path / "wallets");
4963
}
5064

65+
// Show an error or warning if there is a bitcoin.conf file in the
66+
// datadir that is being ignored.
67+
const fs::path base_config_path = base_path / BITCOIN_CONF_FILENAME;
68+
if (fs::exists(base_config_path) && !fs::equivalent(orig_config_path, base_config_path)) {
69+
const std::string cli_config_path = args.GetArg("-conf", "");
70+
const std::string config_source = cli_config_path.empty()
71+
? strprintf("data directory %s", fs::quoted(fs::PathToString(orig_datadir_path)))
72+
: strprintf("command line argument %s", fs::quoted("-conf=" + cli_config_path));
73+
const std::string error = strprintf(
74+
"Data directory %1$s contains a %2$s file which is ignored, because a different configuration file "
75+
"%3$s from %4$s is being used instead. Possible ways to address this would be to:\n"
76+
"- Delete or rename the %2$s file in data directory %1$s.\n"
77+
"- Change datadir= or conf= options to specify one configuration file, not two, and use "
78+
"includeconf= to include any other configuration files.\n"
79+
"- Set allowignoredconf=1 option to treat this condition as a warning, not an error.",
80+
fs::quoted(fs::PathToString(base_path)),
81+
fs::quoted(BITCOIN_CONF_FILENAME),
82+
fs::quoted(fs::PathToString(orig_config_path)),
83+
config_source);
84+
if (args.GetBoolArg("-allowignoredconf", false)) {
85+
LogPrintf("Warning: %s\n", error);
86+
} else {
87+
return ConfigError{ConfigStatus::FAILED, Untranslated(error)};
88+
}
89+
}
90+
5191
// Create settings.json if -nosettings was not specified.
5292
if (args.GetSettingsPath()) {
5393
std::vector<std::string> details;

src/init.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ void SetupServerArgs(ArgsManager& argsman)
444444
argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
445445
argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
446446
argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
447+
argsman.AddArg("-allowignoredconf", strprintf("For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
447448
argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
448449
argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
449450
argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);

src/qt/test/test_main.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ int main(int argc, char* argv[])
7171
gArgs.ForceSetArg("-upnp", "0");
7272
gArgs.ForceSetArg("-natpmp", "0");
7373

74+
std::string error;
75+
if (!gArgs.ReadConfigFiles(error, true)) QWARN(error.c_str());
76+
7477
// Prefer the "minimal" platform for the test instead of the normal default
7578
// platform ("xcb", "windows", or "cocoa") so tests can't unintentionally
7679
// interfere with any background GUIs and don't require extra resources.

test/functional/feature_config_args.py

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@
55
"""Test various command line arguments and configuration file parameters."""
66

77
import os
8+
import pathlib
9+
import re
10+
import sys
11+
import tempfile
812
import time
913

1014
from test_framework.test_framework import BitcoinTestFramework
15+
from test_framework.test_node import ErrorMatch
1116
from test_framework import util
1217

1318

@@ -74,7 +79,7 @@ def test_config_file_parser(self):
7479
util.write_config(main_conf_file_path, n=0, chain='', extra_config=f'includeconf={inc_conf_file_path}\n')
7580
with open(inc_conf_file_path, 'w', encoding='utf-8') as conf:
7681
conf.write('acceptnonstdtxn=1\n')
77-
self.nodes[0].assert_start_raises_init_error(extra_args=[f"-conf={main_conf_file_path}"], expected_msg='Error: acceptnonstdtxn is not currently supported for main chain')
82+
self.nodes[0].assert_start_raises_init_error(extra_args=[f"-conf={main_conf_file_path}", "-allowignoredconf"], expected_msg='Error: acceptnonstdtxn is not currently supported for main chain')
7883

7984
with open(inc_conf_file_path, 'w', encoding='utf-8') as conf:
8085
conf.write('nono\n')
@@ -108,6 +113,41 @@ def test_config_file_parser(self):
108113
with open(inc_conf_file2_path, 'w', encoding='utf-8') as conf:
109114
conf.write('') # clear
110115

116+
def test_config_file_log(self):
117+
# Disable this test for windows currently because trying to override
118+
# the default datadir through the environment does not seem to work.
119+
if sys.platform == "win32":
120+
return
121+
122+
self.log.info('Test that correct configuration path is changed when configuration file changes the datadir')
123+
124+
# Create a temporary directory that will be treated as the default data
125+
# directory by bitcoind.
126+
env, default_datadir = util.get_temp_default_datadir(pathlib.Path(self.options.tmpdir, "test_config_file_log"))
127+
default_datadir.mkdir(parents=True)
128+
129+
# Write a bitcoin.conf file in the default data directory containing a
130+
# datadir= line pointing at the node datadir.
131+
node = self.nodes[0]
132+
conf_text = pathlib.Path(node.bitcoinconf).read_text()
133+
conf_path = default_datadir / "bitcoin.conf"
134+
conf_path.write_text(f"datadir={node.datadir}\n{conf_text}")
135+
136+
# Drop the node -datadir= argument during this test, because if it is
137+
# specified it would take precedence over the datadir setting in the
138+
# config file.
139+
node_args = node.args
140+
node.args = [arg for arg in node.args if not arg.startswith("-datadir=")]
141+
142+
# Check that correct configuration file path is actually logged
143+
# (conf_path, not node.bitcoinconf)
144+
with self.nodes[0].assert_debug_log(expected_msgs=[f"Config file: {conf_path}"]):
145+
self.start_node(0, ["-allowignoredconf"], env=env)
146+
self.stop_node(0)
147+
148+
# Restore node arguments after the test
149+
node.args = node_args
150+
111151
def test_invalid_command_line_options(self):
112152
self.nodes[0].assert_start_raises_init_error(
113153
expected_msg='Error: Error parsing command line arguments: Can not set -proxy with no value. Please specify value with -proxy=value.',
@@ -282,6 +322,55 @@ def test_connect_with_seednode(self):
282322
unexpected_msgs=seednode_ignored):
283323
self.restart_node(0, extra_args=[connect_arg, '-seednode=fakeaddress2'])
284324

325+
def test_ignored_conf(self):
326+
self.log.info('Test error is triggered when the datadir in use contains a bitcoin.conf file that would be ignored '
327+
'because a conflicting -conf file argument is passed.')
328+
node = self.nodes[0]
329+
with tempfile.NamedTemporaryFile(dir=self.options.tmpdir, mode="wt", delete=False) as temp_conf:
330+
temp_conf.write(f"datadir={node.datadir}\n")
331+
node.assert_start_raises_init_error([f"-conf={temp_conf.name}"], re.escape(
332+
f'Error: Data directory "{node.datadir}" contains a "bitcoin.conf" file which is ignored, because a '
333+
f'different configuration file "{temp_conf.name}" from command line argument "-conf={temp_conf.name}" '
334+
f'is being used instead.') + r"[\s\S]*", match=ErrorMatch.FULL_REGEX)
335+
336+
# Test that passing a redundant -conf command line argument pointing to
337+
# the same bitcoin.conf that would be loaded anyway does not trigger an
338+
# error.
339+
self.start_node(0, [f'-conf={node.datadir}/bitcoin.conf'])
340+
self.stop_node(0)
341+
342+
def test_ignored_default_conf(self):
343+
# Disable this test for windows currently because trying to override
344+
# the default datadir through the environment does not seem to work.
345+
if sys.platform == "win32":
346+
return
347+
348+
self.log.info('Test error is triggered when bitcoin.conf in the default data directory sets another datadir '
349+
'and it contains a different bitcoin.conf file that would be ignored')
350+
351+
# Create a temporary directory that will be treated as the default data
352+
# directory by bitcoind.
353+
env, default_datadir = util.get_temp_default_datadir(pathlib.Path(self.options.tmpdir, "home"))
354+
default_datadir.mkdir(parents=True)
355+
356+
# Write a bitcoin.conf file in the default data directory containing a
357+
# datadir= line pointing at the node datadir. This will trigger a
358+
# startup error because the node datadir contains a different
359+
# bitcoin.conf that would be ignored.
360+
node = self.nodes[0]
361+
(default_datadir / "bitcoin.conf").write_text(f"datadir={node.datadir}\n")
362+
363+
# Drop the node -datadir= argument during this test, because if it is
364+
# specified it would take precedence over the datadir setting in the
365+
# config file.
366+
node_args = node.args
367+
node.args = [arg for arg in node.args if not arg.startswith("-datadir=")]
368+
node.assert_start_raises_init_error([], re.escape(
369+
f'Error: Data directory "{node.datadir}" contains a "bitcoin.conf" file which is ignored, because a '
370+
f'different configuration file "{default_datadir}/bitcoin.conf" from data directory "{default_datadir}" '
371+
f'is being used instead.') + r"[\s\S]*", env=env, match=ErrorMatch.FULL_REGEX)
372+
node.args = node_args
373+
285374
def run_test(self):
286375
self.test_log_buffer()
287376
self.test_args_log()
@@ -290,7 +379,10 @@ def run_test(self):
290379
self.test_connect_with_seednode()
291380

292381
self.test_config_file_parser()
382+
self.test_config_file_log()
293383
self.test_invalid_command_line_options()
384+
self.test_ignored_conf()
385+
self.test_ignored_default_conf()
294386

295387
# Remove the -datadir argument so it doesn't override the config file
296388
self.nodes[0].args = [arg for arg in self.nodes[0].args if not arg.startswith("-datadir")]

test/functional/test_framework/test_node.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def __getattr__(self, name):
190190
assert self.rpc_connected and self.rpc is not None, self._node_msg("Error: no RPC connection")
191191
return getattr(RPCOverloadWrapper(self.rpc, descriptors=self.descriptors), name)
192192

193-
def start(self, extra_args=None, *, cwd=None, stdout=None, stderr=None, **kwargs):
193+
def start(self, extra_args=None, *, cwd=None, stdout=None, stderr=None, env=None, **kwargs):
194194
"""Start the node."""
195195
if extra_args is None:
196196
extra_args = self.extra_args
@@ -213,6 +213,8 @@ def start(self, extra_args=None, *, cwd=None, stdout=None, stderr=None, **kwargs
213213

214214
# add environment variable LIBC_FATAL_STDERR_=1 so that libc errors are written to stderr and not the terminal
215215
subp_env = dict(os.environ, LIBC_FATAL_STDERR_="1")
216+
if env is not None:
217+
subp_env.update(env)
216218

217219
self.process = subprocess.Popen(self.args + extra_args, env=subp_env, stdout=stdout, stderr=stderr, cwd=cwd, **kwargs)
218220

test/functional/test_framework/util.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
import json
1313
import logging
1414
import os
15+
import pathlib
1516
import random
1617
import re
18+
import sys
1719
import time
1820

1921
from . import coverage
2022
from .authproxy import AuthServiceProxy, JSONRPCException
21-
from typing import Callable, Optional
23+
from typing import Callable, Optional, Tuple
2224

2325
logger = logging.getLogger("TestFramework.utils")
2426

@@ -419,6 +421,22 @@ def get_datadir_path(dirname, n):
419421
return os.path.join(dirname, "node" + str(n))
420422

421423

424+
def get_temp_default_datadir(temp_dir: pathlib.Path) -> Tuple[dict, pathlib.Path]:
425+
"""Return os-specific environment variables that can be set to make the
426+
GetDefaultDataDir() function return a datadir path under the provided
427+
temp_dir, as well as the complete path it would return."""
428+
if sys.platform == "win32":
429+
env = dict(APPDATA=str(temp_dir))
430+
datadir = temp_dir / "Bitcoin"
431+
else:
432+
env = dict(HOME=str(temp_dir))
433+
if sys.platform == "darwin":
434+
datadir = temp_dir / "Library/Application Support/Bitcoin"
435+
else:
436+
datadir = temp_dir / ".bitcoin"
437+
return env, datadir
438+
439+
422440
def append_config(datadir, options):
423441
with open(os.path.join(datadir, "bitcoin.conf"), 'a', encoding='utf8') as f:
424442
for option in options:

0 commit comments

Comments
 (0)