Skip to content

cl/sentinel: honour the peer ban on inbound connections - #23606

Merged
lystopad merged 5 commits into
mainfrom
lystopad/sentinel-handshake-gate
Sep 7, 2026
Merged

lystopad merged 5 commits into
mainfrom
lystopad/sentinel-handshake-gate

Conversation

@lystopad

@lystopad lystopad commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Closes #23605.

The three-strike ban in peers.Pool was written and never read on the inbound path.
RecordHandshakeFailure installed the ban, but only ConnectWithPeer consulted it, and that
covers dials we initiate — not the connection events that arrive regardless. A banned peer
therefore got a fresh status handshake on every reconnect.

Measured on a gnosis archive node: 101 attempts against a single peer in two minutes, 13,827
handshake failures across 1,638 distinct peers in ninety minutes, and 460 dials refused by
libp2p's own dialer with rate limit exceeded.

Change

  • read BanStatus in the connection handler and close banned peers before handshaking
  • split the callback body into handleNewConnection, reporting whether the peer was kept, so
    the inbound path is reachable from a test

Retained-peer behaviour is untouched. Keeping a peer whose status exchange failed on a
transport error ("may still work for gossip") is deliberate and unchanged — only the rate at
which a banned peer is re-attempted changes.

Tests

cl/sentinel/ban_on_connection_test.go uses two real connected hosts, so closing the peer is
observable rather than a no-op against an absent connection. It covers entry through
onConnection with a real network.Conn, and drives #23605 end to end: three transport
failures reach the ban, then the next event closes the peer without validating again.

Mutation-verified rather than assumed: removing the ban read fails
TestBannedPeerIsClosedInsteadOfHandshaked; making onConnection bypass
handleNewConnection fails TestOnConnectionClosesABannedPeer.

History, for anyone reading the commit message

Earlier revisions also added a per-peer gate admitting one handshake at a time. @domiwei showed
it dropped replacement connections created during closePeer and lost their validation, which
was a regression against the existing fork-mismatch path, so the gate was removed — the ban
read is the whole fix. The squash commit message predates that removal and still describes the
gate, the dropped concurrent events and a burst test, none of which are in the merged code.

Follow-ups tracked separately: duplicate-handshake coalescing done correctly, the
ConnectWithPeer -> Host.Connect failure path that never records a handshake failure, and
enforcing the ban in Gater.InterceptSecured so a banned peer is dropped before the connection
is upgraded.

@lystopad lystopad added Networking Caplin Caplin: Consensus Layer, Beacon API labels Aug 26, 2026
@lystopad lystopad self-assigned this Aug 26, 2026
@yperbasis
yperbasis requested review from anacrolix and a balanced review from Copilot August 26, 2026 15:20
@lystopad
lystopad enabled auto-merge August 26, 2026 15:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@domiwei domiwei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for two related lifecycle issues.

  • cl/sentinel/discovery.go:562-568 checks BanStatus before gate admission, leaving a TOCTOU window. Event B can observe not-banned and pause; event A can complete the third failing handshake, install the ban, and release; then B can acquire and call ValidatePeer for the now-banned peer. Acquire first and check or recheck the ban inside the serialized section before handshaking.

  • The new tests exercise only handshakeGate; removing the new onConnection wiring leaves all of them green. The burst test also never releases its winner, so serial execution still admits exactly one. Because the issue and PR both say the observed production ordering is unverified, please add a deterministic production-sequence test covering onConnection -> BanStatus -> ValidatePeer -> RecordHandshakeFailure, three failures reaching the ban, release on all exits, and the next inbound event closing without another handshake.

The focused cl/sentinel suite passes normally and under -race, but it does not cover these sequences.

@lystopad

Copy link
Copy Markdown
Member Author

Both findings addressed in 69196c7.

TOCTOU — you are right, and the window is not where I would have guessed it. The gate is now taken first and the ban is read while it is held, so a ban installed by a handshake that completed while this event waited is visible before ValidatePeer runs.

