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 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:
CI seems to fail because the new test loop binds a |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
See #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. |
aa8bfe2 to
1ab3f14
Compare
There was a problem hiding this comment.
Concept ACK 1ab3f14 for parsing improvements here, but I'd recommend against increased use of the DISALLOW_NEGATION flag:
- If your option can't accept zero values, DISALLOW_NEGATION is only a partial fix and may allow zeroes to slip through because you are only guarding against them being set ib a single path. Better to check for valid values one place instead of multiple.
- It creates inconsistent UX where -option=0 and -nooption have different behaviors without a clear reason, when normal behavior is for them to behave the same.
DISALLOW_NEGATION was intended to used rarely and eventually removed (#22766 (comment)) and this PR seems to increase usage by a lot. The other changes here look very good though.
Edit: My comment above about DISALLOW_NEGATION was overbroad. The flag does make sense for limit options where "no limit" and 0 mean different things, see #36861 (review).
1ab3f14 to
7a5c9d8
Compare
7a5c9d8 to
0ad0c71
Compare
| if (auto value{args.GetIntArg("-maxtipage")}) { | ||
| // A negative max tip age would put the IBD cutoff in the future, so the | ||
| // node would never consider its tip recent and would stay in IBD. | ||
| if (*value < 0) { |
There was a problem hiding this comment.
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 */>
There was a problem hiding this comment.
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:
- Either we keep the saturation feature, and just use dumb parsing, or
- we do proper validation, but then inside the argparser, to avoid re-inventing the wheel for every call site.
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)?
There was a problem hiding this comment.
re: #36861 (comment)
In commit "Configuration argument handling improvements." (9611ea5)
we do proper validation, but then inside the argparser, to avoid re-inventing the wheel for every call site.
+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.5 is an error, but -limitclustersize=2.5 is silently treated as 2, because GetIntArg ignores anything after the leading digits, while the ToIntegral call used for -limitclustercount rejects 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:
//! Return nullopt if the option is not set, the value if it is an integer in
//! [min, max], or an error if it is not an integer or is out of range.
template <std::integral Int>
util::Result<std::optional<Int>> GetArg(const std::string& name, Int min, Int max) const;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 GetArg default arguments into compile-time setting declarations and could handle min and max arguments the same way.
There was a problem hiding this comment.
That would make each call site one line
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:
template <std::integral Int>
struct GetArgOptions {
Int min{std::numeric_limits<Int>::min()};
Int max{std::numeric_limits<Int>::max()};
};
template <std::integral Int>
std::optional<util::Result<Int>> GetArg(const std::string& name, GetArgOptions<Int> opts = {}) const;
This would result in code like:
if (const auto foo = args.GetArg<u16>("-foo", {.max = 100})) {
if (!*foo) return util::Error{util::ErrorString(*foo)};
opts.foo = **foo;
// foo is not leaked outside this scope, nice
}There was a problem hiding this comment.
re: #36861 (comment)
passing the min and max without named args will be confusing, when normally the second arg meant the default value
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 the if. It would also fit #31260, whose setting declarations already take options as designated initializers ({.legacy = true}), so .min and .max could be added there the same way.
One small thought: putting util::Result on the outside would make the error check the one callers can't skip, while with std::optional outside, forgetting the inner check only shows up as an assert when someone passes a bad value.
There was a problem hiding this comment.
forgetting the inner check only shows up as an assert when someone passes a bad value.
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.
|
Concept ACK There is a bit of overlap between this and #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 |
ryanofsky
left a comment
There was a problem hiding this comment.
re: #36861 (review)
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 -nofoo reads as "no limit" but 0 means something very different. Ideally -nofoo might 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:
- Make sense:
-dbbatchsize,-mempoolexpiry,-maxreceivebuffer,-maxsendbuffer,-maxtipage,-limitancestorcount,-limitdescendantcount,-datacarriersize. - Not needed because the PR already rejects 0, so
-nofoowould get that error:-bantime,-timeout,-peertimeout,-limitclustercount,-limitclustersize,-txconfirmtarget. - Not needed because 0 means what
-nofoosays:-bytespersigop, where 0 turns off the sigop adjustment.
0ad0c71 to
2d93cf5
Compare
|
Updated negation support: -bantime → Error: -bantime must be greater than 0 (got 0). Each is now validated in exactly one place, and -nofoo produces the identical message to -foo=0 |
2d93cf5 to
9611ea5
Compare
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK 9611ea5. 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 (#36861 (comment)), but the changes are an end-user improvement either way and I didn't see other significant problems.
| if (auto value{args.GetIntArg("-maxtipage")}) { | ||
| // A negative max tip age would put the IBD cutoff in the future, so the | ||
| // node would never consider its tip recent and would stay in IBD. | ||
| if (*value < 0) { |
There was a problem hiding this comment.
re: #36861 (comment)
In commit "Configuration argument handling improvements." (9611ea5)
we do proper validation, but then inside the argparser, to avoid re-inventing the wheel for every call site.
+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.5 is an error, but -limitclustersize=2.5 is silently treated as 2, because GetIntArg ignores anything after the leading digits, while the ToIntegral call used for -limitclustercount rejects 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:
//! Return nullopt if the option is not set, the value if it is an integer in
//! [min, max], or an error if it is not an integer or is out of range.
template <std::integral Int>
util::Result<std::optional<Int>> GetArg(const std::string& name, Int min, Int max) const;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 GetArg default arguments into compile-time setting declarations and could handle min and max arguments the same way.
bbf0fe6 to
9a342c9
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
a210aee to
0b33a8c
Compare
Several numeric options were read with GetArg<int>() 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<T>() on the raw string rather than with GetArg<T>(): 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: - -maxtipage: uint32_t seconds, range [0, UINT32_MAX]. A negative age placed the IBD cutoff in the future, so the node never treated its tip as recent. - -dbbatchsize: uint64_t bytes. A negative value wrapped to a huge batch size and disabled flushing, so a reindex could hold an unbounded batch. - -dbcrashratio: uint32_t, range [0, UINT32_MAX]. CoinsViewOptions:: simulate_crash_ratio is changed from int to uint32_t to match. - -limitclustercount: [1, MAX_CLUSTER_COUNT_LIMIT]. The separate upper-bound check in ApplyArgsManOptions is folded into this one, so an invalid value is reported once with one message. - -limitclustersize: [1, INT64_MAX / 1000] kB. Zero made every transaction exceed the cluster size and blocked all mempool admission. - -limitancestorcount, -limitdescendantcount: non-negative. - -mempoolexpiry: [0, std::chrono::seconds::max() / 3600] hours, and the value is stored as seconds directly. The bound is taken from seconds rather than hours because std::chrono::hours is not guaranteed to be 64-bit. - -datacarriersize: [0, UINT_MAX]; still unchecked when -datacarrier=0 turns the limit off. - -bytespersigop: [0, UINT_MAX]. A negative value wrapped and inflated the sigop-adjusted size of every transaction until all were non-standard. - -maxsendbuffer, -maxreceivebuffer: [0, UINT_MAX / 1000], since both are multiplied by 1000 into unsigned int members. - -bantime: greater than 0. Zero or negative made setban without an explicit duration create an already expired ban. - -timeout: positive and at most INT_MAX milliseconds. A non-positive value now fails instead of silently falling back to the default (as -peertimeout already did), and a value above INT_MAX used to narrow before it could be checked (e.g. 2^32 + 1 became 1). - -txconfirmtarget: [1, UINT_MAX] in parameter interaction, and additionally bounded by the fee estimator's maximum when a wallet is loaded. A target beyond the estimator's range made every transaction fall back to -fallbackfee. The help text now states the minimum. 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 0 (-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<void> (marked [[nodiscard]]) so its errors abort startup instead of being discarded. Finally, -help gains the =<n> 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.
0b33a8c to
830af36
Compare
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK 830af36. 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 -mempoolexpiry bound still lets absurdly large values overflow when the mempool is loaded (#36861 (comment)), and the release note and commit message still describe 0 as "disabled" for options where it is the strictest setting (#36861 (comment)), and the release note could be much shorter (#36861 (comment)). I also still think these checks would be better in ArgsManager, and maflcko's options struct looks like a good way to do it (#36861 (comment)).
| if (auto value{args.GetIntArg("-maxtipage")}) { | ||
| // A negative max tip age would put the IBD cutoff in the future, so the | ||
| // node would never consider its tip recent and would stay in IBD. | ||
| if (*value < 0) { |
There was a problem hiding this comment.
re: #36861 (comment)
passing the min and max without named args will be confusing, when normally the second arg meant the default value
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 the if. It would also fit #31260, whose setting declarations already take options as designated initializers ({.legacy = true}), so .min and .max could be added there the same way.
One small thought: putting util::Result on the outside would make the error check the one callers can't skip, while with std::optional outside, forgetting the inner check only shows up as an assert when someone passes a bad value.
| // a 64-bit representation (it is 32-bit on MSVC), which would make the | ||
| // bound itself wrap before it could be compared against. | ||
| constexpr int64_t SECONDS_PER_HOUR{3600}; | ||
| constexpr int64_t MAX_EXPIRY_HOURS{std::chrono::seconds::max().count() / SECONDS_PER_HOUR}; |
There was a problem hiding this comment.
In commit "init: reject invalid numeric configuration values" (830af36)
I think this bound is still too high. LoadMempool() subtracts the expiry from NodeClock::now(), which converts it to NodeClock::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 in mempool.dat, -mempoolexpiry=3000000 passes this check and the node then crashes at startup on the overflow trap, while -mempoolexpiry=2000000 loads fine. Taking the bound from the clock's duration fixed it:
// LoadMempool() subtracts the expiry from NodeClock::now(), which converts
// it to NodeClock::duration, so the bound has to come from that type.
constexpr int64_t MAX_EXPIRY_HOURS{std::chrono::duration_cast<std::chrono::seconds>(NodeClock::duration::max()).count() / SECONDS_PER_HOUR};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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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:
src/node/block_template_manager.cpp:234: if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
src/wallet/rpc/encrypt.cpp:64: // Clamp timeout to ~3 years to avoid overflow when computing the relock time
There was a problem hiding this comment.
re: #36861 (comment)
Wouldn't this cause the config values to be platform-dependent
Good catch, you're right: NodeClock uses system_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.
| // Both values are multiplied by 1000 and stored in unsigned int members, so a | ||
| // negative value would wrap to a huge buffer size, and a value large enough | ||
| // to overflow the multiplication would wrap too. | ||
| constexpr int64_t MAX_BUFFER_KB{std::numeric_limits<unsigned int>::max() / 1'000}; |
There was a problem hiding this comment.
In commit "init: reject invalid numeric configuration values" (830af36)
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 .min and .max.
| // a 64-bit representation (it is 32-bit on MSVC), which would make the | ||
| // bound itself wrap before it could be compared against. | ||
| constexpr int64_t SECONDS_PER_HOUR{3600}; | ||
| constexpr int64_t MAX_EXPIRY_HOURS{std::chrono::seconds::max().count() / SECONDS_PER_HOUR}; |
There was a problem hiding this comment.
re: #36861 (comment)
Wouldn't this cause the config values to be platform-dependent
Good catch, you're right: NodeClock uses system_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.

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.