Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
|
Concept ACK, the surprising nature of the negations was documented a few times, e.g. in #36861 (comment) |
Hm, that was opened after I did my initial research on related open PRs. Clearly there is a lot overlap, I will check if a separate PR still make sense. |
|
The first commit (cluster limit below 1) is covered in #36861 and the last commit (disallow negating) got some approach push back there already. Generally the "piecemeal" approach there got push back too. I think this here is a bit better but it also doesn't handle everything inside argsman. I tend to drop the first and the last commit and otherwise keep the PR open separately but I will comment about it on #36861 and see what the feedback is first. |
There was a problem hiding this comment.
Concept ACK 4b181fd, and approach ACK with a few tweaks.
My main feedback is that I think "no" should mean none, false, or zero, or else be an error. We should avoid more clever interpretations like "default" or "unlimited", even where they could be sensible, because the precedent for mapping negated options to falsy values is well established, and other interpretations create unnecessary ambiguity.
Inline comments suggest changes to NEGATE_TO_DEFAULT (#36880 (comment)), -noblocksdir/-nowalletdir (#36880 (comment), #36880 (comment)), -notorcontrol (#36880 (comment)) and -nobantime (#36880 (comment)).
| if (mempool_opts.limits.cluster_count < 1 || mempool_opts.limits.cluster_count > MAX_CLUSTER_COUNT_LIMIT) { | ||
| return util::Error{Untranslated(strprintf("limitclustercount must be between 1 and %d", MAX_CLUSTER_COUNT_LIMIT))}; | ||
| } |
There was a problem hiding this comment.
In commit "mempool: Reject cluster limits below 1" (512773d)
Note: This change looks right to me: -nolimitclustercount is treated as 0, and 0 is rejected as out of bounds. If we ever need an unlimited or automatic setting, an explicit value like -limitclustercount=unlimited would be better than a special meaning for -nolimitclustercount.
Also fine with me if this moves to #36861. Both reject negated and 0 values, but the checks there range-check before narrowing to unsigned and multiplying by 1000, so they also reject -limitclustercount=4294967297, which wraps to 1 here, and very large -limitclustersize values, which overflow here and crash a -ftrapv debug build.
There was a problem hiding this comment.
6447b07 to
8731550
Compare
|
Addressed review feedback from @ryanofsky, thanks a lot! Also rebased for good measure since the CI failed with an unrelated error. The table in the pull description is updated as well. |
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK 8731550. This fixes a set of options where -nofoo did the opposite of what it says, failed startup, or crashed the node, and makes negation behave predictably: negated options now mean empty or 0, and negating a limit where 0 would mean something very different is an error.
Thanks for taking all the suggestions from my last review!
8731550 to
7658850
Compare
-limitclustercount=0 or -nolimitclustercount passed the upper bound check and triggered an assertion in TxGraph when mempool sanity checks are enabled, while -limitclustersize=0 or -nolimitclustersize made every transaction fail with a misleading error. Reject both at startup.
7658850 to
f65919e
Compare
|
Addressed feedback from @ryanofsky , thanks a lot again! Also required a rebase due to the merge of #36637. |
ryanofsky
left a comment
There was a problem hiding this comment.
Code review f65919e. The changes from my last review all look good, but the new -nosigner test found a real bug in builds without the wallet (#36880 (comment)), so I'll re-ACK once that's fixed.
Thanks for the quick update and for adding the tests!
f65919e to
24e7274
Compare
The node reads -signer in builds without the wallet too, for enumeratesigners and the GUI, since the external signer was moved out of the wallet in bitcoin#21467. It was still registered as a wallet option though, and only as a hidden placeholder in DummyWalletInit, so flags set on it did not apply in those builds. Register it in SetupServerArgs() instead. The -help output of wallet builds stays the same. Builds without the wallet now show it under the wallet options, and builds with neither the wallet nor external signer support reject it, like wallet builds without external signer support already do. Co-authored-by: Ryan Ofsky <[email protected]>
GetArg() returns "0" for a negated option, so -noblocknotify, -nowalletnotify, -nostartupnotify and -noalertnotify ran the command "0", -nosigner used "0" as the signer command, -noi2psam failed at startup and -norpcpassword set the RPC password to "0" instead of using cookie authentication. Add a NEGATE_TO_EMPTY flag that makes GetArg() return "" instead, like GetPathArg() already does for negated paths and as doc/bitcoin-conf.md describes for negated strings, and use it for these options as well as -rpcuser and -torpassword. Returning "" rather than the default keeps -nofoo meaning none if one of these options gets a default later. The flag is opt-in because other options such as -noonion and -noblockfilterindex rely on reading "0". Co-authored-by: Ryan Ofsky <[email protected]>
Both were checked with IsArgSet(), so -cjdnsreachable=0 and -nocjdnsreachable made CJDNS reachable, contradicting the -rpcallowip error that tells users to set -cjdnsreachable=0, and -nohelp printed the help text. Use GetBoolArg() instead.
… as unset This changes the behavior of negated and empty -blocksdir and -walletdir values. Other values behave the same as before. -noblocksdir Before: same as -blocksdir= below. After: startup error "Negating of -blocksdir is meaningless and therefore forbidden". -blocksdir= Before: depended on the C++ standard library. With libstdc++ (most Linux builds), startup aborted with an uncaught "cannot make absolute path" filesystem exception. With libc++ (macOS), block files were written under the working directory while the block index stayed in the datadir. After: blocks are stored in the default location in the datadir, as if -blocksdir were not set. -nowalletdir Before: startup error 'Specified -walletdir "" does not exist'. After: startup error "Negating of -walletdir is meaningless and therefore forbidden". -walletdir= Before: startup error 'Specified -walletdir "" does not exist'. After: wallets are loaded from the default wallet directory, as if -walletdir were not set. The negated forms are rejected, like -nodatadir, instead of falling back to the default directory, because -noblocksdir and -nowalletdir read as not using a directory at all.
-notorcontrol made the node connect to the Tor control port at "0", i.e. 0.0.0.0:9051, which reaches a local Tor on most systems. Reject it while the automatic onion service is enabled, so the user has to turn that off explicitly with -nolistenonion rather than having -notorcontrol guess what else to disable. It still works when -listenonion is already off, for example through -listen=0.
-nocheckblocks, -nomaxreceivebuffer, -nomaxsendbuffer and -nomaxtipage read as 0, which is the opposite of what the negation suggests. All blocks are checked, buffers are minimal and the node never leaves initial block download. Reject them at startup instead.
24e7274 to
9cf00ac
Compare
|
Addressed feedback from @ryanofsky , thanks again for the review! |
l0rinc
left a comment
There was a problem hiding this comment.
I like this targeted cleanup of surprising -no behavior while preserving options where 0 is meaningful. I left inline suggestions for -nodbcache, the signer field in Qt, and a few test gaps.
| std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const | ||
| { | ||
| const common::SettingsValue value = GetSetting(strArg); | ||
| if (value.isFalse() && (GetArgFlags(strArg).value_or(0) & NEGATE_TO_EMPTY)) return ""; |
There was a problem hiding this comment.
c3b3522 args: Add NEGATE_TO_EMPTY so -nofoo reads as an empty string:
With nosigner=1, the Options dialog should show an empty signer path instead of 0.
Example patch
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index 0744702888..c4bcaeb668 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -445,8 +445,10 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
return SettingToBool(setting()).value_or(wallet::DEFAULT_SPEND_ZEROCONF_CHANGE);
- case ExternalSignerPath:
- return QString::fromStdString(SettingToString(setting()).value_or(""));
+ case ExternalSignerPath: {
+ const auto signer{setting()};
+ return QString::fromStdString(signer.isFalse() ? "" : SettingToString(signer).value_or(""));
+ }
case SubFeeFromAmount:
return m_sub_fee_from_amount;
#endif
diff --git a/src/qt/test/optiontests.cpp b/src/qt/test/optiontests.cpp
index 144743b107..6bbd9fd9fa 100644
--- a/src/qt/test/optiontests.cpp
+++ b/src/qt/test/optiontests.cpp
@@ -13,6 +13,7 @@
#include <QSettings>
#include <QTest>
+#include <QVariant>
#include <univalue.h>
@@ -103,6 +104,19 @@ void OptionTests::integerGetArgBug()
gArgs.WriteSettingsFile();
}
+void OptionTests::negatedExternalSigner()
+{
+#ifdef ENABLE_WALLET
+ OptionsModel options{m_node};
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = false; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{});
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = "0"; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{"0"});
+#else
+ QSKIP("Wallet support is disabled");
+#endif
+}
+
void OptionTests::parametersInteraction()
{
// Test that the bug https://github.com/bitcoin-core/gui/issues/567 does not resurface.
diff --git a/src/qt/test/optiontests.h b/src/qt/test/optiontests.h
index f8791882f9..8562169a4c 100644
--- a/src/qt/test/optiontests.h
+++ b/src/qt/test/optiontests.h
@@ -21,6 +21,7 @@ private Q_SLOTS:
void init(); // called before each test function execution.
void migrateSettings();
void integerGetArgBug();
+ void negatedExternalSigner();
void parametersInteraction();
void extractFilter();
There was a problem hiding this comment.
re: #36880 (comment)
In commit "args: Add NEGATE_TO_EMPTY so -nofoo reads as an empty string" (c3b3522)
With
nosigner=1, the Options dialog should show an empty signer path instead of0.
Good catch. But I think it would be better to fix this in SettingToString() than in the GUI. The underlying problem is that SettingToString() converts negated values differently from GetArg(), which applies NEGATE_TO_EMPTY itself before calling it. If SettingToString() took the option's flags as a required argument and applied NEGATE_TO_EMPTY itself, GetArg() could pass GetArgFlags() and OptionsModel could pass the flags from gArgs, where the GUI registers its options, so the two couldn't disagree. Making the argument required also lets the compiler find every caller.
I tried this with your test, and it passes with the change and fails without it. The test needs to register the options first, because the Qt test harness clears them:
Diff
diff --git a/src/common/args.cpp b/src/common/args.cpp
index 338ef7f9ad..36c2fc2178 100644
--- a/src/common/args.cpp
+++ b/src/common/args.cpp
@@ -283,7 +283,7 @@ fs::path ArgsManager::GetPathArg_(std::string arg, const fs::path& default_value
AssertLockHeld(cs_args);
const auto value = GetSetting_(arg);
if (value.isFalse()) return {};
- std::string path_str = SettingToString(value).value_or("");
+ std::string path_str = SettingToString(value, GetArgFlags_(arg).value_or(0)).value_or("");
if (path_str.empty()) return default_value;
fs::path result = fs::PathFromString(path_str).lexically_normal();
// Remove trailing slash, if present.
@@ -524,14 +524,13 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st
std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
{
const common::SettingsValue value = GetSetting(strArg);
- if (value.isFalse() && (GetArgFlags(strArg).value_or(0) & NEGATE_TO_EMPTY)) return "";
- return SettingToString(value);
+ return SettingToString(value, GetArgFlags(strArg).value_or(0));
}
-std::optional<std::string> SettingToString(const common::SettingsValue& value)
+std::optional<std::string> SettingToString(const common::SettingsValue& value, unsigned int flags)
{
if (value.isNull()) return std::nullopt;
- if (value.isFalse()) return "0";
+ if (value.isFalse()) return (flags & ArgsManager::NEGATE_TO_EMPTY) ? "" : "0";
if (value.isTrue()) return "1";
if (value.isNum()) return value.getValStr();
return value.get_str();
diff --git a/src/common/args.h b/src/common/args.h
index db55b5402e..262de886f8 100644
--- a/src/common/args.h
+++ b/src/common/args.h
@@ -91,7 +91,9 @@ struct SectionInfo {
int m_line;
};
-std::optional<std::string> SettingToString(const common::SettingsValue&);
+//! Convert a setting value to a string. Pass the option's ArgsManager flags
+//! (e.g. from GetArgFlags()) so flags like NEGATE_TO_EMPTY apply.
+std::optional<std::string> SettingToString(const common::SettingsValue&, unsigned int flags);
template <std::integral Int>
std::optional<Int> SettingTo(const common::SettingsValue&);
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index 0744702888..c45c3d37dc 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -160,7 +160,7 @@ void OptionsModel::addOverriddenOption(const std::string &option)
bool OptionsModel::Init(bilingual_str& error)
{
// Initialize display settings from stored settings.
- language = QString::fromStdString(SettingToString(node().getPersistentSetting("lang")).value_or(""));
+ language = QString::fromStdString(SettingToString(node().getPersistentSetting("lang"), gArgs.GetArgFlags("-lang").value_or(0)).value_or(""));
checkAndMigrate();
@@ -401,6 +401,7 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) const
{
auto setting = [&]{ return node().getPersistentSetting(SettingName(option) + suffix); };
+ auto flags = [&]{ return gArgs.GetArgFlags(std::string{"-"} + SettingName(option)).value_or(0); };
QSettings settings;
switch (option) {
@@ -418,10 +419,10 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
// default proxy
case ProxyUse:
case ProxyUseTor:
- return ParseProxyString(SettingToString(setting()).value_or("")).is_set;
+ return ParseProxyString(SettingToString(setting(), flags()).value_or("")).is_set;
case ProxyIP:
case ProxyIPTor: {
- ProxySetting proxy = ParseProxyString(SettingToString(setting()).value_or(""));
+ ProxySetting proxy = ParseProxyString(SettingToString(setting(), flags()).value_or(""));
if (proxy.is_set) {
return proxy.ip;
} else if (suffix.empty()) {
@@ -432,7 +433,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
}
case ProxyPort:
case ProxyPortTor: {
- ProxySetting proxy = ParseProxyString(SettingToString(setting()).value_or(""));
+ ProxySetting proxy = ParseProxyString(SettingToString(setting(), flags()).value_or(""));
if (proxy.is_set) {
return proxy.port;
} else if (suffix.empty()) {
@@ -446,7 +447,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
case SpendZeroConfChange:
return SettingToBool(setting()).value_or(wallet::DEFAULT_SPEND_ZEROCONF_CHANGE);
case ExternalSignerPath:
- return QString::fromStdString(SettingToString(setting()).value_or(""));
+ return QString::fromStdString(SettingToString(setting(), flags()).value_or(""));
case SubFeeFromAmount:
return m_sub_fee_from_amount;
#endif
@@ -455,7 +456,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
case ThirdPartyTxUrls:
return strThirdPartyTxUrls;
case Language:
- return QString::fromStdString(SettingToString(setting()).value_or(""));
+ return QString::fromStdString(SettingToString(setting(), flags()).value_or(""));
case FontForMoney:
return QVariant::fromValue(m_font_money);
case CoinControlFeatures:
diff --git a/src/qt/test/optiontests.cpp b/src/qt/test/optiontests.cpp
index 144743b107..9b538b789a 100644
--- a/src/qt/test/optiontests.cpp
+++ b/src/qt/test/optiontests.cpp
@@ -13,6 +13,7 @@
#include <QSettings>
#include <QTest>
+#include <QVariant>
#include <univalue.h>
@@ -26,6 +27,7 @@ OptionTests::OptionTests(interfaces::Node& node) : m_node(node)
void OptionTests::init()
{
// reset args
+ gArgs.ClearArgs();
gArgs.LockSettings([&](common::Settings& s) { s = m_previous_settings; });
gArgs.ClearPathCache();
}
@@ -103,6 +105,22 @@ void OptionTests::integerGetArgBug()
gArgs.WriteSettingsFile();
}
+void OptionTests::negatedExternalSigner()
+{
+#ifdef ENABLE_WALLET
+ // Register options the way the GUI does in bitcoin.cpp, so -signer has its
+ // NEGATE_TO_EMPTY flag. cleanup() clears them again.
+ SetupServerArgs(gArgs, /*can_listen_ipc=*/false);
+ OptionsModel options{m_node};
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = false; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{});
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = "0"; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{"0"});
+#else
+ QSKIP("Wallet support is disabled");
+#endif
+}
+
void OptionTests::parametersInteraction()
{
// Test that the bug https://github.com/bitcoin-core/gui/issues/567 does not resurface.
diff --git a/src/qt/test/optiontests.h b/src/qt/test/optiontests.h
index f8791882f9..8562169a4c 100644
--- a/src/qt/test/optiontests.h
+++ b/src/qt/test/optiontests.h
@@ -21,6 +21,7 @@ private Q_SLOTS:
void init(); // called before each test function execution.
void migrateSettings();
void integerGetArgBug();
+ void negatedExternalSigner();
void parametersInteraction();
void extractFilter();
| alert_text = f.read() | ||
| blocknotify_files = sorted(os.listdir(self.blocknotify_dir)) | ||
| walletnotify_files = sorted(os.listdir(self.walletnotify_dir)) | ||
| with self.nodes[0].assert_debug_log(expected_msgs=[], unexpected_msgs=["runCommand error"]), \ |
There was a problem hiding this comment.
c3b3522 args: Add NEGATE_TO_EMPTY so -nofoo reads as an empty string:
The alert-file check can pass without exercising -noalertnotify if the warning does not recur after restart.
Example patch
diff --git a/test/functional/feature_notifications.py b/test/functional/feature_notifications.py
index 4249120bce..89dcb3748d 100755
--- a/test/functional/feature_notifications.py
+++ b/test/functional/feature_notifications.py
@@ -238,7 +238,7 @@ class NotificationsTest(BitcoinTestFramework):
alert_text = f.read()
blocknotify_files = sorted(os.listdir(self.blocknotify_dir))
walletnotify_files = sorted(os.listdir(self.walletnotify_dir))
- with self.nodes[0].assert_debug_log(expected_msgs=[], unexpected_msgs=["runCommand error"]), \
+ with self.nodes[0].assert_debug_log(expected_msgs=["Found invalid chain more than 6 blocks longer"], unexpected_msgs=["runCommand error"]), \
self.nodes[1].assert_debug_log(expected_msgs=[], unexpected_msgs=["runCommand error"]):
self.start_node(0, extra_args=self.extra_args[0] + ["-noblocknotify", "-noalertnotify"])
self.start_node(1, extra_args=self.extra_args[1] + ["-nowalletnotify"])| self.log.info("Test -norpcuser sends an empty user name") | ||
| # The node's cookie user is __cookie__, so an empty user name fails | ||
| # here. Node-side -norpcuser is tested in rpc_users.py. | ||
| assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword were specified', self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', '-norpcuser', f'-rpcpassword={password}').echo) |
There was a problem hiding this comment.
c3b3522 args: Add NEGATE_TO_EMPTY so -nofoo reads as an empty string:
The authentication failure is the same for an empty username and 0, so this check does not prove -norpcuser works.
Example patch
diff --git a/test/functional/interface_bitcoin_cli.py b/test/functional/interface_bitcoin_cli.py
index bf90935828..a0904e4f71 100755
--- a/test/functional/interface_bitcoin_cli.py
+++ b/test/functional/interface_bitcoin_cli.py
@@ -241,11 +241,6 @@ class TestBitcoinCli(BitcoinTestFramework):
assert_equal(BLOCKS, self.nodes[0].cli('-rpcpassword=foo', '-norpcpassword').getblockcount())
assert_raises_process_error(1, "Cookie file was disabled via -norpccookiefile and no rpcpassword was specified.", self.nodes[0].cli("-norpccookiefile", "-norpcpassword").echo)
- self.log.info("Test -norpcuser sends an empty user name")
- # The node's cookie user is __cookie__, so an empty user name fails
- # here. Node-side -norpcuser is tested in rpc_users.py.
- assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword were specified', self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', '-norpcuser', f'-rpcpassword={password}').echo)
-
self.log.info("Test connecting without RPC cookie file and with password arg")
assert_equal(BLOCKS, self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', f'-rpcpassword={password}').getblockcount())
diff --git a/test/functional/rpc_users.py b/test/functional/rpc_users.py
index eede5ed55c..197ce6336f 100755
--- a/test/functional/rpc_users.py
+++ b/test/functional/rpc_users.py
@@ -157,6 +157,8 @@ class HTTPBasicsTest(BitcoinTestFramework):
assert_equal(200, call_with_auth(self.nodes[0], "", "secret").status)
assert_equal(401, call_with_auth(self.nodes[0], "0", "secret").status)
assert_equal(401, call_with_auth(self.nodes[0], "alice", "secret").status)
+ if self.is_cli_compiled():
+ assert_equal(["hello"], self.nodes[0].cli("-rpcuser=alice", "-norpcuser", "-rpcpassword=secret").echo("hello"))
assert_equal(200, call_with_auth(self.nodes[0], "", "secret", method="stop").status)
self.nodes[0].wait_until_stopped()
There was a problem hiding this comment.
re: #36880 (comment)
The authentication failure is the same for an empty username and
0, so this check does not prove-norpcuserworks.
Agree, this is better than the check I suggested, which only showed the request failed. In rpc_users.py the node's user name is already checked to be empty by the call_with_auth lines before it, so the bitcoin-cli call there should only succeed if -norpcuser sends an empty user name too. The Ralph review flagged the old check too.
| self.stop_node(0) | ||
| self.nodes[0].replace_in_config([("listenonion=0\n", "")]) | ||
| self.nodes[0].assert_start_raises_init_error(["-notorcontrol"], "Error: -notorcontrol cannot be used while -listenonion is enabled (the default). Use -nolistenonion to stop connecting to the Tor control port.") | ||
| self.start_node(0, extra_args=["-notorcontrol", "-nolistenonion"]) |
There was a problem hiding this comment.
f204dc0 init: Require -nolistenonion with -notorcontrol:
This test also needs to cover -notorcontrol -listen=0, which disables onion listening implicitly.
Example patch
diff --git a/test/functional/feature_torcontrol.py b/test/functional/feature_torcontrol.py
index c1fc55241f..aa098e2134 100755
--- a/test/functional/feature_torcontrol.py
+++ b/test/functional/feature_torcontrol.py
@@ -343,11 +343,13 @@ class TorControlTest(BitcoinTestFramework):
mock_tor.stop()
def test_notorcontrol(self):
- self.log.info("Test that -notorcontrol requires -nolistenonion")
+ self.log.info("Test that -notorcontrol requires onion listening to be disabled")
self.stop_node(0)
self.nodes[0].replace_in_config([("listenonion=0\n", "")])
self.nodes[0].assert_start_raises_init_error(["-notorcontrol"], "Error: -notorcontrol cannot be used while -listenonion is enabled (the default). Use -nolistenonion to stop connecting to the Tor control port.")
self.start_node(0, extra_args=["-notorcontrol", "-nolistenonion"])
+ self.nodes[0].replace_in_config([("bind=127.0.0.1\n", "")])
+ self.restart_node(0, extra_args=["-notorcontrol", "-listen=0"])
def test_invalid_service_id(self):
invalid_service_id = "a" + SERVICE_ID[1:]| self.log.info("Starting with an empty -blocksdir uses the datadir ...") | ||
| self.cleanup_folder(self.nodes[0].datadir_path) | ||
| initialize_datadir(self.options.tmpdir, 0, self.chain) | ||
| self.start_node(0, ["-blocksdir="]) |
There was a problem hiding this comment.
27c2e46 args, wallet: Reject -noblocksdir/-nowalletdir and treat empty values as unset:
Without a configured blocksdir, this test passes even if the empty -blocksdir= override is ignored.
Example patch
diff --git a/test/functional/feature_blocksdir.py b/test/functional/feature_blocksdir.py
index 9af23fbf88..f4b476536e 100755
--- a/test/functional/feature_blocksdir.py
+++ b/test/functional/feature_blocksdir.py
@@ -8,6 +8,7 @@
from pathlib import Path
from test_framework.test_framework import BitcoinTestFramework, initialize_datadir
+from test_framework.util import append_config
class BlocksdirTest(BitcoinTestFramework):
@@ -39,6 +40,7 @@ class BlocksdirTest(BitcoinTestFramework):
self.log.info("Starting with an empty -blocksdir uses the datadir ...")
self.cleanup_folder(self.nodes[0].datadir_path)
initialize_datadir(self.options.tmpdir, 0, self.chain)
+ append_config(self.nodes[0].datadir_path, [f"blocksdir={blocksdir_path}"])
self.start_node(0, ["-blocksdir="])
assert (self.nodes[0].blocks_path / "blk00000.dat").is_file()
| expected_msg='Error: Error parsing command line arguments: Can not set -proxy with no value. Please specify value with -proxy=value.', | ||
| extra_args=['-proxy'], | ||
| ) | ||
| for option in ['checkblocks', 'maxreceivebuffer', 'maxsendbuffer', 'maxtipage']: |
There was a problem hiding this comment.
9b63d8f init: Disallow negating options where it has no meaning:
-nodbcache silently selects the 4 MiB minimum rather than disabling the cache. It should be rejected alongside the buffer negations.
Example patch
diff --git a/src/init.cpp b/src/init.cpp
index 01f25de271..a89e137663 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -526,7 +526,7 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", DEFAULT_DB_CACHE_BATCH), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
- argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (minimum %d, default: %d). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).", MIN_DBCACHE_BYTES / 1_MiB, node::GetDefaultDBCache() / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
+ argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (minimum %d, default: %d). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).", MIN_DBCACHE_BYTES / 1_MiB, node::GetDefaultDBCache() / 1_MiB), ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
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);
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);
argsman.AddArg("-loadblock=<file>", "Imports blocks from an external file on startup. Obfuscated blocks are not supported.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
diff --git a/test/functional/feature_config_args.py b/test/functional/feature_config_args.py
index f328b7f3a9..4be06e7d02 100755
--- a/test/functional/feature_config_args.py
+++ b/test/functional/feature_config_args.py
@@ -220,7 +220,7 @@ class ConfArgsTest(BitcoinTestFramework):
expected_msg='Error: Error parsing command line arguments: Can not set -proxy with no value. Please specify value with -proxy=value.',
extra_args=['-proxy'],
)
- for option in ['checkblocks', 'maxreceivebuffer', 'maxsendbuffer', 'maxtipage']:
+ for option in ['checkblocks', 'dbcache', 'maxreceivebuffer', 'maxsendbuffer', 'maxtipage']:
self.nodes[0].assert_start_raises_init_error(
expected_msg=f'Error: Error parsing command line arguments: Negating of -{option} is meaningless and therefore forbidden',
extra_args=[f'-no{option}'],
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK 9cf00ac. This fixes a set of options where -nofoo did the opposite of what it says, failed startup, or crashed the node, and makes negation behave predictably: negated options now mean empty or 0, and negating a limit where 0 would mean something very different is an error.
Thanks for the quick updates and for following up on the placeholder options! l0rinc's suggestions look good to me too, especially making -nodbcache an error (#36880 (comment)) and the two test improvements (#36880 (comment), #36880 (comment)).
| self.log.info("Test -norpcuser sends an empty user name") | ||
| # The node's cookie user is __cookie__, so an empty user name fails | ||
| # here. Node-side -norpcuser is tested in rpc_users.py. | ||
| assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword were specified', self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', '-norpcuser', f'-rpcpassword={password}').echo) |
There was a problem hiding this comment.
re: #36880 (comment)
The authentication failure is the same for an empty username and
0, so this check does not prove-norpcuserworks.
Agree, this is better than the check I suggested, which only showed the request failed. In rpc_users.py the node's user name is already checked to be empty by the call_with_auth lines before it, so the bitcoin-cli call there should only succeed if -norpcuser sends an empty user name too. The Ralph review flagged the old check too.
| std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const | ||
| { | ||
| const common::SettingsValue value = GetSetting(strArg); | ||
| if (value.isFalse() && (GetArgFlags(strArg).value_or(0) & NEGATE_TO_EMPTY)) return ""; |
There was a problem hiding this comment.
re: #36880 (comment)
In commit "args: Add NEGATE_TO_EMPTY so -nofoo reads as an empty string" (c3b3522)
With
nosigner=1, the Options dialog should show an empty signer path instead of0.
Good catch. But I think it would be better to fix this in SettingToString() than in the GUI. The underlying problem is that SettingToString() converts negated values differently from GetArg(), which applies NEGATE_TO_EMPTY itself before calling it. If SettingToString() took the option's flags as a required argument and applied NEGATE_TO_EMPTY itself, GetArg() could pass GetArgFlags() and OptionsModel could pass the flags from gArgs, where the GUI registers its options, so the two couldn't disagree. Making the argument required also lets the compiler find every caller.
I tried this with your test, and it passes with the change and fails without it. The test needs to register the options first, because the Qt test harness clears them:
Diff
diff --git a/src/common/args.cpp b/src/common/args.cpp
index 338ef7f9ad..36c2fc2178 100644
--- a/src/common/args.cpp
+++ b/src/common/args.cpp
@@ -283,7 +283,7 @@ fs::path ArgsManager::GetPathArg_(std::string arg, const fs::path& default_value
AssertLockHeld(cs_args);
const auto value = GetSetting_(arg);
if (value.isFalse()) return {};
- std::string path_str = SettingToString(value).value_or("");
+ std::string path_str = SettingToString(value, GetArgFlags_(arg).value_or(0)).value_or("");
if (path_str.empty()) return default_value;
fs::path result = fs::PathFromString(path_str).lexically_normal();
// Remove trailing slash, if present.
@@ -524,14 +524,13 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st
std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
{
const common::SettingsValue value = GetSetting(strArg);
- if (value.isFalse() && (GetArgFlags(strArg).value_or(0) & NEGATE_TO_EMPTY)) return "";
- return SettingToString(value);
+ return SettingToString(value, GetArgFlags(strArg).value_or(0));
}
-std::optional<std::string> SettingToString(const common::SettingsValue& value)
+std::optional<std::string> SettingToString(const common::SettingsValue& value, unsigned int flags)
{
if (value.isNull()) return std::nullopt;
- if (value.isFalse()) return "0";
+ if (value.isFalse()) return (flags & ArgsManager::NEGATE_TO_EMPTY) ? "" : "0";
if (value.isTrue()) return "1";
if (value.isNum()) return value.getValStr();
return value.get_str();
diff --git a/src/common/args.h b/src/common/args.h
index db55b5402e..262de886f8 100644
--- a/src/common/args.h
+++ b/src/common/args.h
@@ -91,7 +91,9 @@ struct SectionInfo {
int m_line;
};
-std::optional<std::string> SettingToString(const common::SettingsValue&);
+//! Convert a setting value to a string. Pass the option's ArgsManager flags
+//! (e.g. from GetArgFlags()) so flags like NEGATE_TO_EMPTY apply.
+std::optional<std::string> SettingToString(const common::SettingsValue&, unsigned int flags);
template <std::integral Int>
std::optional<Int> SettingTo(const common::SettingsValue&);
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index 0744702888..c45c3d37dc 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -160,7 +160,7 @@ void OptionsModel::addOverriddenOption(const std::string &option)
bool OptionsModel::Init(bilingual_str& error)
{
// Initialize display settings from stored settings.
- language = QString::fromStdString(SettingToString(node().getPersistentSetting("lang")).value_or(""));
+ language = QString::fromStdString(SettingToString(node().getPersistentSetting("lang"), gArgs.GetArgFlags("-lang").value_or(0)).value_or(""));
checkAndMigrate();
@@ -401,6 +401,7 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) const
{
auto setting = [&]{ return node().getPersistentSetting(SettingName(option) + suffix); };
+ auto flags = [&]{ return gArgs.GetArgFlags(std::string{"-"} + SettingName(option)).value_or(0); };
QSettings settings;
switch (option) {
@@ -418,10 +419,10 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
// default proxy
case ProxyUse:
case ProxyUseTor:
- return ParseProxyString(SettingToString(setting()).value_or("")).is_set;
+ return ParseProxyString(SettingToString(setting(), flags()).value_or("")).is_set;
case ProxyIP:
case ProxyIPTor: {
- ProxySetting proxy = ParseProxyString(SettingToString(setting()).value_or(""));
+ ProxySetting proxy = ParseProxyString(SettingToString(setting(), flags()).value_or(""));
if (proxy.is_set) {
return proxy.ip;
} else if (suffix.empty()) {
@@ -432,7 +433,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
}
case ProxyPort:
case ProxyPortTor: {
- ProxySetting proxy = ParseProxyString(SettingToString(setting()).value_or(""));
+ ProxySetting proxy = ParseProxyString(SettingToString(setting(), flags()).value_or(""));
if (proxy.is_set) {
return proxy.port;
} else if (suffix.empty()) {
@@ -446,7 +447,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
case SpendZeroConfChange:
return SettingToBool(setting()).value_or(wallet::DEFAULT_SPEND_ZEROCONF_CHANGE);
case ExternalSignerPath:
- return QString::fromStdString(SettingToString(setting()).value_or(""));
+ return QString::fromStdString(SettingToString(setting(), flags()).value_or(""));
case SubFeeFromAmount:
return m_sub_fee_from_amount;
#endif
@@ -455,7 +456,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con
case ThirdPartyTxUrls:
return strThirdPartyTxUrls;
case Language:
- return QString::fromStdString(SettingToString(setting()).value_or(""));
+ return QString::fromStdString(SettingToString(setting(), flags()).value_or(""));
case FontForMoney:
return QVariant::fromValue(m_font_money);
case CoinControlFeatures:
diff --git a/src/qt/test/optiontests.cpp b/src/qt/test/optiontests.cpp
index 144743b107..9b538b789a 100644
--- a/src/qt/test/optiontests.cpp
+++ b/src/qt/test/optiontests.cpp
@@ -13,6 +13,7 @@
#include <QSettings>
#include <QTest>
+#include <QVariant>
#include <univalue.h>
@@ -26,6 +27,7 @@ OptionTests::OptionTests(interfaces::Node& node) : m_node(node)
void OptionTests::init()
{
// reset args
+ gArgs.ClearArgs();
gArgs.LockSettings([&](common::Settings& s) { s = m_previous_settings; });
gArgs.ClearPathCache();
}
@@ -103,6 +105,22 @@ void OptionTests::integerGetArgBug()
gArgs.WriteSettingsFile();
}
+void OptionTests::negatedExternalSigner()
+{
+#ifdef ENABLE_WALLET
+ // Register options the way the GUI does in bitcoin.cpp, so -signer has its
+ // NEGATE_TO_EMPTY flag. cleanup() clears them again.
+ SetupServerArgs(gArgs, /*can_listen_ipc=*/false);
+ OptionsModel options{m_node};
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = false; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{});
+ gArgs.LockSettings([](common::Settings& settings) { settings.rw_settings["signer"] = "0"; });
+ QCOMPARE(options.getOption(OptionsModel::ExternalSignerPath).toString(), QString{"0"});
+#else
+ QSKIP("Wallet support is disabled");
+#endif
+}
+
void OptionTests::parametersInteraction()
{
// Test that the bug https://github.com/bitcoin-core/gui/issues/567 does not resurface.
diff --git a/src/qt/test/optiontests.h b/src/qt/test/optiontests.h
index f8791882f9..8562169a4c 100644
--- a/src/qt/test/optiontests.h
+++ b/src/qt/test/optiontests.h
@@ -21,6 +21,7 @@ private Q_SLOTS:
void init(); // called before each test function execution.
void migrateSettings();
void integerGetArgBug();
+ void negatedExternalSigner();
void parametersInteraction();
void extractFilter();
| - An empty `-blocksdir=` or `-walletdir=` now uses the default directory, as | ||
| if the option were not set. (#36880) |
There was a problem hiding this comment.
In commit "doc: Add release note for negated option changes" (9cf00ac)
It might help to mention what previous behavior was, since "now uses the default directory" raises question of what was happening before:
| - An empty `-blocksdir=` or `-walletdir=` now uses the default directory, as | |
| if the option were not set. (#36880) | |
| - An empty `-blocksdir=` or `-walletdir=` now uses the default directory, as | |
| if the option were not set. Previously they could fail at startup or, for | |
| `-blocksdir=`, use the current working directory, depending on the platform. | |
| (#36880) |
|
🐙 This pull request conflicts with the target branch and needs rebase. |

While looking into #36759 I discovered
-notorcontroldid the opposite of what would be expected from it and I then checked for similar issues in other init options. There are several more where-nofoodoes something surprising including one of them crashing the node.This PR attempts to fix all these surprising behaviors while also keeping things as simple as possible and just change behavior to something that makes sense harmless in the context of the option. Fixes that use a common approach for the fix are grouped together into a commit even if the options included themselves may have no relation at all.
-nolimitclustercounthits an assertion inTxGraphon the first mempool transaction.-nolimitclustersizerejects every transaction.GetArg()returns"0"for a negated option. The-no*notifyoptions run the command0,-nosigneruses0as signer,-noi2psamfails startup and-norpcpasswordsets the password to0. Opt-in because options like-noonionand-noblockfilterindexdepend on reading"0".NEGATE_TO_EMPTYmakesGetArg()return"".-cjdnsreachable=0and-nocjdnsreachableturn CJDNS on.-nohelpprints the help.GetBoolArg()instead ofIsArgSet().-noblocksdirwrites block files relative to the working directory.-nowalletdirfails startup.DISALLOW_NEGATION. An empty value falls back to the default directory, like-datadirdoes.-notorcontrolconnects to0.0.0.0:9051, which reaches a local Tor.-listenonionis disabled.-nocheckblocks,-nomaxreceivebuffer,-nomaxsendbufferand-nomaxtipageread as 0, the opposite of what the user asked for.DISALLOW_NEGATION.-nomempoolexpiryhas a similar kind of problem. It evicts transactions as soon as the next one arrives. I left it out because #36540 already is open and addresses this.