Tests — your critique is correct and it is the second time I have made it: the four gate tests exercised handshakeGate in isolation, so deleting the onConnection wiring left them green, and the burst test never released its winner. I extracted the sequence into exchangeStatus so it is reachable from a test, and added four that drive the real path against a real peers.Pool:

  • TestExchangeStatusReachesTheBanAndThenRefusesThePeer — three transport failures reach the pool ban, then the next event closes the peer with ValidatePeer not called again, and the gate is released.
  • TestExchangeStatusRefusesAPeerBannedWhileTheEventWaited — a banned peer is closed without a handshake.
  • TestExchangeStatusAdmitsOneHandshakePerPeerAtATime — a second event for the same peer, raised from inside the in-flight handshake, is refused. Deterministic, no goroutines.
  • TestExchangeStatusDropsAForkMismatchWithoutRecordingAFailure — a completed handshake on the wrong fork is dropped and does not count toward the ban.

I verified they bite by mutation rather than assuming:

  • deleting the gate → TestExchangeStatusAdmitsOneHandshakePerPeerAtATime fails
  • deleting the ban check → the ban-sequence and banned-peer tests both fail

cl/sentinel passes normally and under -race; make lint clean.

One limit worth stating plainly: these tests pin that the ban is consulted and that a ban installed during an earlier handshake is honoured by the next event. They do not deterministically pin the ordering of acquire-versus-check, because that interleaving needs a hook inside the function to reproduce. If you want that guaranteed against future edits, I can add a test seam for it — say the word and I will.

@domiwei domiwei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The production TOCTOU is fixed correctly at 69196c7: gate admission now precedes BanStatus, so a same-peer event cannot carry a stale ban observation past the third failing handshake. One blocking regression-test gap remains.

The new sequence tests still pass if BanStatus is moved back above tryAcquire, which restores the exact bug, and they also pass if the onConnection -> exchangeStatus wiring is deleted. TestExchangeStatusRefusesAPeerBannedWhileTheEventWaited pre-bans the peer before the call; no event actually waits or crosses the check/admission boundary because busy admission is dropped.

Please add a deterministic production-sequence seam that distinguishes the ordering: prove gate ownership exists when ban status is observed, and enter through onConnection or a directly invoked production handler. The sequence should pause one validation, submit a same-peer event and an unrelated peer, complete the third failure, then assert the next inbound event closes without validation. This should fail if ban observation is moved before admission or if the onConnection wiring is removed.

The full cl/sentinel package passes normally and under -race; this request is specifically about pinning the production regression.

@lystopad

Copy link
Copy Markdown
Member Author

Fixed in f116f2d. You were right that the previous tests pinned nothing — they only observed outcomes, and the outcome is identical either way because admission is non-blocking, so TestExchangeStatusRefusesAPeerBannedWhileTheEventWaited never crossed the boundary it was named after.

The seam. exchangeStatus now takes the ban reader as a parameter (alongside the validate/closePeer/dropPeer values it already took); production passes s.peers.BanStatus. The test passes an observer that checks handshakeGate.holds(pid) on every read, so gate ownership at the moment of observation is asserted directly rather than inferred.

The entry point. onConnection is now just go s.handleNewConnection(peerId, validate), and handleNewConnection is driven directly by two tests against a real in-memory libp2p host (libp2p.New(libp2p.NoListenAddrs), no network).

The sequence is the one you described: a first handshake for peer A pauses mid-flight holding the slot; a second same-peer event is refused without validating; an unrelated peer B proceeds anyway; A resumes; two more failures reach the three-strike ban; the next A event closes it without a handshake; every exit leaves inFlight() at zero.

Mutation results, both fast:

  • ban read moved back above tryAcquire → fails in 0.00s: Should be zero, but was 5 — the ban must be read while this peer's handshake slot is held, not before admission
  • exchangeStatus call deleted from handleNewConnection → fails in 0.01s

One detail worth flagging, since I hit it: my first version asserted inside the handshake goroutine with require, and the mutation was detected by a 600-second timeout rather than a failure — FailNow calls Goexit, so the channel the main goroutine waited on never closed. The observer now counts violations and asserts on the test goroutine, which is why the failure above is immediate and named. A regression test that reports by hanging would have been worse than no test in CI.

