mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:29:39 +00:00
Configuration argument handling improvements. #36861
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36861
Loading…
Reference in a new issue
No description provided.
Delete branch "configValidation"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Several numeric options were read with GetArg() and then stored into unsigned or wider members without a range check. A negative value wrapped to a huge value and disabled the limit it was meant to configure, and a value wider than the destination could silently become a different number.
Parse the options whose destination is unsigned with ToIntegral() on the raw string rather than with GetArg(): the typed getter saturates values it cannot represent (so a leading '-' for an unsigned T becomes 0), while ToIntegral rejects '-', trailing garbage and overflow instead of saturating. Reject the remaining out-of-range values where they are read:
Zero remains valid wherever it already meant "disabled": -dbbatchsize, -datacarriersize, -mempoolexpiry, -maxtipage, -bytespersigop, -maxsendbuffer, -maxreceivebuffer, -limitancestorcount and -limitdescendantcount.
Since -nofoo is parsed as 0, add DISALLOW_NEGATION to the options where 0 is valid but very different from "no limit": -dbbatchsize, -mempoolexpiry, -maxreceivebuffer, -maxsendbuffer, -maxtipage, -limitancestorcount, -limitdescendantcount and -datacarriersize. Options that already reject (-bantime, -timeout, -peertimeout, -limitclustercount, -limitclustersize, -txconfirmtarget) need no separate check: negation reports the value error once. -bytespersigop still allows negation, because 0 turns the sigop adjustment off, which is exactly what -nobytespersigop says.
ReadCoinsViewArgs now returns util::Result (marked nodiscard) so its errors abort startup instead of being discarded.
Finally, -help gains the = placeholder for the options that take a value (-dbbatchsize, -bytespersigop, -datacarriersize, -stopatheight, -checkblockindex) and states the bounds for -bantime, -limitclustercount, -limitclustersize and -txconfirmtarget.
Add unit tests for the option parsers and functional tests for the accepted, rejected and negated forms.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, 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.
Earlier concerns neither republished nor resolved: 1 minor finding · 3 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor · Release notes misdescribe restrictive zero values as unlimited
The new release note can lead operators to set
-mempoolexpiry=0expecting no expiry, although zero instead expires older transactions at the next limiting pass.Location:
doc/release-notes-36861.md:29(head).🔵 Suggestion ·
-maxtipagestrict parsing also removes a previously tested rangeStrict parsing rejects previously regression-tested
-maxtipagevalues throughINT64_MAXeven though the seconds-based consumer handles them; no operational reliance on the widerDEBUG_ONLYrange is known.Location:
src/node/chainstatemanager_args.cpp:63(head).🔵 Suggestion ·
mempool_args_validationdiscards the parsed valuesmempool_args_validationchecks only success or failure, so incorrect stored values and a regression in wide-hour expiry handling would pass its new assertions.Location:
src/test/mempool_tests.cpp:557(head).🔵 Suggestion · Strict-parser tests miss numeric prefixes with trailing garbage
The new database-option assertions do not distinguish strict whole-string parsing from prefix parsing with the same range checks.
Location:
src/test/validation_chainstatemanager_tests.cpp:1026(head).🔵 Suggestion ·
-txconfirmtargetestimator policy is coupled to storage-range checksA separate wallet commit would make the new load-time estimator ceiling, including its
-blocksonlyexemption, independently reviewable and revertible without undoing unrelated numeric hardening.Location: src/wallet/wallet.cpp:2854 (commit).
Review coverage was incomplete.
Reviewed:
830af36b820d· Review report · Previous reportspermalink
Concept ACK
There are lots of AI findings about these potential misconfigurations, so it would be good to close off as many of them as possible in one go.
A few closely related cases seem worth covering as well:
-timeoutvalues aboveINT_MAXare narrowed before the new positivity check (similar ones were already attempted here and closed).-mempoolexpiryvalues can overflow when converted from hours to seconds.-txconfirmtargetwraps into the wallet's unsigned target and can make fee estimation fall back to-fallbackfee.0, so-nolimitclustersizeand-nobantimeare equivalent to the zero values this PR explicitly accepts.-limitclustersize=0makes every transaction oversized and prevents normal mempool admission, while-bantime=0makessetbanwithout an explicit duration create an immediately expired ban.CI seems to fail because the new test loop binds a
std::stringreference to temporary strings.🚧 At least one of the CI tasks failed.
Task
i686: https://github.com/bitcoin/bitcoin/actions/runs/43477395661/job/132064683071LLM reason (✨ experimental): The build failed because
mempool_tests.cpptriggers a range-loop warning treated as an error:const std::string&binds to temporary strings.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
See https://github.com/bitcoin/bitcoin/issues/36763
But I think I'm Approach NACK at yet another piecemeal approach to a solution for this. This should be solved by the args handler itself, not with many different bug prone special cases.
Concept ACK
1ab3f14858for parsing improvements here, but I'd recommend against increased use of the DISALLOW_NEGATION flag:DISALLOW_NEGATION was intended to used rarely and eventually removed (https://github.com/bitcoin/bitcoin/pull/22766#issuecomment-944924866) and this PR seems to increase usage by a lot. The other changes here look very good though.
left some nits
this fix seems wrong. The correct fix would be to just parse as u32. Note that chrono itself can't deal with i64 here:
std::chrono::seconds std::chrono::duration</* int35 */>u64?
maybe
simulate_crash_ratioshould be u32?parsing should be done as u32?
Concept ACK
There is a bit of overlap between this and https://github.com/bitcoin/bitcoin/pull/36880 and I didn't catch the overlap because I looked for related PRs before this PR here was opened. This particularly focusses on the "-no..." flags behavior. It may be a little bit better in some parts but others may still be considered too "piecemeal".
I could drop parts of my PR to remove the overlap but I would first like to see if the approach should be completely different. I am particularly interested in fixing the
-no...options that either do the complete opposite of what's expected or even prevent startup or can crash the node. I think that is worth fixing even with a more priecemeal approach but I am also fine if these can drive a faster implementation of fixes within argsman.re: https://github.com/bitcoin/bitcoin/pull/36861#pullrequestreview-5899222221
Correction to my earlier review: I overstated the case against
DISALLOW_NEGATION, sorry about that. It makes sense for options that are a maximum, limit, or timeout, where-nofooreads as "no limit" but 0 means something very different. Ideally-nofoomight mean unlimited for these, but since negation has always meant 0, an error is the safest choice.I still think negation should generally behave like setting 0 or empty values, and if these values are invalid, better to check for them once than have multiple checks producing different errors. By that standard, about half of the uses here look right to me, and the rest aren't needed:
-dbbatchsize,-mempoolexpiry,-maxreceivebuffer,-maxsendbuffer,-maxtipage,-limitancestorcount,-limitdescendantcount,-datacarriersize.-nofoowould get that error:-bantime,-timeout,-peertimeout,-limitclustercount,-limitclustersize,-txconfirmtarget.-nofoosays:-bytespersigop, where 0 turns off the sigop adjustment.Updated negation support:
-bantime → Error: -bantime must be greater than 0 (got 0).
-timeout → Error: timeout must be a positive integer.
-peertimeout → Error: peertimeout must be a positive integer.
-limitclustercount → Error: limitclustercount must be between 1 and 64 (got 0)
-limitclustersize → Error: limitclustersize must be between 1 and 9223372036854775 kilobytes (got 0)
-txconfirmtarget → Error: -txconfirmtarget must be between 1 and 4294967295 (got 0).
-bytespersigop → accepts negation silently, since 0 means "no sigop adjustment"
Each is now validated in exactly one place, and -nofoo produces the identical message to -foo=0
I know that parsing saturates, but I am not sure if it is the right fix to do manual parsing one-by-one at each call site.
This is adding tens of lines of code for what is basically a debug-only option. Also, it takes away the saturation "feature" here.
I think we'll have to decide:
Maybe this can be done with a new Getter that takes an options object with the upper and lower bound and then it returns either nothing (if nothing was set), or the value (if it fits the range), or the error (if it doesn't fit the range, or so)?
Code review ACK
9611ea5584. This makes numeric options that master silently accepts with nonsensical values (negative buffer sizes, ban times and confirmation targets,-timeout=0), or that crash the node (-limitclustercount=0), fail at startup with clear errors instead. I tried each changed option on regtest with valid, out-of-range and negated values, and they all behaved as described.I still think these checks would be better in ArgsManager (https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4682944029), but the changes are an end-user improvement either way and I didn't see other significant problems.
re: https://github.com/bitcoin/bitcoin/pull/36861#issuecomment-6979485030
In commit "Configuration argument handling improvements." (
9611ea5584)Thanks, this looks right to me now.
DISALLOW_NEGATIONis used only for the limits where "no limit" and 0 mean different things, and the other options give the same error for-nofooand-foo=0.In commit "Configuration argument handling improvements." (
9611ea5584)Could this add a release note? Some configurations that start on master will fail to start after this change, for example
-timeout=0(which currently falls back to the default),-bantime=0,-limitclustersize=0, and-txconfirmtarget=0or above 1008 when a wallet is loaded. A short note listing the options that now reject out-of-range values would help anyone who hits one of the new errors after upgrading. The Ralph review suggested this too.re: https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4614637883
In commit "Configuration argument handling improvements." (
9611ea5584)+1 for doing the validation in ArgsManager. Besides the extra code, doing it at each call site means options in this PR now parse numbers differently. For example,
-limitclustercount=2.5is an error, but-limitclustersize=2.5is silently treated as 2, becauseGetIntArgignores anything after the leading digits, while theToIntegralcall used for-limitclustercountrejects it. The error messages also vary ("-bantime must be...", "limitclustersize must be...", "timeout must be a positive integer.").A getter like you describe could be something like:
That would make each call site one line and give every option the same parsing and error format. It would also fit #31260, which turns
GetArgdefault arguments into compile-time setting declarations and could handle min and max arguments the same way.In commit "Configuration argument handling improvements." (
9611ea5584)The commit message and PR description still say
-limitclustersize=0and-bantime=0remain valid, but this code now rejects 0 for both (-bantimetoo), so they could move to the list with-limitclustercountand-timeout.The same paragraph says 0 still means "disabled", but for several of these options 0 is the strictest setting rather than disabled:
-maxsendbuffer=0pauses sending whenever anything is queued,-maxtipage=0keeps the node in IBD, and-mempoolexpiry=0expires every transaction. It could just say that these options still accept 0. The Ralph review pointed this out too.In commit "Configuration argument handling improvements." (
9611ea5584)I think this comment has the effect backwards.
Expire()removes entries older than the cutoff, so a cutoff in the future would expire every transaction at the next check, not stop them from expiring. Maybe: "so a negative value would move the expiration cutoff into the future and expire every transaction." The Ralph review caught this.This may be true in Rust, but I don't think this is true in C++. Recall that the clang-format doesn't allow stuff like
if (auto r = args.GetArg("-foo", 0, 100); !r) return util::Error{...}; else if (*r) opts.foo = **r;Also, the alternative, where the result is assigned in the outer scope (before the if) is ugly and tedious, because the result will leak the scope after the if handling.
Finally, passing the min and max without named args will be confusing, when normally the second arg meant the default value. Also, having to redundantly pass the min/max when not needed seems redundant.
So the better option would be:
This would result in code like:
added release notes
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/45672897049/job/139412907538LLM reason (✨ experimental): CI failed the
doc_release_note_snippetslint check becausedoc/release-notes-36861.mddoes not include its PR reference.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Code review ACK
830af36b82. This makes numeric options that master silently accepts with nonsensical values (negative buffer sizes, ban times and confirmation targets,-timeout=0), or that crash the node (-limitclustercount=0), fail at startup with clear errors instead.Thanks for the release note and the clearer commit message! The remaining issues are small: the
-mempoolexpirybound still lets absurdly large values overflow when the mempool is loaded (https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4740978823), and the release note and commit message still describe 0 as "disabled" for options where it is the strictest setting (https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4740978085), and the release note could be much shorter (https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4741659479). I also still think these checks would be better in ArgsManager, and maflcko's options struct looks like a good way to do it (https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4740978473).re: https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4699000436
In commit "init: reject invalid numeric configuration values" (
830af36b82)Thanks! I think the note could be much shorter, though. Readers mainly need to know which options changed and roughly how, and
-helpalready gives most of the accepted ranges, so the maximum values and per-option explanations could go. For example:The one detail
-helpdoesn't cover is the new-txconfirmtargetlimit when a wallet is loaded, so it would be good to mention it in that option's help text too.In commit "init: reject invalid numeric configuration values" (
830af36b82)Many of the new upper limits are much larger than any value that makes sense, since they only stop the value from wrapping. This one allows about 4 GB per connection, against defaults of 1 MB and 5 MB, so a typo like an extra few zeros would still be accepted. Since this PR adds range checks anyway, it might be better to pick limits that catch user errors now, because tightening them later would break configurations this release accepts. With maflcko's options struct, they would fit naturally in
.minand.max.re: https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4684786604
Good points, and I agree the options struct is better. I was wrong that each call site would be one line, but your version still keeps each range check in one place with one error format, and returning
std::optional<util::Result<Int>>keeps the result scoped to theif. It would also fit #31260, whose setting declarations already take options as designated initializers ({.legacy = true}), so.minand.maxcould be added there the same way.One small thought: putting
util::Resulton the outside would make the error check the one callers can't skip, while withstd::optionaloutside, forgetting the inner check only shows up as an assert when someone passes a bad value.re: https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4682944850
In commit "init: reject invalid numeric configuration values" (
830af36b82)Thanks,
-limitclustersizeand-bantimeare in the right place now. But the commit message still says 0 "already meant 'disabled'" for the options that accept it, and the new release note says 0 "keeps its existing meaning of 'disabled' or 'unlimited'". For several of these options 0 is the strictest setting instead:-maxsendbuffer=0pauses sending whenever anything is queued,-maxtipage=0keeps the node in IBD, and-mempoolexpiry=0expires every transaction. This also contradicts the paragraph after it, which says that for these options 0 "means something very different from 'no limit'". The release note heading could just say:and the commit message could say "Zero remains valid for ...". Similarly, the release note's negation paragraph says
-nofooused to be "quietly turning the limit off", but since negation is read as 0, it set these limits to 0 rather than turning them off. The Ralph review flagged this too.In commit "init: reject invalid numeric configuration values" (
830af36b82)I think this bound is still too high.
LoadMempool()subtracts the expiry fromNodeClock::now(), which converts it toNodeClock::duration(nanoseconds with libstdc++), so an expiry above about 2.5 million hours (292 years) overflows there. These are absurd values, but this is the check meant to prevent that. I tried it on a debug build: with a transaction inmempool.dat,-mempoolexpiry=3000000passes this check and the node then crashes at startup on the overflow trap, while-mempoolexpiry=2000000loads fine. Taking the bound from the clock's duration fixed it:That makes the maximum 2562047 hours on Linux, so the release note and the tests that use the current maximum would need updating. The Ralph review found this too.
That's a good point, but I wouldn't worry too much about it. If reviewers really forget it, I presume LLMs are good at finding this, also there could be a clang-tidy check for this, if needed.
Wouldn't this cause the config values to be platform-dependent since std::chrono::system_clock::duration is ns with libstdc++, µs with libc++ on macOS, and 100 ns with MSVC, giving 2562047 / 2562047788 / 25620477880 hours respectively?
Right, I don't think we want platform-dependent caps here. This makes testing tedious for no benefit. All of those are absurd values anyway, so I think just using 1year is fine, or 5 years, or 2562047hours, if this needs to be "exact".
edit: For reference, other code is also just using an arbitrary upper limit:
re: https://github.com/bitcoin/bitcoin/pull/36861#discussion_r4758268700
Good catch, you're right:
NodeClockusessystem_clock's duration, so my suggestion would make the limit and the error message vary by platform. A fixed cap like maflcko suggests is better. Anything up to 2562047 hours avoids the overflow on all three platforms, and a smaller one like a few years would also catch typos, as in my other comment about right-sizing these limits.