Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35208. ReviewsSee the guideline 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. |
5297571 to
e201bdb
Compare
dergoegge
left a comment
There was a problem hiding this comment.
utACK e201bdb74b994ebb34999a38612401167b02c4a9
There was a problem hiding this comment.
reACK 9274f92
Prev:
ACK e201bdb74b994ebb34999a38612401167b02c4a9
Good catch of a boundary condition issue, fixed correctly.
Verified build and the test passing locally.
Reproduced the failure of the new test with the pre-change production code.
Note that the auto->int64_t change is not strictly needed, but it is correct, and it's safer to be explicit (the compiler resolves auto to signed int64_t (at least with c++/linux)).
Ran the test with these variations:
| variant | type | conditional present | test result |
|---|---|---|---|
| pre-change | auto | no | fail |
| uint64_t | no | fail | |
| int64_t | no | fail | |
| auto | yes | pass | |
| uint64_t | yes | fail | |
| post-change | int64_t | yes | pass |
hodlinator
left a comment
There was a problem hiding this comment.
Concept ACK e201bdb74b994ebb34999a38612401167b02c4a9
Good to tighten up the code!
e201bdb to
d84c8cc
Compare
d84c8cc to
f90578b
Compare
hodlinator
left a comment
There was a problem hiding this comment.
ACK f90578b977758ffa19b623747a8faa083dc61f57
It's unfortunate that we don't error out from the constructor and instead set the invalid value 0, but as already discussed (#35208 (comment)), doing so might be very disruptive to surrounding code. The new abort condition in HeadersSyncState::ValidateAndStoreHeadersCommitments() ensures we fail early during the sync with a clear error at least.
vasild
left a comment
There was a problem hiding this comment.
Concept ACK as of f90578b977
I think a simpler one-liner would suffice:
- m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period;
+ m_max_commitments = max_seconds_since_start > 0 ? 6 * max_seconds_since_start / m_params.commitment_period : 0;and I find it hard to fully grasp the implication of the other changes.
| const auto max_seconds_since_start{(Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}})) | ||
| + MAX_FUTURE_BLOCK_TIME}; | ||
| m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period; | ||
| const int64_t max_seconds_since_start{ | ||
| Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}}) + MAX_FUTURE_BLOCK_TIME}; |
There was a problem hiding this comment.
This:
-
Removes the unnecessary braces around
Ticks:(Ticks<...>(...))->Ticks<...>(...). -
Changes
autotoint64_t(before the variable ended aslong longand after - justlong). The commit message reads "Keep the elapsed value signed ...", however that implies that before this PR the value was changed from signed to unsigned. Correct me if I am wrong, but this is not the case? -
Reformats the entire expression.
All 3 seem unnecessary. I would revert the changes to this line. It is confusing why change those if not needed.
There was a problem hiding this comment.
The int64_t was made explicit to help us see the signed-to-unsigned change here.
The formatting and parentheses are easy to ignore; it's quite a simple expression.
There was a problem hiding this comment.
Reverted the formatting and parenthesis but kept the auto to int64_t change and explained it in the commit message.
There was a problem hiding this comment.
You're still changing the indent of + MAX_FUTURE_BLOCK_TIME - not sure what column you are aiming for? Better to change it to something sane or avoid touching that line.
Lines 41 to 42 in 9274f92
There was a problem hiding this comment.
I’d prefer not to keep iterating on whitespace here. This line is touched because the PR intentionally makes the signed elapsed value explicit for the security fix; the continuation indentation is incidental and does not change behavior. I’d rather keep this PR focused on the bug fix than force-push another version for formatting churn.
| if (m_max_commitments == 0) { | ||
| LogWarning("Initial headers sync aborted with peer=%d: local clock behind chain-start MTP (presync phase)", m_id); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
I do not fully understand why this addition is necessary. The commit message reads:
Abort presync upfront on the first header batch in that case with a
LogWarning, instead of waiting for the random commitment offset to reach a commitment slot.
But that does not quite answer the question "Why?" for me. Is it just an optimization?
This is not strictly related to the unsigned underflow fixed in the constructor of HeadersSyncState. The fix is legit even without this.
Further, is this causing an unintended change of behavior:
- before this PR if
m_max_commitmentsended up0(the current time is exactly 2h behind MTP) all calls toValidateAndProcessSingleHeader()might have returnedtrueand thusValidateAndStoreHeadersCommitments()might have returnedtrueas well. - after this PR if
m_max_commitmentsends up0, thenValidateAndStoreHeadersCommitments()will never returntrue.
There was a problem hiding this comment.
It is not required to fix, just to detect and log the inconsistency early.
Letting ValidateAndStoreHeadersCommitments() return true in that state would keep presync alive despite us already knowing no valid commitment can be reached under the current local time bound.
There was a problem hiding this comment.
What about if the job is done (we get out of presync because enough PoW was reached) even if m_max_commitments would have been triggered but was not because the check is not done for every block:
if (next_height % m_params.commitment_period == m_commit_offset) {
m_header_commitments.push_back(m_hasher(current.GetHash()) & 1);
if (m_header_commitments.size() > m_max_commitments) { // return false, abort
...
}
}
m_current_chain_work += GetBlockProof(current);Correct me if I am wrong. It looks to me that in master, m_header_commitments might be empty and m_max_commitments equal to 0 in which case the next time the first if above is entered, we would abort the operation. However that first if is not entered for every block and the current chain work grows for every block. So, it might happen that we successfully get out of presync after processing a few blocks even when m_header_commitments.size() == m_max_commitments == 0. And this PR changes that.
There was a problem hiding this comment.
I have reverted this to avoid diverting the change, we can do these in a follow-up instead, thanks for the comments.
There was a problem hiding this comment.
m_max_commitments == 0 rightfully is a valid value on master is an excellent point that I missed during earlier review. Credits to @vasild!
It highlights that attempting to set an invalid value to induce a later failure is brittle.
What is a valid number of header commitments if our system time is stuck at Jan 1st 1970? Surely it is not zero?
In kernel/chainparams.cpp we have:
consensus.nMinimumChainWork = uint256{"0000000000000000000000000000000000000001128750f82f4c366153a3a030"};
consensus.defaultAssumeValid = uint256{"00...177c478e094bfad51ba5ac"}; // 938343If we had the block height of 938343 as a constant instead of a comment we could fall back to using that to calculate roughly how many commitments we need from the chain_start height (when the system clock is unreliable). 938343 is the height we reach the minimum chainwork, unless some major re-org action has been happening.
With an upper bound of zero m_max_commitments, the commitment_period should eventually cause us to abort upon pushing the first one. But this seems very sloppy unless I'm misunderstanding something? I don't see a reason to rush-ACK + merge this in it's current state.
If we really want to keep the invalid value with later abort, maybe m_max_commitments could be made std::optional, or we could set it to some invalid value like ~0ULL and add back the new early abort.
There was a problem hiding this comment.
The goal of this PR is to fix a potential underflow, not fix every problem with headers sync commitment calculation algorithm.
There was a problem hiding this comment.
Please see my suggestions branch at master...hodlinator:bitcoin:pr/35208_suggestions
- It uses
nulloptto flag thatm_max_commitmentsis unusable instead of setting it to0which is a valid value for when the system clock is exactlyMAX_FUTURE_BLOCK_TIMEbehind the chain start, found by @vasild. - It re-adds the early abort in
HeadersSyncState::ValidateAndStoreHeadersCommitments()similar to your f90578b977758ffa19b623747a8faa083dc61f57 push which I previously acked. Aborting in this place should be minimally disruptive to surrounding code, and we are able to log a clear reason for why its happening. It also means we abort reliably, unlike with the current (9274f92) which may succeed, see inline comment about the commit message. - The current state of this PR manipulates the commitment period in the test to the unrealistic value of
1which makesHeadersSyncState::ValidateAndProcessSingleHeader()fail on the first header whereas in 99.9+% of real-world scenarios it would not. In my branch there is no need for manipulating the period. - The test case is added after the others in headers_sync_chainwork_tests.cpp, see other inline comment.
l0rinc
left a comment
There was a problem hiding this comment.
Thanks for the comments, I'll investigate them in more detail soon.
| const auto max_seconds_since_start{(Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}})) | ||
| + MAX_FUTURE_BLOCK_TIME}; | ||
| m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period; | ||
| const int64_t max_seconds_since_start{ | ||
| Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}}) + MAX_FUTURE_BLOCK_TIME}; |
There was a problem hiding this comment.
The int64_t was made explicit to help us see the signed-to-unsigned change here.
The formatting and parentheses are easy to ignore; it's quite a simple expression.
| if (m_max_commitments == 0) { | ||
| LogWarning("Initial headers sync aborted with peer=%d: local clock behind chain-start MTP (presync phase)", m_id); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
It is not required to fix, just to detect and log the inconsistency early.
Letting ValidateAndStoreHeadersCommitments() return true in that state would keep presync alive despite us already knowing no valid commitment can be reached under the current local time bound.
When the local clock sits more than `MAX_FUTURE_BLOCK_TIME` behind the chain-start MTP, the elapsed value used to derive `m_max_commitments` is negative. The later division by the unsigned commitment period converts that negative value to a large unsigned bound. With `commitment_period=1`, presync accepts the peer's first commitment slot and requests more, where it should abort. Pin that pre-fix behavior in a regression test that the subsequent fix will flip.
Make the elapsed-time value as `int64_t` explicit for clarity and assign an explicit zero commitment cap when the chain-start MTP is still too far in the future.
This avoids converting a negative elapsed value through the unsigned commitment-period arithmetic into a large `m_max_commitments` bound.
With a zero cap, the existing commitment-limit check aborts once the first commitment slot is reached.
Flip the regression test to expect that abort, and broaden the `headers_sync_state` fuzz target so it covers the same clock-skew case.
Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^[email protected]>
Co-authored-by: Hodlinator <[email protected]>
f90578b to
9274f92
Compare
vasild
left a comment
There was a problem hiding this comment.
ACK 9274f92
I was wondering how to exercise this on master without any changes to the non-test-code (like the early quit when max commitments is zero) and couldn't figure it out. Setting commitment period to 1 is cool - it forces the random commit offset to be 0 and so next_height % m_params.commitment_period == m_commit_offset becomes next_height % 1 == 0 which is always true.
|
utACK 9274f92 |
hodlinator
left a comment
There was a problem hiding this comment.
Approach NACK 9274f92
| const auto max_seconds_since_start{(Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}})) | ||
| + MAX_FUTURE_BLOCK_TIME}; | ||
| m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period; | ||
| const int64_t max_seconds_since_start{ | ||
| Ticks<std::chrono::seconds>(NodeClock::now() - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}}) + MAX_FUTURE_BLOCK_TIME}; |
There was a problem hiding this comment.
You're still changing the indent of + MAX_FUTURE_BLOCK_TIME - not sure what column you are aiming for? Better to change it to something sane or avoid touching that line.
Lines 41 to 42 in 9274f92
| if (m_max_commitments == 0) { | ||
| LogWarning("Initial headers sync aborted with peer=%d: local clock behind chain-start MTP (presync phase)", m_id); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
m_max_commitments == 0 rightfully is a valid value on master is an excellent point that I missed during earlier review. Credits to @vasild!
It highlights that attempting to set an invalid value to induce a later failure is brittle.
What is a valid number of header commitments if our system time is stuck at Jan 1st 1970? Surely it is not zero?
In kernel/chainparams.cpp we have:
consensus.nMinimumChainWork = uint256{"0000000000000000000000000000000000000001128750f82f4c366153a3a030"};
consensus.defaultAssumeValid = uint256{"00...177c478e094bfad51ba5ac"}; // 938343If we had the block height of 938343 as a constant instead of a comment we could fall back to using that to calculate roughly how many commitments we need from the chain_start height (when the system clock is unreliable). 938343 is the height we reach the minimum chainwork, unless some major re-org action has been happening.
With an upper bound of zero m_max_commitments, the commitment_period should eventually cause us to abort upon pushing the first one. But this seems very sloppy unless I'm misunderstanding something? I don't see a reason to rush-ACK + merge this in it's current state.
If we really want to keep the invalid value with later abort, maybe m_max_commitments could be made std::optional, or we could set it to some invalid value like ~0ULL and add back the new early abort.
| // when the chain a peer provides has too little work. | ||
| BOOST_FIXTURE_TEST_SUITE(headers_sync_chainwork_tests, HeadersGeneratorSetup) | ||
|
|
||
| BOOST_AUTO_TEST_CASE(future_chain_start_mtp_bounds_commitments) |
There was a problem hiding this comment.
Please put this test case after the pre-existing ones or in another file. There's a comment block right above which describes the test suites and the existing test cases, and splicing this in before they start makes things disorderly.
bitcoin/src/test/headers_sync_chainwork_tests.cpp
Lines 133 to 146 in 9274f92
Sorry for not catching this earlier.
There was a problem hiding this comment.
The commit message in 9274f92 states:
With a zero cap, the existing commitment-limit check aborts once the first commitment slot is reached.
It is not necessarily true that we will abort, in fact it is somewhat unlikely in this case:
- A node manages to complete IBD with a valid system clock. (Maybe the datadir is copied from another machine).
- It is then only intermittently online, now with an invalid clock.
- If we go offline for more than 144 blocks, then came back online, we would not meet the dynamic
minimum_chain_workthreshold inPeerManagerImpl::TryLowWorkHeadersSync()and therefore re-enterHeadersSyncStateeven though we are outside IBD. - It depends on whether the range of block heights we sync headers for in order to reach the minimum chainwork do overlap with the
commitment_period(currently 641 blocks on mainnet). - If there is no overlap, we never try to store a commitment, and the node will complete the
HeadersSyncStatesuccessfully.
| if (m_max_commitments == 0) { | ||
| LogWarning("Initial headers sync aborted with peer=%d: local clock behind chain-start MTP (presync phase)", m_id); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
Please see my suggestions branch at master...hodlinator:bitcoin:pr/35208_suggestions
- It uses
nulloptto flag thatm_max_commitmentsis unusable instead of setting it to0which is a valid value for when the system clock is exactlyMAX_FUTURE_BLOCK_TIMEbehind the chain start, found by @vasild. - It re-adds the early abort in
HeadersSyncState::ValidateAndStoreHeadersCommitments()similar to your f90578b977758ffa19b623747a8faa083dc61f57 push which I previously acked. Aborting in this place should be minimally disruptive to surrounding code, and we are able to log a clear reason for why its happening. It also means we abort reliably, unlike with the current (9274f92) which may succeed, see inline comment about the commit message. - The current state of this PR manipulates the commitment period in the test to the unrealistic value of
1which makesHeadersSyncState::ValidateAndProcessSingleHeader()fail on the first header whereas in 99.9+% of real-world scenarios it would not. In my branch there is no need for manipulating the period. - The test case is added after the others in headers_sync_chainwork_tests.cpp, see other inline comment.
|
@hodlinator has worked more with headers than I have, has stronger opinions about how it should be done, and already has a branch ready with the alternative. Could you please open a new PR that reflects the way you imagine it? I'll review it - seems cleaner than going back and forth here. |
…lock ff3e2e4 net: Trigger process abort when behind start block MTP (Hodlinator) 1883cec test: Characterize lagging-clock headers presync (Hodlinator) Pull request description: ### Problem Headers presync computes `m_max_commitments` from the elapsed time since the chain-start MTP plus `MAX_FUTURE_BLOCK_TIME`. When the local system clock is more than `MAX_FUTURE_BLOCK_TIME` behind the chain-start MTP, that elapsed value is negative, but it is used in arithmetic assigned to the unsigned commitment cap. This can turn the intended zero bound into a large cap, letting low-work headers presync continue instead of aborting when a reasonable commitment cap would have been exceeded. ### Fix Instead of allowing an invalid `HeadersSyncState` object to be created, emit an error and **abort the node process**. Typically, the node will detect that the system clock is set too far in the past when comparing it to the chain tip during chain state loading and shut down before we start syncing headers. So in practice this is very unlikely to make a difference (might be possible if the system clock jumps backwards after we loaded the chain state). #### Commits * Add functional and unit characterization tests [pinning the current behavior](#35260). * The fix, along with corresponding test changes. --- Replaces #35208 which was clamping `m_max_commitments` to zero and then letting the `HeadersSyncState` consume headers until the block height either reached the the next `commitment_period` point and aborted, or reached the minimum work threshold and succeeded (possible when having been offline for >144 blocks). ACKs for top commit: l0rinc: diff and code review ACK ff3e2e4 sedited: ACK ff3e2e4 mzumsande: Code Review ACK [ff3e2e4](ff3e2e4) Tree-SHA512: bdd82fd0609309aa4bea026db1b607ae856c53403ec01b2511fa2ccae9db4ff1bb9e39523b446583c09ae53823275b8a603050d9090b61fabb84fab35e458f28
Follow-up is in #35351
Problem
Headers presync computes
m_max_commitmentsfrom the elapsed time since the chain-start MTP plusMAX_FUTURE_BLOCK_TIME.When the local clock is more than
MAX_FUTURE_BLOCK_TIMEbehind the chain-start MTP, that elapsed value is negative, but it is used in arithmetic assigned to the unsigned commitment cap.This can turn the intended zero bound into a large cap, letting low-work headers presync continue instead of aborting when the commitment cap is reached.
Fix
Assign an explicit zero commitment cap when the chain-start MTP is still too far in the future for a locally acceptable extension to exist.
The branch is split into two bisect-friendly commits: a regression test pinning the current behavior, and the minimal fix, which flips those test assertions.
The
headers_sync_statefuzz target also now allows the same clock-skew case instead of always choosing a time at or after the chain-start MTP.