cl/sentinel passes normally and under -race; make lint clean.

@domiwei

domiwei commented Aug 27, 2026

Copy link
Copy Markdown
Member

I took another pass at the current head (f116f2d). The per-peer gate itself looks sound: admission precedes the ban read, same-peer handshakes are suppressed, unrelated peers can proceed, and the deferred release covers the normal exit paths.

One blocking test gap remains:

  • The regression suite still stops before the public connection-event boundary. The added tests call handshakeGate, exchangeStatus, or handleNewConnection directly; none triggers ConnectedF -> onConnection. Removing the onConnection -> handleNewConnection wiring leaves all added tests green. Also, TestHandleNewConnectionRefusesABannedPeerWithoutHandshaking uses a host with no live connection for that peer, so ClosePeer is a successful no-op and the test does not observe a real disconnect.

Because both #23605 and this PR say that the production event ordering was not reproduced, please add a deterministic test entering through onConnection or a registered ConnectedF, with observable validation and connection-close effects. It should fail on the fixed-point behavior for the intended reason. If that production sequence cannot be reproduced yet, I would change Closes #23605 to Related to #23605 and keep the issue open for instrumentation/live verification.

Two lower-priority cleanup items:

  • The new comments in discovery.go:563-565,604-612, handshake_gate.go:25-28, and the detailed incident/test comments violate the repository comment policy: they are multi-sentence, scenario/call-site-heavy, and one includes the Gnosis incident measurements. Please reduce production comments to the invariant and keep incident/test history in the PR description.
  • TestHandshakeSequenceSerializesPerPeerAndReachesTheBan closes resume only after several require calls. A regression that reaches FailNow before that close leaves the validation goroutine blocked. Please register unconditional cleanup/unblocking before those assertions.

Validation on this head: go test ./cl/sentinel -count=1, the focused tests with -count=20, the focused tests with -race, and git diff --check all pass. GitHub CI is green.

One adjacent, non-blocking risk: a pure initial ConnectWithPeer -> Host.Connect failure still does not call RecordHandshakeFailure, so that path cannot install the three-strike ban. This is distinct from the incident log path (ValidatePeer -> Host.NewStream), so I would track it separately unless the intended scope is all outbound dial failures.

@lystopad

Copy link
Copy Markdown
Member Author

Thanks — two of the four are fixed in 46e880f.

Comment policy. Trimmed discovery.go and handshake_gate.go to the invariant, and dropped the gnosis incident measurements from the gate test docstring. That was our own policy and I broke it; the history belongs in the PR description.

Paused-handshake deadlock. resume was closed only after several assertions, so a regression reaching FailNow first left the validation goroutine parked and the failure surfaced as a timeout rather than a message. The release is now registered with t.Cleanup, which runs after Goexit. Verified by forcing an early failure: reports in 0.67s instead of hitting the timeout.

cl/sentinel passes normally and under -race; make lint clean.

On the blocking item — you are right on both counts: nothing enters through onConnection, so deleting that wiring leaves the suite green, and TestHandleNewConnectionRefusesABannedPeerWithoutHandshaking uses a host with no live connection to that peer, so the close is an unobserved no-op.

I would rather fix it than downgrade the issue link. My plan: two real in-memory hosts, actually connected, enter through onConnection with the real network.Conn, and assert connectedness drops to NotConnected — a genuine observable disconnect. For the unbanned half I need one small production change to make validation observable: a validatePeer func(peer.ID) (bool, error) field on Sentinel, set in the constructor to the handshaker call. It also lets me drop the validate parameter from handleNewConnection, so the signature gets simpler rather than more complex.

If you would prefer to avoid that field, say so and I will take your alternative instead — Related to #23605, issue kept open for live instrumentation.

Your last point — a pure ConnectWithPeer -> Host.Connect failure never calls RecordHandshakeFailure, so that path cannot reach the three-strike ban. Agreed, and distinct from the ValidatePeer -> Host.NewStream path this PR addresses. I will file it separately rather than widen the scope here.

@domiwei domiwei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ban check is now correctly inside the per-peer gate. Requesting changes for one introduced reconnection regression, detailed inline: a replacement connection can lose its only status-validation event while the previous connection is being rejected.

The focused handshake/gate/handler tests pass normally and with -race. A deterministic scratch regression test reproduces the replacement-connection failure in all three runs; a control using the same test with only gate admission/drop/release removed passes all three runs. That control isolates the cause; removing serialization is not the proposed fix.

Non-blocking test cleanup:

  • handshake_sequence_test.go:63: replace waitForInFlight with a direct assertion. Receiving entered already establishes acquisition, and resume keeps the handshake paused. The helper and time import can go.
  • handshake_sequence_test.go:84: the validatedA mutex/wrapper is unnecessary; entered and wg.Wait() already order its accesses. These two simplifications remove about 13 lines.
  • testSentinel() creates two positive-TTL cache cleaner goroutines per call through peers.NewPool(nil). The pinned expirable LRU has no working close API, so the four new fixture uses retain eight goroutines per suite repetition. A bounded fixture arrangement would help; a broader Pool/LRU lifecycle redesign should be a separate follow-up.

Only the reconnection regression is blocking this review.

Comment thread cl/sentinel/discovery.go Outdated
// exchangeStatus runs one status handshake for peerId and reports whether the peer was kept.
// The ban must be read while the slot is held: a handshake completing meanwhile may install it.
func (s *Sentinel) exchangeStatus(peerId peer.ID, banned func(peer.ID) bool, validate func() (bool, error), closePeer, dropPeer func(peer.ID)) bool {
if !s.handshakeGate.tryAcquire(peerId) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve status validation for replacement connections during rejection

Dropping every same-peer event while the slot is held assumes the in-flight verdict also handles any replacement connection. That is not true across closePeer/dropPeer:

  1. Connection A's status is rejected (valid == false, err == nil). Its handler still owns the gate while closing the peer.
  2. libp2p ClosePeer takes a snapshot of current connections and closes those connections.
  3. The same peer establishes connection B after that snapshot, before A's handler returns and releases the gate.
  4. B's connection callback reaches this branch and is dropped. A's close did not include B, and releasing the gate does not schedule another validation, so B remains connected without a status check.

The previous implementation ran a separate validation for B. This is therefore an introduced regression in the existing fork-mismatch rejection behavior.

I reproduced this with two libp2p mocknet hosts, real connection notifications, and the production handleNewConnection handler. The test substitutes a rejecting validator and pauses a wrapped Network.ClosePeer after the underlying close but before returning; it reconnects the peer and waits for B's handler to finish before releasing A. All three runs report validation calls=1, live replacement connections=1. This deliberately stretches a valid scheduling window; it is not a live-network reproduction.

Please distinguish replacement connections from duplicate events, or preserve sufficient pending work to validate/close a replacement after rejection, while retaining the one-active-handshake invariant. Add a deterministic regression test that observes the replacement connection's actual validation/closure.

…ound

onConnection handles every connection event on its own goroutine, so a burst of
events for one peer started a handshake for each. The three-strike ban could not
intervene: all of them completed before any raised the failure count to its
threshold. It also only consulted the ban in ConnectWithPeer, which covers dials we
initiate and not the events that arrive anyway.

A gnosis archive node reached 101 attempts against a single peer in two minutes, and
13,827 handshake failures across 1,638 peers in ninety minutes, until libp2p's own
dialer began refusing with "rate limit exceeded".

Banned peers are now closed before the handshake, and a per-peer gate admits one
attempt at a time so the ban threshold is reachable. Concurrent events for the same
peer are dropped rather than queued: the peer is about to be judged by the attempt
already running.

Closes #23605
Checking BanStatus before admission left a window: an event could observe the peer as not
banned, a concurrent handshake could complete the third failure and install the ban, and
the first event could then acquire the gate and handshake a peer that is already banned.

Extracts the status exchange into exchangeStatus so the gate is taken first and the ban is
read while it is held, and so the sequence is reachable from a test. The connection handler
keeps its subnet and peer-limit checks.

The previous tests only exercised handshakeGate in isolation, leaving the wiring unpinned:
deleting it kept them green. The new tests drive the whole sequence against a real peers
pool - three transport failures reaching the ban, the next event closing the peer without
another handshake, a concurrent event for the same peer refused, and a fork mismatch
dropped without counting toward the ban - and each exit path leaving the gate released.
The previous tests passed with BanStatus moved back above tryAcquire, so they did not pin
the fix at all. They only observed outcomes, and the outcome is the same either way when
admission is non-blocking.

Injects the ban reader into exchangeStatus, so a test can assert the peer's handshake slot
is already held at the moment the ban is read - which is false if the read moves back above
admission. Splits onConnection's body into handleNewConnection so the handler itself is
reachable without a live handshaker.

The sequence test pauses one handshake mid-flight, submits a second event for the same peer
and one for an unrelated peer, releases, drives two more failures to reach the pool ban, and
asserts the next event closes the peer without handshaking it. Violations are counted rather
than asserted inside the handshake goroutine: a failed require there would Goexit and turn a
regression into a ten-minute timeout instead of a named failure.

Verified both regressions fail fast: reading the ban before admission, and deleting the
handleNewConnection wiring.
…n failure

Cuts the production comments to the invariant and drops the incident measurements from the
test docstring, per the repository comment policy.

The sequence test closed its resume channel only after several assertions, so a regression
reaching FailNow first left the paused handshake goroutine parked and the failure surfaced as
a timeout. Registers the release as cleanup, which runs after Goexit: a forced early failure
now reports in under a second.
The connection callback never read the ban list. Handshake failures were recorded and the
three-strike ban was installed, but nothing consulted it on the inbound path, so a banned
peer was handshaked again on every reconnect - 101 handshakes against one peer in two
minutes on a gnosis node.

Reads the ban before handshaking, and closes the peer instead. Splits the callback body into
handleNewConnection so the sequence is reachable from a test.

Drops the per-peer handshake gate from earlier revisions of this change. It was an
optimisation against duplicate concurrent handshakes, not the fix, and it introduced a
regression: a replacement connection arriving while the previous one was being closed had
its only status validation dropped and stayed connected unvalidated. Reducing duplicate
handshakes is worth doing separately, with event coalescing so no connection loses its
validation.
@lystopad
lystopad force-pushed the lystopad/sentinel-handshake-gate branch from 46e880f to 6242da5 Compare September 7, 2026 09:34
@lystopad

lystopad commented Sep 7, 2026

Copy link
Copy Markdown
Member Author

You found a real regression, and chasing it led me to conclude the gate should not be in this PR at all. Rebased on current main and reduced to the actual fix in 6242da5.

Why I dropped the gate. I went back to the original onConnection on main and it never consults BanStatus anywhere. Failures were recorded by RecordHandshakeFailure and the three-strike ban was installed — and then nothing ever read it on the inbound path. That is what produced 101 handshakes against one peer: not concurrency, but a ban that was written and never checked. The gate was an optimisation against duplicate concurrent handshakes layered on top, and it is what introduced your replacement-connection hole. Your control experiment said the same thing: removing gate admission makes the failure go away.

So the fix is now just the ban read, plus splitting the callback body into handleNewConnection so it is testable. Gate, pending-slot bookkeeping and the sequence tests are gone — net 412 deletions against 167 additions.

Your regression is structurally gone. With no serialization, a replacement connection gets its own validation exactly as it did before this PR. Nothing is dropped, so there is no lost-validation window to reason about.

Tests use two real hosts with a live connection, so the close is observable rather than a no-op on an absent connection:

  • TestOnConnectionClosesABannedPeer — enters through onConnection with a real network.Conn and waits for connectedness to actually drop.
  • TestBannedPeerIsClosedInsteadOfHandshaked — the validator fails the test if it is reached.
  • TestRepeatedHandshakeFailuresStopBeingHandshaked — three transport failures reach the ban, then the next event closes the peer with the validator not called again. This is the storm from cl/sentinel: unreachable peers are re-dialled until libp2p's own rate limiter refuses, despite the three-strike ban #23605 end to end.
  • TestUnbannedPeerIsHandshakedAndKept — the normal path still validates and keeps the peer.

Mutation-verified rather than assumed:

  • removing the ban read → TestBannedPeerIsClosedInsteadOfHandshaked fails
  • making onConnection bypass handleNewConnection → TestOnConnectionClosesABannedPeer fails after its 5s disconnect timeout

cl/sentinel passes normally and under -race; make lint clean. Your non-blocking test cleanups are moot now — waitForInFlight, the validatedA mutex and the multi-fixture peers.NewPool goroutine accumulation all went with the deleted files. The remaining fixture builds one pool per test with a real host.

Follow-ups I will file separately rather than widen this: duplicate-handshake coalescing done properly; the ConnectWithPeer -> Host.Connect failure path that never records a failure; and enforcing the ban in Gater.InterceptSecured, which would reject a banned peer before the connection is upgraded rather than after.

@domiwei domiwei left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The blocking reconnection regression is resolved in 6242da5. Removing the per-peer gate preserves validation of replacement connections, while the early ban check applies the existing ban policy to connection events.

I re-reviewed the cumulative diff and found no new blocking correctness issue. The original deterministic reconnect test, adapted only to the new fixture signature, passes all three runs: two validations and zero remaining connections. The full cl/sentinel package passes normally and with -race; the race run also includes that reconnect test. Removing only the new ban guard in a temporary test overlay makes the ban tests fail as expected.

Approving with two non-blocking comments:

  • Please update the PR title and description. They still describe the removed per-peer gate, dropped concurrent events, and 64-acquire burst test. The current change is inbound ban enforcement; the latest commit message already describes that narrower scope accurately.
  • The test fixture still creates two permanent TTL-cache cleanup goroutines per peers.NewPool call, leaving eight workers per suite repetition. A bounded fixture arrangement would help. A broader shared Pool/LRU lifecycle redesign can remain a separate follow-up.

The reconnect test uses mocknet connections and an injected status verdict; it verifies the reported ordering regression, not the original live-network attempt-rate measurements.

@lystopad
lystopad added this pull request to the merge queue Sep 7, 2026
Merged via the queue into main with commit 3c3a21f Sep 7, 2026
139 checks passed
@lystopad
lystopad deleted the lystopad/sentinel-handshake-gate branch September 7, 2026 10:53
@lystopad lystopad changed the title cl/sentinel: one status handshake per peer, and honour the ban on inbound connections cl/sentinel: honour the peer ban on inbound connections Sep 7, 2026
@lystopad

lystopad commented Sep 7, 2026

Copy link
Copy Markdown
Member Author

Thanks — both non-blocking comments are handled.

Title and description. Updated to describe the merged change: inbound ban enforcement plus
the handleNewConnection split, with the gate, the dropped concurrent events and the burst test
removed. I added a short section noting that the squash commit message predates the gate's
removal and still describes it, since the commit message itself can no longer be corrected.

Test fixture. #23847. One shared pool for the whole package instead of one per test. Safe
because each test creates its own hosts, so peer IDs are disjoint and ban state cannot carry
across, and nothing in cl/sentinel reaches Pool.Request, the only method that uses the host.

Your count was exactly right. A probe counting surviving cleanup goroutines gives eight per
suite repetition before and a flat two after, at -count=1, 2 and 3.
TestFixtureReusesOnePeerPool pins it, and removing the ban read still fails
TestBannedPeerIsClosedInsteadOfHandshaked, so sharing has not weakened the tests.

The broader lifecycle point is #23848 as you suggested. One detail that makes it tractable:
expirable's Get already checks ExpiresAt, so the unstoppable goroutine only reclaims
memory and TTL read semantics do not depend on it. All nine production call sites are
process-level singletons, so nothing leaks at runtime today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Caplin Caplin: Consensus Layer, Beacon API Networking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cl/sentinel: unreachable peers are re-dialled until libp2p's own rate limiter refuses, despite the three-strike ban

3 participants