Repository navigation
build(deps): Bump github.com/cosmos/iavl from 0.15.0-rc5 to 0.15.0 - #17
Closed
dependabot[bot] wants to merge 1 commit into
Closed
dependabot[bot] wants to merge 1 commit into
dependabot[bot] wants to merge 1 commit into
Conversation
Bumps [github.com/cosmos/iavl](https://github.com/cosmos/iavl) from 0.15.0-rc5 to 0.15.0. - [Release notes](https://github.com/cosmos/iavl/releases) - [Changelog](https://github.com/cosmos/iavl/blob/master/CHANGELOG.md) - [Commits](cosmos/iavl@v0.15.0-rc5...v0.15.0) Signed-off-by: dependabot[bot] <[email protected]>
Contributor
Author
|
Dependabot tried to add |
Contributor
Author
|
The following labels could not be found: |
Contributor
Author
|
OK, I won't notify you again about this release, but will get in touch when a new version is available. If you change your mind, just re-open this PR and I'll resolve any conflicts on it. |
dependabot
Bot
deleted the
dependabot/go_modules/github.com/cosmos/iavl-0.15.0
branch
December 1, 2020 18:04
iammadab
added a commit
to iammadab/tenderdash
that referenced
this pull request
Aug 3, 2021
shumkov
added a commit
that referenced
this pull request
Aug 17, 2026
…flood DoS, phase 1) (#17) * docs(consensus): spec for vote-flood DoS hardening Records the reviewed analysis and plan for the consensus vote-flood resource-exhaustion DoS (distinct from the Commit-extension crash, which is fixed on branch fix/commit-extension-panic). §1 mechanics are verified and reliable: an unprivileged peer floods a validator with structurally-valid, cryptographically-invalid precommits, forcing ~2.7-2.9 ms of BLS verification each, a WAL write, and two error logs, with no disconnect. §4 records the proposed mitigation layers (L1-L6) and the blocking defect independent review found in each first draft — none may be implemented as first written. §7 is the revised recommendation; §9 the no-code allowlist-only mitigation; §10 a related latent HeightVoteSet issue. No code fix yet — this branch holds the plan; the fix will be implemented and validated here. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): bound invalid-vote log amplification under peer flood (L4) An unprivileged peer flooding invalid votes made a validator emit two Error-level log lines per message (measured 46,752 entries for 23,376 bad votes) — log volume scaled with the attacker's message rate. Downgrade to Debug only the validation errors an unprivileged peer can trigger at will, classified by error TYPE (not by whether a peer sent the message): - addVoteLoggingMw: a not-added vote logs at Debug. The notable cases (non-deterministic and conflicting signatures) are still logged at Error by addVoteErrorMw. - loggingMiddleware: uses isPeerFloodableError (matches ErrVoteInvalidBlockSignature, ErrVoteInvalidSignature, ErrVoteUnexpectedStep via errors.Is). Anything not positively matched — including internal faults such as ErrPrivValidatorNotSet surfaced while handling a peer message — stays at Error, so this never hides a real problem. Classifying by PeerID alone was too broad (it would hide internal faults that surface during peer-message handling); this uses explicit error categories instead, which fails safe toward surfacing. Part of docs/CONSENSUS_VOTE_FLOOD_SPEC.md (L4). No control-flow change; logging level only. Tests (red→green): internal/consensus/log_amplification_test.go — isPeerFloodableError matches floodable errors (including the production ErrInvalidVoteSignature wrapping) and rejects internal faults; loggingMiddleware logs a floodable error at Debug but an internal fault at Error even for a peer message. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): cap vote-extension count to stop verification amplification (L5) Each threshold-recoverable vote-extension costs one BLS signature verification (~2.7 ms). Nothing bounded the count, so an unprivileged peer could pack ~10^4 extensions into a single ~1 MB commit or precommit and force that many verifications on the single consensus goroutine — the core of the vote-flood DoS. Add MaxVoteExtensions (32) enforced in MakeQuorumSigns, the shared chokepoint of VerifyCommit (commits) and VerifyExtensionSign (precommit votes). Over-cap messages are rejected before any per-extension work. Placed on the verification path, not Commit.ValidateBasic, for the same reason as the unknown-type fix: a rejection on the WAL-decode path would abort replay and re-brick an already-attacked node. Cap rationale: Dash Platform's ExtendVote returns at most withdrawal_transactions_per_block_limit threshold-recoverable extensions (currently 4, a bounded SizedQuery limit, verified in rs-drive-abci). 32 gives 8x headroom for a future protocol increase while bounding attacker-forced work to ~32 verifications (~86 ms) per message instead of ~25 s. If that limit is ever raised above 32, raise this constant in the same release. Part of docs/CONSENSUS_VOTE_FLOOD_SPEC.md (L5). Note: this changes what the p2p layer accepts; a P2PProtocol bump decision is deferred to the maintainer per RELEASES.md (legitimate traffic is unaffected, so practical interop impact is nil). Tests (red→green verified): types/vote_extension_count_test.go pins the count boundary at MakeQuorumSigns and via VerifyCommit; both fail with the check removed. Green across types, privval, light, consensus. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): per-peer vote-channel rate limit (L1) An unprivileged peer can flood the vote channel and force one BLS verification per message (~940/s in the reported attack). Add a per-peer token-bucket rate limit on the vote channel (votes and commits): messages over a peer's budget are dropped in the reactor before reaching signature verification, bounding the CPU one connection can force. - New config consensus.peer-vote-rate-limit (float, messages/s/peer; 0 disables). Default 100: an honest validator gossips ~10-20 vote-channel messages/s, so the limit only bites a flood. - Burst is a small 2x the rate (voteRateBurstMultiplier), not the shared limiter's 10x default: vote-channel messages are individually expensive, so a large burst would let one peer front-load seconds of BLS work in an instant. NewRateLimitWithBurst floors the burst at 1 when the limit is positive, so a small rate cannot truncate to a zero-token bucket that silently drops everything. Config validation rejects NaN/Inf/negative rates. - drop=true (non-blocking): an over-limit peer cannot block the shared channel goroutine, and honest peers on other limiters are unaffected. - Applied in Reactor.processMsgCh via allowVoteChannelMessage; other channels and the disabled (0) case always pass; limiter errors fail open. Scope and limits (honest): this bounds a SINGLE connection. Node identities are free and unbound, so a determined attacker dilutes it across connections/IPs — tighten p2p connection limits alongside. The real fix is the validator-set vote gate (docs/MASTERNODE_VOTE_GATING_SPEC.md). Commits ride this channel and are covered too; a separate typed disconnect on invalid-commit-signature is planned. Tests (red->green): vote_rate_limit_test.go (per-peer drop, isolation, other channels unlimited, disabled=0); ratelimit_test.go (explicit/floored burst); config_test.go (rate validation). Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): wire max-incoming-connection-attempts into the router (connection limit) getRouterConfig set IncomingConnectionWindow but never passed MaxIncomingConnectionAttempts, so the config value was silently ignored and the router always fell back to its internal default (100, router.go:99-100). An operator tightening consensus/p2p connection limits to bound a flood got no effect. Pass conf.P2P.MaxIncomingConnectionAttempts through to RouterOptions so the per-IP incoming-attempt cap is operator-controllable. This is the connection- level lever that bounds how many connections/IPs an attacker can use to dilute the per-peer vote-channel rate limit (L1) and to spam commits (which cannot be sender-gated). Default value unchanged (100); tightening it is now an operator config action. Test: node_test.go asserts a non-default config value flows into RouterOptions (fails before the fix: the field was 0). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs: implementer brief for remaining vote-flood hardening Captures the precise, non-obvious decisions for the three remaining items (typed commit-signature disconnect, data-channel proposal rate limit, L6 block-sig-before-extension) so a focused implementer session can execute them without re-deriving the classification/scope nuances from the specs. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): disconnect peers sending cryptographically invalid commits Commits ride ConsensusVoteChannel and trigger threshold-signature verification, but cannot be sender-gated: non-validators legitimately relay them for catch-up (shouldCommitBeGossipedForCatchup). A commit whose THRESHOLD SIGNATURE fails to verify is, however, unambiguous misbehaviour — a commit is stored only after a successful VerifyCommit (state_data.go), so no honest node ever relays a cryptographically invalid one. Evict the peer that sends one. Precise, safe classification (the whole risk here is a false positive that partitions the network): - New typed error types.ErrInvalidCommitSignature, emitted ONLY wrapping the final quorumSigns.Verify failure in ValidatorSet.VerifyCommit. Wrong block ID (rejected earlier), wrong quorum hash, extension errors, and local finalization faults keep their distinct, untyped errors. - The disconnect fires only when errors.As(err, *ErrInvalidCommitSignature) succeeds, and never for a WAL-replayed message (FromReplay gate — replay re-dispatches with the original PeerID). - Propagation is non-blocking: the state machine queues a peerErrorMsg (dropped if the buffer is full) and a new reactor peerErrorRoutine drains it and emits a Fatal p2p.PeerError. The consensus goroutine never blocks. Composes with L1 (rate-limits commit spam) and the connection-attempt cap; together they bound commit spam without gating honest relayers. Tests (both pin the classification; they fail if any non-signature error were treated as a signature error): - types/validator_set_test.go: a bad threshold signature is typed; wrong block ID / wrong quorum hash are not. - internal/consensus/state_try_add_commit_test.go: only the typed error queues a fatal eviction; wrong-block / wrong-quorum / local-fault / replay-sourced do not; nil queue tolerated; full queue drops the report. Green across types and internal/consensus. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): per-peer data-channel rate limit for proposal flood The data channel has the same re-verifiable BLS flood as the vote channel: a junk proposal fails signature verification (state_proposaler.go) but never sets rs.Proposal, so there is no dedup and every copy re-verifies. An unprivileged peer (need not be the proposer) can force N verifications with N junk proposals. L1/L5/the vote gate do not touch this channel. Add a per-peer token-bucket limit on the data channel, but cost-WEIGHTED rather than a flat message rate — because the channel also carries block parts, which are legitimately gossiped to non-validators for catch-up and must not be throttled: - proposals cost proposalTokenCost (5): each forces an un-deduplicated BLS verification; - block parts and POL bit arrays cost 1: cheap part-set bookkeeping. New config consensus.peer-data-rate-limit (default 500, 0 disables): ~500 block-part messages/s of headroom while capping proposals near the vote channel's verification budget (~100/s). drop=true, same non-blocking semantics as L1. Burst (dataRateBurstFor) is floored at proposalTokenCost: rate.Limiter.AllowN permanently rejects any request larger than the burst, so a burst below a proposal's cost would make the node silently never admit a proposal and stall consensus. Design note: this deviates from a simpler flat generous limit; weighting was chosen so block-part gossip keeps full headroom while proposals are still bounded (a flat limit high enough for parts would leave proposals effectively unbounded). Tests (run, green): internal/consensus/data_rate_limit_test.go — proposal flood dropped past budget; block-part gossip unaffected; burst admits the most expensive message; disabled at 0. Green across internal/consensus, config, p2p/client. Co-Authored-By: Claude Opus 4.8 <[email protected]> * perf(consensus): verify block signature before vote-extension signatures (L6) In the precommit add-vote path, extension signatures were verified before the block signature. Extension verification costs one BLS pairing per threshold-recoverable extension and does not short-circuit, so a peer that cannot produce a single valid signature could still force the whole set of pairings (bounded to 32 by L5, but still 32x a single check). Add Vote.VerifyBlockAndExtensionSigns, which authenticates the block signature first and verifies extension signatures only on success. A forged precommit is then rejected for the cost of one pairing. The set of votes admitted is identical to before (a MatchesFullVerifyAdmission test pins this) and the ABCI VerifyVoteExtension call remains gated exactly as before — only the work done before rejecting a forged vote changes. Marginal once the validator-set vote gate lands (only validators can send precommits then), but cheap, localized, and correct. Tests (green): types/vote_test.go — short-circuits on bad block signature; still rejects a valid-block/bad-extension vote; accepts a valid vote; admission matches unconditional verification. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): gate votes to validator-set senders (the vote-flood fix) This is the root-cause fix for the vote-flood DoS. The mitigations (rate limit, extension cap, log/commit hardening) bound a flood; this changes WHO can send one at all. An unprivileged peer with a freely-generated node key could make a validator perform BLS verification simply by sending votes: nothing checked that the SENDER was a consensus participant (the isValidator gate checks the receiver, and a peer's ProTxHash is self-reported, not bound to its handshake key). Drop votes whose authenticated node ID (envelope.From, bound to the p2p handshake public key) is not in the current or previous validator set. Only validators legitimately send or relay votes — a node gossips a vote to a peer only when that peer is a validator (shouldVoteBeGossiped) — so this rejects nothing honest while restricting the expensive vote path to actual quorum members. In Dash terms the attacker must now own an evonode (collateral-backed, identifiable, PoSe-bannable) rather than any host with a node key. Design (see docs/MASTERNODE_VOTE_GATING_SPEC.md §10): - Set = current Validators UNION LastValidators node IDs. The union covers the quorum-rotation boundary, where late votes for the previous height arrive from the previous quorum. The binding is already in-process (validator.NodeAddress.NodeID, from the ABCI ValidatorUpdate URI) — no Dash Core poll, no new dependency, no registry. - Drop-only, no disconnect (avoids evicting a peer during a rotation window). - Fails OPEN on ANY incomplete identity coverage: if any member of either set lacks a node ID, the gate is disabled entirely rather than risk dropping that validator's votes. The gate is either fully informed or fully off, so a false positive (dropping an honest vote and partitioning the network) is impossible. Current Dash Platform never produces mixed sets (platformNodeID is mandatory for every validator), but generic/non-Dash and transitional states are handled safely. Only VOTES are gated. Commits are not (non-validators relay them for catch-up); they are handled by the per-peer rate limit and the invalid-signature disconnect. Tests: internal/consensus/vote_sender_gate_test.go (red->green) — current and previous-set validators allowed; non-validator dropped; fail-open with no node IDs, at genesis (nil LastValidators), and on a MIXED set (any node-ID-less member) in either set. The full internal/consensus suite passes unchanged. Recommended before release: testnet / e2e validation across a quorum rotation. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs: bring vote-flood + gating specs up to date with the implementation The vote-flood spec still said "sent back for rework, none may be implemented" — stale now that every layer plus the root-cause validator-set vote gate is built, tested, and reviewed. Update its status to IMPLEMENTED with a table mapping each shipped layer to its commit, and note what was deliberately deferred. Add MASTERNODE_VOTE_GATING_SPEC.md to this branch (the gate's design doc, which belongs with the gate code) and mark it IMPLEMENTED. Both specs now reflect the final validator-scoped design and carry the testnet-validation caveat. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): harden vote/commit signature verification against extension amplification Block-signature short-circuit before vote-extension signatures; typed ErrVoteExtensionCountMismatch so a count/version mismatch is not treated as evictable forgery; vote-extension cap enforced on the verification path only, never on signing. Red-green tests included. Co-Authored-By: Claude Opus 4.8 <[email protected]> * wip(consensus): vote-gate fail-open metric + processMsgCh log hygiene SEC-006 gate observability (VoteGateFailOpen metric, transition-only Warn) and SEC-008 envelope-dump log downgrade. Gate observability is superseded by the DoS-throttle rework (gate is being removed); log hygiene is kept. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): DoS defense plan, per-message analysis, and review trail Reviewed lean throttle plan (Phase 1) + parallelization follow-up (Phase 2), the per-message DoS matrix and findings, open-questions log, and the Codex review trail. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound peer signature verification Add a shared node-wide 300-operation-per-second token bucket with a bounded burst sized for both current verification passes of the largest accepted precommit. Acquire permits immediately before the block signature check, then acquire extension permits only after the block signature succeeds. Apply the shared budget to peer Votes and Commits while bypassing local and replayed messages. Budget exhaustion is surfaced as a non-punitive, flood-safe drop and cannot be classified as forged commit evidence. Test would have caught this in CI: ✖ before fix (budget APIs and config were absent), ✔ after (staged-permit, affected-package, lint, and build checks pass). Co-Authored-By: OpenAI Codex <[email protected]> * test(consensus): add DoS attack-surface audit POCs Empirical grounding for the DoS defense plan. Each test documents a concrete attack surface and passes by demonstrating current behavior: - HeightVoteSet unbounded round allocation: a peer mints two new rounds per 32 bytes of forged proTxHash, rejected without BLS work (memory cost without CPU cost). - Per-node-identity rate-limit reset: the per-peer limiter is keyed on the p2p node ID, so a fresh Ed25519 keypair resets the budget; the cap is per-keypair, not per-attacker. - Burst-clamp permanent drop: a cost-weighted rate limit silently and permanently drops any single message heavier than the token bucket's burst, halting the chain if the app returns more extensions than burst. - Commit verification cost vs extension count: measures victim CPU per attacker byte, the denomination the rate-limit default must use. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): refine verification budget handling Preserve verification-budget exhaustion as local overload on the Vote path, count live remote Vote and Commit budget drops, and keep wrapped budget errors out of peer-eviction handling. Test would have caught this in CI: ✖ before fix (Vote budget denial was wrapped as an invalid signature and metric wiring was absent), ✔ after (the regression and metric classification tests pass). Co-Authored-By: OpenAI Codex <[email protected]> * docs(consensus): piece 2 spec - verification fairness Design for the required fairness invariant: per-peer lanes drained by deficit round robin, so an attacker flood cannot starve honest consensus traffic out of the shared verification budget added in piece 1. Reviewed by four independent lenses before implementation. Notable outcomes: - Prices every message type on the peer queue. The queue carries Proposal and BlockPart as well as Vote and Commit, so pricing only the latter two left the scheduler's own bounds unprovable and left proposal verification as an unbudgeted pivot that a handful of peers can use to saturate the verifier. - Drops the escrow/lease design in favour of a whole-message affordability check on the state goroutine. The token bucket cannot express partial settlement, a lease cannot ride a message that is also a WAL record, and the reservation leaked across the scheduler handoff where a single leak halts the peer path. - Records what the piece cannot deliver: honest share is bounded by connection slots, not by scheduling, so raising it is folded into piece 3b. - Names the existing full-queue error path that would turn a routine lane overflow into peer eviction, which bounded lanes make reachable. Also surfaces two new Phase 1 items: the unprotected evidence channel, and whether removing the double verification must move out of Phase 2. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(consensus): fix starvation flaw in piece 2 budget admission Adversarial re-review of the admission mechanism found it broken for the very property the piece exists to guarantee. Gating dispatch on "can the bucket cover this message, else drop" is biased against expensive messages absolutely rather than proportionally. The bucket is a level, not a queue, and a dropped message costs microseconds, so a saturated supply of cheap messages pins the level below what an expensive one needs and it is never admitted. Round robin cannot compensate: it allocates turns while the check allocates tokens, and a turn granted then discarded is a turn wasted. The mechanism is fair only when all offered costs are equal, which is precisely not the adversarial case. Replaced with bounded, context-aware waiting. Because every draw is serialized on one goroutine, blocking for tokens is itself the reservation, which buys what the rejected lease design was reaching for without any lease. The staged draws also wait rather than fail, so whole-message atomicity holds by construction instead of by argument. Also restates the fairness invariant over admitted verification rather than dispatch. As worded it stayed true while messages were discarded, so it could not fail even as the chain stopped making progress; the test now asserts honest completion latency, and a regression test pins the rejected behaviour. Records three implementation traps found in the process: cancelling a token reservation refunds nothing once its deadline passes, the limiter's own wait consults real time and would defeat the test clock, and equal burst and worst-case cost admit a maximum message only on a fully idle node. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(consensus): charge the per-peer vote budget in verification work Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §8 commit 1 (the §5a work plus the §7 clock-seam prerequisite). The per-peer vote-channel limiter charged one token per message, so a peer could buy a precommit carrying 32 vote extensions — up to 66 BLS signature verifications — for the same price as a prevote. The budget therefore bounded message count, not the CPU it was introduced to bound. Price every message a peer can put on a consensus channel in verification work, per the spec's §5a table: prevote 1; nil-block precommit 1; non-nil precommit with n extensions 2*(1+n) (two verification passes), capped at 66; commit with n extensions 1+n, capped at 33; proposal 1; block part 1. The cost is derived from the message's declared contents alone, so it is charged before conversion, validation or verification. A message declaring more extensions than any legitimate participant produces is refused a price and dropped locally — never reported as a peer error, so neither a protocol revision nor a bug in this model can evict honest peers. Floor the per-peer burst at that worst-case cost. This fixes a live hazard: rate.Limiter rejects any request larger than the burst no matter how long it waits, so with burst = 2 * limit any peer-vote-rate-limit below 33 would make a fully-extended precommit permanently inadmissible — every validator's precommits silently dropped and no block ever committed. Raise the peer-vote-rate-limit default to 600, now denominated in verification work rather than messages. A Dash-realistic precommit (four extensions) costs 10, so this admits ~60/s from one peer. Provisional pending the load test. verificationBudgetBurst now derives from the same constant instead of repeating the expression, so the global burst and the message cost cannot drift apart. Prerequisite for the spec's §7 test plan: the p2p rate limiter read time.Now() directly, so refill behaviour could only be inferred from sleeps. It now meters through an injectable clockwork.Clock (the abstraction already used by the blocksync synchronizer and the p2p client), defaulting to the real clock — production behaviour is unchanged. Out of scope, deliberately: the §5b affordability peek and minimum-rate validation, and the §5c lanes/DRR. Red → green: * TestAllowVoteChannelMessage_ChargesVerificationCost — ✖ "1201 is not greater than 12000" (prevotes and maximum-cost precommits were admitted in equal numbers) → ✔ * TestAllowVoteChannelMessage_CostSharesOneBudget — ✖ → ✔ * TestAllowVoteChannelMessage_UnpriceableMessageDroppedLocally — ✖ → ✔ * TestVoteRateBurstAdmitsMostExpensiveMessage — ✖ against the old burst = 2 * limit formula ("1 is not greater than or equal to 66") → ✔ * TestRateLimit_RefillsOnInjectedClock — ✖ (undefined: WithRateLimitClock) against the previous ratelimit.go → ✔ Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): make whole-message verification affordable by waiting Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §8 commit 2 (§5b, plus the §5d placement argument). Lanes/DRR (§5c) stay out of scope. Piece 1 charges the node-wide verification budget in stages while a message is verified: a remote precommit draws 1 then n, twice over. A later stage can therefore be denied after earlier stages already paid for a BLS pairing and the ABCI VerifyVoteExtension round-trip, wasting the work and dropping a valid vote. Before a peer Vote or Commit is dispatched, wait until the budget can cover that message's own cost — from the piece-1 cost model, never the protocol maximum. Since every draw is made by the single consensus goroutine, blocking for tokens is itself the reservation: nothing can take them while we wait, so the staged charges that follow cannot fail (I3, now true by construction rather than by argument). Waiting, not peeking-and-dropping. An earlier draft gated dispatch on "does the bucket cover W right now, else drop". That is broken: the bucket is a level, not a queue, and a drop costs microseconds, so demand-saturated cheap messages pin the level below what an expensive honest message needs and it is never admitted. The new cost-bias test pins exactly that failure. The wait is bounded and selects on ctx.Done(). A non-ctx-aware wait would deadlock shutdown (readQueueMessages defer -> fanIn -> stop() -> receiveRoutine never returns); an unbounded one would stall consensus behind an over-subscribed budget. Both give up non-punitively — never a PeerError — since local overload says nothing about the sender. maxWait is 2*C_max/R (440ms at defaults), a safety net rather than a working limit: refilling the most expensive message from an empty bucket takes C_max/R = 220ms, so that is the real bound on how long the goroutine is held. It is implemented as the outermost msg middleware rather than by widening types.VerificationBudget or plumbing a ctx into types/: the state goroutine's dispatch boundary is the only place that has both the ctx and the whole message, and withMiddleware makes the last-appended middleware outermost, so a shed message costs zero WAL writes — asserted, not assumed. rate.Limiter.WaitN is avoided (it reads the wall clock internally and would defeat the clock seam), as is ReserveN+Cancel (CancelAt refunds nothing once timeToAct has passed, silently double-charging). The wait is built from TokensAt plus the injected clockwork clock, which the budget now meters against. Burst is no longer a coincidence. verificationBudgetBurst was exactly C_max, so a maximum-cost message was admissible only on a completely idle node. It is now 2*C_max, and B > C_max is a compile-time assertion: MaxVoteExtensions invites being raised, and at 64 a burst left behind would make that message permanently inadmissible. Validate a minimum verification-rate-limit. 0.5 was legal (only NaN/Inf/negative were checked) and would mean minute-scale stalls; the limit must now be 0 (disabled) or at least the cost of the most expensive single message, so the bucket refills it within a second. Red -> green (peek-and-drop counterfactual: waitFor replaced by "TokensAt >= cost, else drop"): * TestVerificationBudgetWaitAdmitsExpensiveMessageUnderCheapFlood — ✖ "expensive message starved in round 0: cheap traffic must delay it, not exclude it" → ✔ * TestVerificationBudgetWaitAdmitsMessageAfterRefill — ✖ "a message that is not affordable yet must wait for the refill, not be dropped" → ✔ * TestVerificationBudgetWaitCompletesStagedPrecommitDraws — ✖ "expected []int{1,4,1,4}, actual []int(nil)" → ✔ Red -> green (piece-1 baseline: middleware wait disabled): * TestVerificationBudgetWaitCompletesStagedPrecommitDraws — ✖ "expected []int{1,4,1,4}, actual []int{1,4}", with the node logging "rejected peer message: verification budget exhausted" mid-verification → ✔ * Whole new API absent → ✖ "undefined: withVerificationBudgetClock", "inner.maxWait undefined", "undefined: config.MinVerificationRateLimit" Also covered: ctx cancellation returns promptly and does not hang shutdown of receiveRoutine; a deadline drop writes nothing to the WAL, queues no peer error and verifies nothing, while the same message admitted does write one WAL record; every budget charge is made on the receiveRoutine goroutine; a commit charges [1, n] and its admitted cost covers it; B > C_max; minimum-rate validation. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): decouple the per-peer vote burst from the configured rate Review follow-ups on the piece-2 cost model (5056628, 2064219), per docs/CONSENSUS_DOS_PIECE2_SPEC.md §5a and §7. Burst is no longer a multiple of the rate. voteRateBurstFor returned max(2*limit, C_max), so the new default of 600 work/s gave every peer a 1200-unit bucket: ~1200 cost-1 messages or 18 maximum-cost precommits front-loaded in a single instant, and 64 connection slots exposed 76800 units — nearly four times the 20000-message consensus queue they share. Since a peer starts with a full bucket, that is what one reconnect buys. The burst is now an independent work allowance sized from honest demand (voteRateBurstCatchUp = 200: ten vote-channel messages a second at the ten work units a four-extension Dash precommit costs, i.e. about two seconds of an honest peer's heaviest gossip), with C_max kept as a floor so the most expensive protocol-legal message can never become permanently inadmissible. All 64 slots now front-load 12800 units, below the queue. peer-vote-rate-limit keeps its default of 600. Message pricing is exhaustive. peerMessageCost priced any unrecognised message at the floor of 1, so a message type added later would be admitted at an invented price with nothing to notice it. Every type in the consensus wire union is now priced explicitly and an unknown type is refused a price — dropped locally, never a PeerError, since a version skew says nothing about the sender. The doc comment now states the contract narrowly: the cost covers the direct staged signature verifications only, not threshold recovery/interpolation over a vote set (types/vote_set.go) and not the ABCI VerifyVoteExtension round-trip. The clock seam covers the waiting path. WithRateLimitClock only reached AllowN, access timestamps and GC; with drop=false the limiter still called WaitN(ctx, 1), which reads the wall clock internally (so an injected clock could not release it) and discarded the caller's nTokens entirely, silently dropping cost weighting on that path. It is replaced by a ReserveN-based wait metered against the injected clock, charging the full weight and refunding the reservation when the caller's context is cancelled. The prevote row of the cost table is now documented as the conditional it is: charging 1 regardless of declared extensions is safe only because types.Vote.ValidateBasic rejects extensions on anything but a precommit for a real block, and MsgFromProto runs it before dispatch. A test pins that dependency so deleting the validation cannot silently turn a prevote into a 33x undercharge. Also drops release-status narration from the peer-vote-rate-limit default comment; the provisional status of 600 lives in the spec. Red → green: * TestVoteRateBurstDoesNotScaleWithLimit — ✖ "expected 1200, actual 12000" at a tenfold rate, and 120 at a tenth → ✔ * TestVoteRateBurstBoundsFreshPeerAggregate — ✖ "76800 is not less than 20000" → ✔ * TestPeerMessageCost_RefusesUnrecognisedMessage — ✖ "An error is expected but got nil" (priced at the floor) → ✔ * TestRateLimitWaitPathChargesNTokens (was TestRateLimitWaitPathIgnoresNTokens, which pinned the defect) — ✖ "9999.015583 is not less than 5100" for a 5000-token message → ✔ * TestRateLimit_WaitPathRefillsOnInjectedClock — ✖ hung until the 2-minute test timeout: the wait never registered on the injected clock → ✔ * TestPrevoteWithExtensionsRejectedBeforeVerification — passes as a guard; verified non-tautological by deleting the "unexpected vote extensions" check in types/vote.go, which turns it ✖ "An error is expected but got nil" Verified: go build ./... clean, go vet clean, config, internal/p2p/client and internal/consensus green with -race. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): record the chosen per-peer vote burst The spec asked for a burst sized independently of the rate but never named a value, leaving it out of sync with the implementation. Record 200 work units and the reasoning: it covers roughly two seconds of an honest peer's heaviest gossip while keeping the aggregate a fresh peer set can front-load below the shared queue's capacity. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(consensus): fold piece 2 review findings back into the plan The fairness review surfaced two things the plan did not account for. The evidence channel is undefended and was owned by no piece: two signature verifications per message, no rate limit at all, and de-duplication by hash so that flipping one signature byte forces the work to be redone. Added as a Phase 1 item. Validator connection hardening also has to raise how many honest peers we connect to, not only stop the ones we have from being evicted. We dial twelve of sixty-eight slots and the rest can be taken from a single host with free identities, so the honest share is capped no matter how fairly the work is scheduled. Records the fairness form decision and its arithmetic, and adds an open item on whether removing the double verification has to move out of Phase 2, since honest demand alone already exceeds the budget in normal operation. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(p2p): reserve connection slots for current-quorum validators Validator connection protection was attached to the dial action rather than to the validator's identity, which left it absent exactly where it matters. `routerDashDialer.ConnectAsync` sets `MutableScore = PeerScorePersistent` but never the `Persistent` flag, so `Score()` caps at `MaxInt16-1`, the value is ephemeral, and every peer error decrements it. Worse, `ConnectAsync` is only reached for validators we dial: `filterAddresses` skips any validator that is already connected, and DIP-6 is a directed overlay, so the neighbours at `(i-2^k) mod n` only ever connect inwards — as does every neighbour after a restart, since the remote retries at 250ms and wins the race against our startup. Those validators sit at score 0, and `findUpgradeCandidate` needs only a strictly lower score, so one `PeerError` (score -1) let any fresh score-0 Sybil evict them. `updateConnections()` runs only on validator-set updates, so the evicted validator was not redialed until the next quorum rotation. Introduce a reserved connection slot, keyed on the node ID the handshake authenticates. `PeerManager.SetProtectedPeers` replaces the reserved set; `configurePeer` derives `peerInfo.Protected` from it, so an inbound connection from a never-before-seen quorum member is covered on arrival. A reserved slot ranks as persistent, so it cannot be eroded by error scoring or dial failures, cannot be selected for eviction to make room for another peer, and wins an upgrade when the node is full. `ValidatorConnExecutor` publishes the set for the quorum members it must stay connected to, whichever side dials. Two findings from spec review are folded in: - `router.routeChannel` disconnected *any* erroring peer whenever `len(connected) >= MaxConnected`, ignoring rank — and a flood is precisely what puts a node at its ceiling, so this alone would have kept the one-error eviction alive. `ShouldDisconnectOnError` now spares peers holding a reserved slot from pressure-driven shedding; fatal errors still disconnect them. - Reservations are granted only to node IDs bound to the address the chain published (inline in the validator address, or from the TCP resolver's secret-connection handshake). `resolveNodeID` also answers from the address book, which peer exchange lets any peer write, so an attacker could otherwise PEX-inject `attackerNodeID@validatorIP:port` and be handed the validator's slot. Address-book answers remain good enough to dial. Design, verification of each claim against the code, and the rejected alternatives (per-/24 conn-tracker keys, raising MaxOutgoingConnections, a numeric inbound reservation) are in docs/CONSENSUS_DOS_PIECE3B_SPEC.md. Tests would have caught this in CI: TestProtectedValidatorSurvivesFloodErrorsAndRestart score -100 -> persistent TestProtectedValidatorDisplacesFloodOnInbound refused -> admitted TestProtectedPeersReplacedOnQuorumChange 0 -> persistent TestReservedSlotIsNotShedUnderConnectionPressure shed -> kept Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(dash): reserve slots for the inbound half of the DIP-6 overlay Reserving slots only for the validators this node dials protects half of its quorum neighbourhood. DIP-6 is a directed overlay: the member at sorted index i dials (i+2^k)%n, so the members that dial it are the ones at (i-2^k)%n — a different set, which `selectValidators` never returns and which is therefore only ever known through the connection it opens. Those are exactly the slots a connection flood takes, and the honest share stays pinned to the outbound half. Add `SelectInboundValidators` as the inverse of `SelectValidators`: same sorted list, same offsets, walked backwards. The two share one implementation parameterised by direction, so they cannot drift apart, and the index arithmetic moves from float to integer because Go's % keeps the sign of the dividend and a negative offset needs the result brought back into range. `ValidatorConnExecutor` now reserves the union of both halves. A failure to compute the inbound half keeps the outbound reservations rather than dropping everything. The union is small and bounded: at most 2*floor(log2(n-1)) identities, 12 for a 100-member LLMQ and fewer where the halves overlap (at n=64, -32 is +32 mod 64, giving 11), and at most n-1 <= 3 below the DIP-6 minimum, which is what keeps 4-node testnets safe. Guaranteed honest connection slots under a flood go from 0 — every neighbour was removable with one peer error before the previous commit — to the whole 12-member DIP-6 neighbourhood, plus the 6 outbound slots an attacker can only reach by poisoning the address book: >= 18 of 68. Test would have caught this in CI: the inverse property test (j in forward(i) <=> i in inverse(j)) fails on every quorum size at or above the DIP-6 minimum when the inbound selection is anything but the true inverse. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): harden slot reservations after review Independent security and liveness review of the previous two commits found three ways the mechanism could be turned against the node it protects. Reservations no longer run node ID resolution at all; they use only the node ID the chain published with the validator address. Resolution consults the address book first, and peer exchange lets any connected peer put an arbitrary node ID at an arbitrary address there, so an attacker could advertise `attackerID@validatorIP:port` and have the resolver name its own identity for a real validator — either claiming the slot or, since the answer was then treated as unauthenticated, stripping the reservation from that validator on demand. A per-target kill switch on the mitigation, for one PEX message. Resolution is also far too expensive to run here: `WithValidatorSetUpdate` publishes the full validator set on every committed block, so `updateConnections` runs per block, not per rotation. Resolving the inbound half would have added a blocking 1s dial plus 1s handshake per unresolved member, per block, on the event-bus subscriber goroutine — for peers this node never dials. A subscriber that falls behind is evicted by the pubsub server and never resubscribes, which would have frozen the reserved set on a rotated-out quorum. A rejected reservation set is now dropped instead of leaving the previous one in force, which was stale protection of exactly the kind keeping reservations out of the peer store is meant to prevent. A malformed node ID no longer costs the rest of the set its reservations, and the size ceiling now counts the configured persistent peers that hold a slot for the same reason. Score changes are no longer recorded for a peer holding a reservation. They were invisible while it lasted but still accumulated, so an attacker that could not shed a reserved validator could bank errors against it and have it drop to the bottom of the ranking the moment its quorum rotated out. Also: remove `HasMaxPeerCapacity`, dead since the previous commit replaced its only caller. Review found one test that could not fail — the hard-ceiling test passed with protection removed, because the flood peers it left at score -1 could be out-ranked by anyone. It now restores them to a clean rank first, so only a reservation can win the admission. New tests cover the rejected-set, malformed and self ID paths, and the seed-node incoming-connection timer. One review suggestion was rejected: keeping a connection to a member that moved to the half of the overlay that dials us. Holding an outbound connection to a peer DIP-6 says should dial us contradicts the overlay's semantics, and the existing executor tests encode that. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): serve peer messages in per-peer lanes by deficit round robin Every peer shared one arrival-ordered queue of 20 000 slots, drained by a single reader, so service was proportional to how much a peer sent. A peer flooding cheap messages could hold up the vote the node needed to make progress, however honest its sender. Give each peer a lane of its own and serve the lanes by deficit round robin. Plain round robin is not enough here: message cost varies by two orders of magnitude, so a rotation blind to cost lets a lane of maximum-cost precommits take 66 times an honest lane's work per turn. A per-lane deficit counter with a one-unit quantum makes the rotation fair in verification work instead of in message count, and bounds what other lanes can complete ahead of a head of cost W at lanes x max(quantum, W). Also restores the invariant that internal progress is independent of the peer path. The affordability wait introduced in 206421997 ran on the state goroutine because there was no scheduler to put it on; that goroutine also serves this node's own messages and the timeout ticker, so a saturated budget delayed timeouts by up to C_max/R against a one-second vote timeout. The wait now runs on the scheduler, and the state-goroutine check remains only for messages that did not come through the scheduler. Handing over one peer message at a time is what makes reading the budget on another goroutine sound, since a message's charges are made while it is verified. And fixes the non-punitive invariant. chanQueue.send reported a full queue as an error, which reactor.go turned into a p2p.PeerError and peerManager.Errored turned into eviction. With 20 000 shared slots that path was near-dead; with bounded lanes it becomes routine, and the peer that reaches capacity at full load is the honest one. Shedding and a cancelled context now both return nil. Lane capacity is 512 messages: a whole 21 MB proposal block arrives as 337 parts, and a peer's instantaneous vote allowance is 200 work units of the cheapest messages. The lanes are bounded in aggregate at the size of the queue they replace, so per-peer scheduling does not raise the memory a flood can pin; once several dozen lanes are busy that aggregate binds first, and a single peer can no longer hold a whole block's parts. Lanes are retired when a peer disconnects and reclaimed after 60 seconds idle, so an attacker cycling through free node identities cannot grow the rotation without bound. Overflow drops the oldest message, never the arriving one: consensus messages are only valid for the height and round they were made in, so dropping the newest would spend a peer's turns on guaranteed-stale messages and mute it for rounds with no attacker involved. Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §5c, restores I6 and fixes I4. Test evidence, per invariant: - I4: TestSheddingAPeerMessageNeverReportsThePeer/lane_overflow fails against a send that returns "msg queue is full" ("the peer was reported for a message this node chose to shed"), passes here. - DRR: TestPeerLanesBoundWorkAheadOfAHead/"cheap head, expensive flood" fails against cost-blind round robin ("528" is not less than or equal to "8"), passes here. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(consensus): prove peer scheduling holds end to end The lane unit tests exercise the rotation directly. These drive real messages through the reactor, the scheduler, the write-ahead log and the consensus state machine, so they assert what the invariants are actually about rather than what the scheduler reports. - An honest peer's vote completes VERIFICATION — enters the vote set, not merely gets dispatched — while 67 attacker lanes hold the verification budget at zero with forged commits, within the round timeout it belongs to. Both a cheap head and the heaviest precommit Dash validators produce, since only the expensive one distinguishes a scheduler that waits for budget from one that passes over what it cannot afford right now. - Shedding a peer message, whether at the lane or at the peer's own rate limiter, reaches neither the reactor's error path nor the write-ahead log nor the vote set, while a genuinely malformed message from another peer is still reported — so the test cannot pass by never reaching the scheduler. - This node's own messages and its round timeouts are served while the peer path is blocked on the verification budget. - A peer message the dispatcher finds no handler for still lets the scheduler serve the peer's next message. - The node stops while the scheduler is parked on the verification budget. - A peer going down retires its lane, and reconnecting starts it over. Timing is asserted against a fake clock advanced at exactly the rate the verification budget refills, so what the tests measure is the delay the budget imposes and nothing else. Work that rides inside a dispatch without being charged — threshold recovery and the vote-extension round-trip — is invisible to that measurement; bounding it is what the piece's load test is for. Red-before-green evidence: - The honest-vote test fails against a budget check that peeks instead of waiting ("the honest peer's vote was never verified while other peers flooded"), which is the design docs/CONSENSUS_DOS_PIECE2_SPEC.md §5b rejects, and passes here. - The dispatcher-drop test fails when the finished-message report is made from the middleware instead of the dispatch loop, because a message that reaches no middleware then never reports and the scheduler stops serving peers for good. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): fold peer-scheduling review findings back in Findings from independent liveness, concurrency and spec-conformance reviews of the per-peer scheduler. Correctness and robustness: - A budget that loses the ability to defer a message is now a compile error. Both callers ask for it through a type assertion and quietly stop deferring when it fails, which would give up whole-message atomicity with every test still green. - The reactor retires a lane outside its own lock, so the lane lock stays a leaf and cannot take part in a cycle if a future handler ever queues a message while holding the reactor's. - The consensus goroutine now stops the message queue when it leaves on a dispatch error, instead of stranding the queue's reader goroutines. Tests that asserted less than they claimed: - The aggregate bound over all charges is asserted against the real bucket over the flood, which matters more now that the budget is read on the scheduler goroutine and charged on another: the bound rests on the handoff between them rather than on one goroutine doing both. - The flood's premise is asserted rather than assumed: a commit an attacker cannot make good on is charged exactly one verification, and it is that price that decides how many turns it takes to hold the budget down. - Two assertions in the shed test could not fail, since nothing consumes the queue there. Replaced with what that setup can actually show, and the write-ahead log claim moved to the budget test, where a message really is dropped between the queue and the log. - The honest-vote test waited four minutes for a failure, twice, which is longer than the repo's own test timeout — a regression would have shown up as a timeout rather than as the assertion message. Now thirty seconds. Comments that were wrong or claimed too much: - The wait for budget takes no tokens, so it is not the reservation the old comment described; what makes the charges that follow safe is that only one peer message is ever in flight. - A lane's capacity is not a reservation: the aggregate bound is the smaller of the two once several dozen lanes are busy, so under a wide flood a single peer can no longer hold a whole block's parts and the round times out. - The deficit bound scales with the head's own cost. The heaviest precommit Dash validators produce is served inside the propose timeout but not inside the vote timeout; the test now says so instead of quietly grading it against the looser one. - Drop-oldest is argued from time-validity, which holds for votes and commits but not for block parts; the block-part case is now argued on its own terms. - The rotation is bounded at every instant, but the lane table only across a reclamation interval. The identity-rotation test claimed both. - An expensive head against a cheap flood bounds the wait but does not tell deficit round robin apart from plain round robin, which serves such a head sooner. Only the cheap-head-against-expensive-flood case does. - Which functions require the lane lock, that the scheduler's clock does not reach the budget's, and that routing every message with a peer to the peer side is what the finished-message report depends on. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): correct the fairness bound to account for message cost The stated bound assumed every competing message was the cheapest possible, and was then used as the acceptance criterion. The real bound scales with the head message's own verification cost, so a realistic precommit lands around two seconds rather than the fifth of a second quoted, which is longer than the vote timeout. No work-conserving fair scheduler can do better than the fair share, so the criterion as written could never have been met. The measured value is now recorded, the test grades against the propose timeout, and the three inputs that can actually close the gap are named: a higher verification rate, fewer lanes an attacker can hold, or removing the second verification pass. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(consensus): charge proposal verification to the verification budget Proposal signature verification is one BLS pairing on the consensus goroutine, and it was the one peer-reachable pairing the node-wide verification budget did not price: budgetedMessageCost returned 0 for a proposal, so the peer scheduler never gated one and nothing drew a permit before the check. Nothing de-duplicates a proposal that fails verification either -- rs.Proposal is set only by a proposal that passes -- so every forged copy is verified again. The per-peer data limit admits ~100 proposals/s/peer (PeerDataRateLimit 500 / proposalTokenCost 5) with a 200-message burst, so a handful of peers saturate a ~370 pairings/s verifier while the honest proposer's message waits behind rotating lanes, keeping rs.Proposal nil and the flood self-sustaining. Price a proposal at one work unit and draw the permit where the pairing is, so the gate the scheduler applies and the work actually drawn agree. The permit is taken after proposer selection (the non-validator path runs no pairing and is not charged) and before the sign-digest derivation, so that hashing is inside the bound too. Refusal returns the existing budget-exhausted sentinel, which the logging middleware already treats as a non-punitive local drop: no peer error, no WAL record. Red -> green: TestProposalFloodCannotExceedTheVerificationBudget dispatches 50 forged proposals against a drained budget. before: 50 WAL writes, 50 signature checks after: 0 WAL writes, 0 signature checks; one admitted after refill Refs docs/CONSENSUS_DOS_PLAN.md §1, §2.3; docs/CONSENSUS_DOS_PIECE2_SPEC.md §5a. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): stop peer-triggerable rejections from writing Error logs Two log-amplification leaks on the proposal and block-part paths. A proposal that fails signature verification wrote an Error line that embedded the whole proposal — an attacker-controlled, unbounded payload — and nothing de-duplicates a failing proposal, so one line was written per copy. The line is now Debug and carries only the round and the key the check was made against; nothing that came off the wire. Block-part proof failures, and the remaining proposal rejections (POL round, core-chain height, blockID-vs-commit mismatch, unverifiable proposal), all reached the logging middleware unclassified and were written at Error. Every one of them is free for a peer to produce, so they join the floodable set and are logged at Debug. Classification only selects a log level; it does not change whether a peer error is raised, and neither of these paths raises one. Red -> green: TestProposalRejectionsAreFloodable, TestBlockPartRejectionsAreFloodable and TestRejectedProposalIsNotEchoedIntoTheLog all fail before the change (8 unclassified errors; an Error line carrying the forged signature). Refs docs/CONSENSUS_DOS_PLAN.md §2.7. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): fail a rate-limit wait fast when the caller cannot wait it out Three review follow-ups. The rewritten wait path lost rate.Limiter.WaitN's fast-fail. WaitN reserves against the caller's remaining context budget and refuses up front when the delay exceeds it; the rewrite reserved without a limit and then blocked on the timer or ctx, so a caller with a short deadline was parked for the whole deadline — holding the reserved tokens, and on a shared channel goroutine every message behind it — only to be refused anyway. It also lost the distinction between "the bucket cannot serve you in time" and "you were cancelled". Restore both: compare the delay against the deadline, cancel the reservation (which refunds in full, since it has not come due) and return a distinct error. The fresh-peer burst aggregate test used 64 connections. The peer manager may hold MaxConnected plus MaxConnectedUpgrade at once, and node/setup.go passes 4 for the latter, so the ceiling is 68; the burst comment in the consensus reactor claimed 64 for the same reason. Narrow two comments that claimed more scope than the code delivers: the data-channel limiter and proposalTokenCost bound what ONE peer can spend, not the aggregate across peers, which is the node-wide verification budget's job. Red -> green: TestRateLimit_WaitFailsFastPastTheCallerDeadline before: returns after 301ms wrapping context.DeadlineExceeded after: returns up front with the limiter's own refusal Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound the hashing a peer can force with bad block-part proofs The part-set caps bound how many parts a node ACCEPTS. They say nothing about the ones it rejects: a proof that does not check out leaves the slot empty, so the next copy aimed at the same in-range index is hashed from scratch, and verifying a proof hashes the whole ~64 kB leaf before it can find the mismatch. Nothing charged for that work. Add a per-peer allowance denominated in the bytes of leaf hashing spent on proofs that fail. A part is refused before verification once its sender has spent its allowance; only an actual failure is charged, so a peer whose parts verify never draws on it. Per peer rather than node-wide, deliberately. A node-wide bucket would let one peer's garbage stop this node assembling a block at all, trading a bounded CPU cost for an unbounded liveness one. The node-wide bound follows from the connection ceiling instead: 68 slots x 256 KiB/s is a low single-digit percentage of one core, asserted by TestBlockPartProofBudgetNodeWideBound. An accepted part clears what its sender has spent. Honest proof failures come in runs -- a round this node has moved past -- mixed with parts that do verify, and it is the mixture that must not cost a peer the parts we need from it. The burst additionally absorbs 32 full-size failures before anything is refused. Refusal is a silent local drop: no error, no peer error, no WAL record, counted on the new consensus_block_part_proof_drops metric. Red -> green: TestRepeatedInvalidBlockPartProofsAreBounded, with the gate disabled, re-hashes the same invalid part 1000 times (65 MB of hashing from one peer, and it does not stop there); with it, the run ends inside the burst. Refs docs/CONSENSUS_DOS_PLAN.md §2.5. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound the State and VoteSetBits channels Neither channel verifies a signature, so the node-wide verification budget does not bound them at all; nothing else did either. Three problems, all reachable by any connected peer. Add a per-peer ceiling across both channels AND a node-wide one. Neither substitutes for the other: the per-peer allowance keeps one sender from occupying the channel goroutine, and the aggregate keeps that guarantee from being bought around with fresh node identities, which are free. Both sit well above honest gossip -- a peer broadcasts a HasVote per vote it adds, plus round-step messages and up to four VoteSetMaj23 per gossip tick -- and both drop silently: the peer at its allowance under load is as likely to be honest and gossiping hard as hostile. Price VoteSetMaj23 above the rest. It is the one message here that asks this node for work: it makes us build a bit array over every validator, up to MaxVotesCount bits, and send it back -- more than it cost to ask. Suppress repeats. A peer's gossip loop resends the same claim on every tick, and the answer comes from our own vote set alone, so until that vote set gains a vote the peer has not been told about, answering again conveys nothing. Tracked per peer by claim plus the number of votes the last answer carried; votes are only ever added, so an unchanged count means an unchanged answer, and the peer still learns of every vote we gain. Bound the response send. It went out with the caller's context, so a router that could not take it parked the goroutine serving every peer's state messages. It now has a short deadline of its own and gives up quietly; the peer asks again on its next tick. Red -> green, with each mechanism disabled in turn: per-peer ceiling: 400000 messages admitted from one peer against a 4000 ceiling aggregate: the fresh-identity loop never terminates suppression: an unchanged claim is answered every time bounded send: the test hangs until the 2m timeout Refs docs/CONSENSUS_DOS_PLAN.md §2.4. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(evidence): spec bounding the evidence channel Plan item §2.10. Records what was verified against the code rather than assumed, including three findings the plan did not have: the reactor evicts a peer on the first evidence that fails verification, evidence gossip is retry-based (so a receive-side drop is a delay, not a loss), and signature verification is skipped entirely when the validator set at the evidence height carries no public keys. That last one dictates the whole shape of the de-duplication: acceptance alone cannot be enough to remember an equivocation, or an attacker could claim a real equivocation's identity with garbage signatures and lock the genuine proof out for good. Reviewed by independent security and correctness lenses before any code; their findings are folded in and the pre-existing issues they surfaced are recorded in §6 for other owners. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(evidence): de-duplicate evidence by what it alleges, not how it is encoded De-duplication keyed on the evidence hash, which covers the signature bytes, so flipping one byte of a signature produced a piece of evidence the node had never seen and bought the sender a full re-verification — two BLS pairings plus a block-meta and a validator-set lookup — for the cost of one byte. Nothing rate-limited the evidence channel, so the flood was free to repeat. Remember instead what a piece of evidence alleges: the height, round and step, the accused validator, and the two conflicting block IDs. A re-encoded copy of an equivocation we have already proven is then recognised as the same accusation and costs a map lookup. The memory only ever records evidence whose signatures were actually checked. VerifyDuplicateVote skips them when the validator set at the evidence height carries no public keys, and such evidence is stored anyway — so remembering on acceptance alone would have handed an attacker an evidence-suppression tool: equivocations are public, and a forged copy could claim the identity before the genuine proof arrived. Evidence is a safety mechanism; suppressing it is worse than the flood. The set is bounded at 1024 entries and forgets the lowest heights first, which are the ones closest to ageing out of the window anyway. Forgetting only forfeits a free refusal, so it can never cost correctness. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(evidence): bound the work an inbound evidence message can cost The evidence channel had no ceiling of any kind. Every message that got past the hash de-duplication paid for two BLS pairings and two disk lookups on the evidence reactor's goroutine, and nothing limited how many a peer could send. Admit inbound evidence through a gate ordered cheapest-refusal-first: votes that cannot describe one equivocation, vote extensions beyond what a real vote may carry, heights the block store cannot serve, and equivocations we already hold proof of are all refused before anything is spent — including before the message is hashed for the pool's duplicate check, which is itself a full marshal and digest of a message that may approach the channel's 1 MB limit. Only what survives is charged, in pairings, against a per-peer bucket and a node-wide one. Genuine evidence still lands. Each peer has its own bucket, so an attacker cannot spend an honest peer's allowance however many identities it holds; the node-wide rate is set above what every peer together may spend, so against a fixed peer set it refills faster than it drains and stops being the binding constraint; and it is inspected before the per-peer bucket is charged, so a congested node never bills a peer for capacity it then denies. Where that is not enou…
shumkov
added a commit
that referenced
this pull request
Aug 17, 2026
…#17 could not Merging v1.6-dev brings in TestReactor_Backfill_UnknownVoteExtensionTypeAbortsUnattributed from #17. It fails, and it should: it asserted the mis-attribution this branch removed. #17 recorded the limitation deliberately rather than as an oversight. Its doc comment spelled out that a commit refused while decoding was dropped, that the fetch could only read the resulting silence as a slow peer, and that the run therefore ended on the retry budget every peer shares with the offending peer unnamed - "enough such answers end the backfill while honest peers are still available". Its assertion said the same in one line: ErrorContains "max retries", explained as "the abort is charged to the shared retry budget rather than to the peer that caused it". An unknown vote-extension type is the third member of the decode class this branch fixed, alongside the out-of-range quorum type and the block-protocol mismatch, so the limitation is gone: the response is now delivered to the fetcher as a refusal, the peer is withdrawn from the run and reported, and the run ends naming the cause. The assertions are inverted, not relaxed. Both original safety assertions are kept - the run errors rather than panics, and nothing reaches the block store - and the "max retries" assertion becomes three stronger ones: the failure names the extension type, it explicitly does not blame the budget, and the peer that sent it is reported by name. Renamed accordingly, since AbortsUnattributed asserts the opposite of what now happens. The report is asserted non-fatal, which this cause makes the clearest case for: an extension type undefined in this build is defined by whatever release introduces it, so a peer failing the check is as likely to be an honest node one release ahead as a malicious one. UPGRADING.md already records that adding a type has exactly this effect. Mutation-checked rather than observed passing: restoring the dropped-decode-error behaviour makes it fail with "max retries to fetch valid blocks exceeded (20); target height: 10, height reached: 15" - the string #17 asserted, produced by the code path #17 described. No production code changed. internal/statesync and internal/blocksync green under -race -tags deadlock; no golangci-lint delta across either package. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
shumkov
added a commit
that referenced
this pull request
Aug 17, 2026
…flood DoS, phase 1) (#17) * docs(consensus): spec for vote-flood DoS hardening Records the reviewed analysis and plan for the consensus vote-flood resource-exhaustion DoS (distinct from the Commit-extension crash, which is fixed on branch fix/commit-extension-panic). §1 mechanics are verified and reliable: an unprivileged peer floods a validator with structurally-valid, cryptographically-invalid precommits, forcing ~2.7-2.9 ms of BLS verification each, a WAL write, and two error logs, with no disconnect. §4 records the proposed mitigation layers (L1-L6) and the blocking defect independent review found in each first draft — none may be implemented as first written. §7 is the revised recommendation; §9 the no-code allowlist-only mitigation; §10 a related latent HeightVoteSet issue. No code fix yet — this branch holds the plan; the fix will be implemented and validated here. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): bound invalid-vote log amplification under peer flood (L4) An unprivileged peer flooding invalid votes made a validator emit two Error-level log lines per message (measured 46,752 entries for 23,376 bad votes) — log volume scaled with the attacker's message rate. Downgrade to Debug only the validation errors an unprivileged peer can trigger at will, classified by error TYPE (not by whether a peer sent the message): - addVoteLoggingMw: a not-added vote logs at Debug. The notable cases (non-deterministic and conflicting signatures) are still logged at Error by addVoteErrorMw. - loggingMiddleware: uses isPeerFloodableError (matches ErrVoteInvalidBlockSignature, ErrVoteInvalidSignature, ErrVoteUnexpectedStep via errors.Is). Anything not positively matched — including internal faults such as ErrPrivValidatorNotSet surfaced while handling a peer message — stays at Error, so this never hides a real problem. Classifying by PeerID alone was too broad (it would hide internal faults that surface during peer-message handling); this uses explicit error categories instead, which fails safe toward surfacing. Part of docs/CONSENSUS_VOTE_FLOOD_SPEC.md (L4). No control-flow change; logging level only. Tests (red→green): internal/consensus/log_amplification_test.go — isPeerFloodableError matches floodable errors (including the production ErrInvalidVoteSignature wrapping) and rejects internal faults; loggingMiddleware logs a floodable error at Debug but an internal fault at Error even for a peer message. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): cap vote-extension count to stop verification amplification (L5) Each threshold-recoverable vote-extension costs one BLS signature verification (~2.7 ms). Nothing bounded the count, so an unprivileged peer could pack ~10^4 extensions into a single ~1 MB commit or precommit and force that many verifications on the single consensus goroutine — the core of the vote-flood DoS. Add MaxVoteExtensions (32) enforced in MakeQuorumSigns, the shared chokepoint of VerifyCommit (commits) and VerifyExtensionSign (precommit votes). Over-cap messages are rejected before any per-extension work. Placed on the verification path, not Commit.ValidateBasic, for the same reason as the unknown-type fix: a rejection on the WAL-decode path would abort replay and re-brick an already-attacked node. Cap rationale: Dash Platform's ExtendVote returns at most withdrawal_transactions_per_block_limit threshold-recoverable extensions (currently 4, a bounded SizedQuery limit, verified in rs-drive-abci). 32 gives 8x headroom for a future protocol increase while bounding attacker-forced work to ~32 verifications (~86 ms) per message instead of ~25 s. If that limit is ever raised above 32, raise this constant in the same release. Part of docs/CONSENSUS_VOTE_FLOOD_SPEC.md (L5). Note: this changes what the p2p layer accepts; a P2PProtocol bump decision is deferred to the maintainer per RELEASES.md (legitimate traffic is unaffected, so practical interop impact is nil). Tests (red→green verified): types/vote_extension_count_test.go pins the count boundary at MakeQuorumSigns and via VerifyCommit; both fail with the check removed. Green across types, privval, light, consensus. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): per-peer vote-channel rate limit (L1) An unprivileged peer can flood the vote channel and force one BLS verification per message (~940/s in the reported attack). Add a per-peer token-bucket rate limit on the vote channel (votes and commits): messages over a peer's budget are dropped in the reactor before reaching signature verification, bounding the CPU one connection can force. - New config consensus.peer-vote-rate-limit (float, messages/s/peer; 0 disables). Default 100: an honest validator gossips ~10-20 vote-channel messages/s, so the limit only bites a flood. - Burst is a small 2x the rate (voteRateBurstMultiplier), not the shared limiter's 10x default: vote-channel messages are individually expensive, so a large burst would let one peer front-load seconds of BLS work in an instant. NewRateLimitWithBurst floors the burst at 1 when the limit is positive, so a small rate cannot truncate to a zero-token bucket that silently drops everything. Config validation rejects NaN/Inf/negative rates. - drop=true (non-blocking): an over-limit peer cannot block the shared channel goroutine, and honest peers on other limiters are unaffected. - Applied in Reactor.processMsgCh via allowVoteChannelMessage; other channels and the disabled (0) case always pass; limiter errors fail open. Scope and limits (honest): this bounds a SINGLE connection. Node identities are free and unbound, so a determined attacker dilutes it across connections/IPs — tighten p2p connection limits alongside. The real fix is the validator-set vote gate (docs/MASTERNODE_VOTE_GATING_SPEC.md). Commits ride this channel and are covered too; a separate typed disconnect on invalid-commit-signature is planned. Tests (red->green): vote_rate_limit_test.go (per-peer drop, isolation, other channels unlimited, disabled=0); ratelimit_test.go (explicit/floored burst); config_test.go (rate validation). Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): wire max-incoming-connection-attempts into the router (connection limit) getRouterConfig set IncomingConnectionWindow but never passed MaxIncomingConnectionAttempts, so the config value was silently ignored and the router always fell back to its internal default (100, router.go:99-100). An operator tightening consensus/p2p connection limits to bound a flood got no effect. Pass conf.P2P.MaxIncomingConnectionAttempts through to RouterOptions so the per-IP incoming-attempt cap is operator-controllable. This is the connection- level lever that bounds how many connections/IPs an attacker can use to dilute the per-peer vote-channel rate limit (L1) and to spam commits (which cannot be sender-gated). Default value unchanged (100); tightening it is now an operator config action. Test: node_test.go asserts a non-default config value flows into RouterOptions (fails before the fix: the field was 0). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs: implementer brief for remaining vote-flood hardening Captures the precise, non-obvious decisions for the three remaining items (typed commit-signature disconnect, data-channel proposal rate limit, L6 block-sig-before-extension) so a focused implementer session can execute them without re-deriving the classification/scope nuances from the specs. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): disconnect peers sending cryptographically invalid commits Commits ride ConsensusVoteChannel and trigger threshold-signature verification, but cannot be sender-gated: non-validators legitimately relay them for catch-up (shouldCommitBeGossipedForCatchup). A commit whose THRESHOLD SIGNATURE fails to verify is, however, unambiguous misbehaviour — a commit is stored only after a successful VerifyCommit (state_data.go), so no honest node ever relays a cryptographically invalid one. Evict the peer that sends one. Precise, safe classification (the whole risk here is a false positive that partitions the network): - New typed error types.ErrInvalidCommitSignature, emitted ONLY wrapping the final quorumSigns.Verify failure in ValidatorSet.VerifyCommit. Wrong block ID (rejected earlier), wrong quorum hash, extension errors, and local finalization faults keep their distinct, untyped errors. - The disconnect fires only when errors.As(err, *ErrInvalidCommitSignature) succeeds, and never for a WAL-replayed message (FromReplay gate — replay re-dispatches with the original PeerID). - Propagation is non-blocking: the state machine queues a peerErrorMsg (dropped if the buffer is full) and a new reactor peerErrorRoutine drains it and emits a Fatal p2p.PeerError. The consensus goroutine never blocks. Composes with L1 (rate-limits commit spam) and the connection-attempt cap; together they bound commit spam without gating honest relayers. Tests (both pin the classification; they fail if any non-signature error were treated as a signature error): - types/validator_set_test.go: a bad threshold signature is typed; wrong block ID / wrong quorum hash are not. - internal/consensus/state_try_add_commit_test.go: only the typed error queues a fatal eviction; wrong-block / wrong-quorum / local-fault / replay-sourced do not; nil queue tolerated; full queue drops the report. Green across types and internal/consensus. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): per-peer data-channel rate limit for proposal flood The data channel has the same re-verifiable BLS flood as the vote channel: a junk proposal fails signature verification (state_proposaler.go) but never sets rs.Proposal, so there is no dedup and every copy re-verifies. An unprivileged peer (need not be the proposer) can force N verifications with N junk proposals. L1/L5/the vote gate do not touch this channel. Add a per-peer token-bucket limit on the data channel, but cost-WEIGHTED rather than a flat message rate — because the channel also carries block parts, which are legitimately gossiped to non-validators for catch-up and must not be throttled: - proposals cost proposalTokenCost (5): each forces an un-deduplicated BLS verification; - block parts and POL bit arrays cost 1: cheap part-set bookkeeping. New config consensus.peer-data-rate-limit (default 500, 0 disables): ~500 block-part messages/s of headroom while capping proposals near the vote channel's verification budget (~100/s). drop=true, same non-blocking semantics as L1. Burst (dataRateBurstFor) is floored at proposalTokenCost: rate.Limiter.AllowN permanently rejects any request larger than the burst, so a burst below a proposal's cost would make the node silently never admit a proposal and stall consensus. Design note: this deviates from a simpler flat generous limit; weighting was chosen so block-part gossip keeps full headroom while proposals are still bounded (a flat limit high enough for parts would leave proposals effectively unbounded). Tests (run, green): internal/consensus/data_rate_limit_test.go — proposal flood dropped past budget; block-part gossip unaffected; burst admits the most expensive message; disabled at 0. Green across internal/consensus, config, p2p/client. Co-Authored-By: Claude Opus 4.8 <[email protected]> * perf(consensus): verify block signature before vote-extension signatures (L6) In the precommit add-vote path, extension signatures were verified before the block signature. Extension verification costs one BLS pairing per threshold-recoverable extension and does not short-circuit, so a peer that cannot produce a single valid signature could still force the whole set of pairings (bounded to 32 by L5, but still 32x a single check). Add Vote.VerifyBlockAndExtensionSigns, which authenticates the block signature first and verifies extension signatures only on success. A forged precommit is then rejected for the cost of one pairing. The set of votes admitted is identical to before (a MatchesFullVerifyAdmission test pins this) and the ABCI VerifyVoteExtension call remains gated exactly as before — only the work done before rejecting a forged vote changes. Marginal once the validator-set vote gate lands (only validators can send precommits then), but cheap, localized, and correct. Tests (green): types/vote_test.go — short-circuits on bad block signature; still rejects a valid-block/bad-extension vote; accepts a valid vote; admission matches unconditional verification. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): gate votes to validator-set senders (the vote-flood fix) This is the root-cause fix for the vote-flood DoS. The mitigations (rate limit, extension cap, log/commit hardening) bound a flood; this changes WHO can send one at all. An unprivileged peer with a freely-generated node key could make a validator perform BLS verification simply by sending votes: nothing checked that the SENDER was a consensus participant (the isValidator gate checks the receiver, and a peer's ProTxHash is self-reported, not bound to its handshake key). Drop votes whose authenticated node ID (envelope.From, bound to the p2p handshake public key) is not in the current or previous validator set. Only validators legitimately send or relay votes — a node gossips a vote to a peer only when that peer is a validator (shouldVoteBeGossiped) — so this rejects nothing honest while restricting the expensive vote path to actual quorum members. In Dash terms the attacker must now own an evonode (collateral-backed, identifiable, PoSe-bannable) rather than any host with a node key. Design (see docs/MASTERNODE_VOTE_GATING_SPEC.md §10): - Set = current Validators UNION LastValidators node IDs. The union covers the quorum-rotation boundary, where late votes for the previous height arrive from the previous quorum. The binding is already in-process (validator.NodeAddress.NodeID, from the ABCI ValidatorUpdate URI) — no Dash Core poll, no new dependency, no registry. - Drop-only, no disconnect (avoids evicting a peer during a rotation window). - Fails OPEN on ANY incomplete identity coverage: if any member of either set lacks a node ID, the gate is disabled entirely rather than risk dropping that validator's votes. The gate is either fully informed or fully off, so a false positive (dropping an honest vote and partitioning the network) is impossible. Current Dash Platform never produces mixed sets (platformNodeID is mandatory for every validator), but generic/non-Dash and transitional states are handled safely. Only VOTES are gated. Commits are not (non-validators relay them for catch-up); they are handled by the per-peer rate limit and the invalid-signature disconnect. Tests: internal/consensus/vote_sender_gate_test.go (red->green) — current and previous-set validators allowed; non-validator dropped; fail-open with no node IDs, at genesis (nil LastValidators), and on a MIXED set (any node-ID-less member) in either set. The full internal/consensus suite passes unchanged. Recommended before release: testnet / e2e validation across a quorum rotation. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs: bring vote-flood + gating specs up to date with the implementation The vote-flood spec still said "sent back for rework, none may be implemented" — stale now that every layer plus the root-cause validator-set vote gate is built, tested, and reviewed. Update its status to IMPLEMENTED with a table mapping each shipped layer to its commit, and note what was deliberately deferred. Add MASTERNODE_VOTE_GATING_SPEC.md to this branch (the gate's design doc, which belongs with the gate code) and mark it IMPLEMENTED. Both specs now reflect the final validator-scoped design and carry the testnet-validation caveat. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): harden vote/commit signature verification against extension amplification Block-signature short-circuit before vote-extension signatures; typed ErrVoteExtensionCountMismatch so a count/version mismatch is not treated as evictable forgery; vote-extension cap enforced on the verification path only, never on signing. Red-green tests included. Co-Authored-By: Claude Opus 4.8 <[email protected]> * wip(consensus): vote-gate fail-open metric + processMsgCh log hygiene SEC-006 gate observability (VoteGateFailOpen metric, transition-only Warn) and SEC-008 envelope-dump log downgrade. Gate observability is superseded by the DoS-throttle rework (gate is being removed); log hygiene is kept. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): DoS defense plan, per-message analysis, and review trail Reviewed lean throttle plan (Phase 1) + parallelization follow-up (Phase 2), the per-message DoS matrix and findings, open-questions log, and the Codex review trail. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound peer signature verification Add a shared node-wide 300-operation-per-second token bucket with a bounded burst sized for both current verification passes of the largest accepted precommit. Acquire permits immediately before the block signature check, then acquire extension permits only after the block signature succeeds. Apply the shared budget to peer Votes and Commits while bypassing local and replayed messages. Budget exhaustion is surfaced as a non-punitive, flood-safe drop and cannot be classified as forged commit evidence. Test would have caught this in CI: ✖ before fix (budget APIs and config were absent), ✔ after (staged-permit, affected-package, lint, and build checks pass). Co-Authored-By: OpenAI Codex <[email protected]> * test(consensus): add DoS attack-surface audit POCs Empirical grounding for the DoS defense plan. Each test documents a concrete attack surface and passes by demonstrating current behavior: - HeightVoteSet unbounded round allocation: a peer mints two new rounds per 32 bytes of forged proTxHash, rejected without BLS work (memory cost without CPU cost). - Per-node-identity rate-limit reset: the per-peer limiter is keyed on the p2p node ID, so a fresh Ed25519 keypair resets the budget; the cap is per-keypair, not per-attacker. - Burst-clamp permanent drop: a cost-weighted rate limit silently and permanently drops any single message heavier than the token bucket's burst, halting the chain if the app returns more extensions than burst. - Commit verification cost vs extension count: measures victim CPU per attacker byte, the denomination the rate-limit default must use. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): refine verification budget handling Preserve verification-budget exhaustion as local overload on the Vote path, count live remote Vote and Commit budget drops, and keep wrapped budget errors out of peer-eviction handling. Test would have caught this in CI: ✖ before fix (Vote budget denial was wrapped as an invalid signature and metric wiring was absent), ✔ after (the regression and metric classification tests pass). Co-Authored-By: OpenAI Codex <[email protected]> * docs(consensus): piece 2 spec - verification fairness Design for the required fairness invariant: per-peer lanes drained by deficit round robin, so an attacker flood cannot starve honest consensus traffic out of the shared verification budget added in piece 1. Reviewed by four independent lenses before implementation. Notable outcomes: - Prices every message type on the peer queue. The queue carries Proposal and BlockPart as well as Vote and Commit, so pricing only the latter two left the scheduler's own bounds unprovable and left proposal verification as an unbudgeted pivot that a handful of peers can use to saturate the verifier. - Drops the escrow/lease design in favour of a whole-message affordability check on the state goroutine. The token bucket cannot express partial settlement, a lease cannot ride a message that is also a WAL record, and the reservation leaked across the scheduler handoff where a single leak halts the peer path. - Records what the piece cannot deliver: honest share is bounded by connection slots, not by scheduling, so raising it is folded into piece 3b. - Names the existing full-queue error path that would turn a routine lane overflow into peer eviction, which bounded lanes make reachable. Also surfaces two new Phase 1 items: the unprotected evidence channel, and whether removing the double verification must move out of Phase 2. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(consensus): fix starvation flaw in piece 2 budget admission Adversarial re-review of the admission mechanism found it broken for the very property the piece exists to guarantee. Gating dispatch on "can the bucket cover this message, else drop" is biased against expensive messages absolutely rather than proportionally. The bucket is a level, not a queue, and a dropped message costs microseconds, so a saturated supply of cheap messages pins the level below what an expensive one needs and it is never admitted. Round robin cannot compensate: it allocates turns while the check allocates tokens, and a turn granted then discarded is a turn wasted. The mechanism is fair only when all offered costs are equal, which is precisely not the adversarial case. Replaced with bounded, context-aware waiting. Because every draw is serialized on one goroutine, blocking for tokens is itself the reservation, which buys what the rejected lease design was reaching for without any lease. The staged draws also wait rather than fail, so whole-message atomicity holds by construction instead of by argument. Also restates the fairness invariant over admitted verification rather than dispatch. As worded it stayed true while messages were discarded, so it could not fail even as the chain stopped making progress; the test now asserts honest completion latency, and a regression test pins the rejected behaviour. Records three implementation traps found in the process: cancelling a token reservation refunds nothing once its deadline passes, the limiter's own wait consults real time and would defeat the test clock, and equal burst and worst-case cost admit a maximum message only on a fully idle node. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(consensus): charge the per-peer vote budget in verification work Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §8 commit 1 (the §5a work plus the §7 clock-seam prerequisite). The per-peer vote-channel limiter charged one token per message, so a peer could buy a precommit carrying 32 vote extensions — up to 66 BLS signature verifications — for the same price as a prevote. The budget therefore bounded message count, not the CPU it was introduced to bound. Price every message a peer can put on a consensus channel in verification work, per the spec's §5a table: prevote 1; nil-block precommit 1; non-nil precommit with n extensions 2*(1+n) (two verification passes), capped at 66; commit with n extensions 1+n, capped at 33; proposal 1; block part 1. The cost is derived from the message's declared contents alone, so it is charged before conversion, validation or verification. A message declaring more extensions than any legitimate participant produces is refused a price and dropped locally — never reported as a peer error, so neither a protocol revision nor a bug in this model can evict honest peers. Floor the per-peer burst at that worst-case cost. This fixes a live hazard: rate.Limiter rejects any request larger than the burst no matter how long it waits, so with burst = 2 * limit any peer-vote-rate-limit below 33 would make a fully-extended precommit permanently inadmissible — every validator's precommits silently dropped and no block ever committed. Raise the peer-vote-rate-limit default to 600, now denominated in verification work rather than messages. A Dash-realistic precommit (four extensions) costs 10, so this admits ~60/s from one peer. Provisional pending the load test. verificationBudgetBurst now derives from the same constant instead of repeating the expression, so the global burst and the message cost cannot drift apart. Prerequisite for the spec's §7 test plan: the p2p rate limiter read time.Now() directly, so refill behaviour could only be inferred from sleeps. It now meters through an injectable clockwork.Clock (the abstraction already used by the blocksync synchronizer and the p2p client), defaulting to the real clock — production behaviour is unchanged. Out of scope, deliberately: the §5b affordability peek and minimum-rate validation, and the §5c lanes/DRR. Red → green: * TestAllowVoteChannelMessage_ChargesVerificationCost — ✖ "1201 is not greater than 12000" (prevotes and maximum-cost precommits were admitted in equal numbers) → ✔ * TestAllowVoteChannelMessage_CostSharesOneBudget — ✖ → ✔ * TestAllowVoteChannelMessage_UnpriceableMessageDroppedLocally — ✖ → ✔ * TestVoteRateBurstAdmitsMostExpensiveMessage — ✖ against the old burst = 2 * limit formula ("1 is not greater than or equal to 66") → ✔ * TestRateLimit_RefillsOnInjectedClock — ✖ (undefined: WithRateLimitClock) against the previous ratelimit.go → ✔ Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): make whole-message verification affordable by waiting Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §8 commit 2 (§5b, plus the §5d placement argument). Lanes/DRR (§5c) stay out of scope. Piece 1 charges the node-wide verification budget in stages while a message is verified: a remote precommit draws 1 then n, twice over. A later stage can therefore be denied after earlier stages already paid for a BLS pairing and the ABCI VerifyVoteExtension round-trip, wasting the work and dropping a valid vote. Before a peer Vote or Commit is dispatched, wait until the budget can cover that message's own cost — from the piece-1 cost model, never the protocol maximum. Since every draw is made by the single consensus goroutine, blocking for tokens is itself the reservation: nothing can take them while we wait, so the staged charges that follow cannot fail (I3, now true by construction rather than by argument). Waiting, not peeking-and-dropping. An earlier draft gated dispatch on "does the bucket cover W right now, else drop". That is broken: the bucket is a level, not a queue, and a drop costs microseconds, so demand-saturated cheap messages pin the level below what an expensive honest message needs and it is never admitted. The new cost-bias test pins exactly that failure. The wait is bounded and selects on ctx.Done(). A non-ctx-aware wait would deadlock shutdown (readQueueMessages defer -> fanIn -> stop() -> receiveRoutine never returns); an unbounded one would stall consensus behind an over-subscribed budget. Both give up non-punitively — never a PeerError — since local overload says nothing about the sender. maxWait is 2*C_max/R (440ms at defaults), a safety net rather than a working limit: refilling the most expensive message from an empty bucket takes C_max/R = 220ms, so that is the real bound on how long the goroutine is held. It is implemented as the outermost msg middleware rather than by widening types.VerificationBudget or plumbing a ctx into types/: the state goroutine's dispatch boundary is the only place that has both the ctx and the whole message, and withMiddleware makes the last-appended middleware outermost, so a shed message costs zero WAL writes — asserted, not assumed. rate.Limiter.WaitN is avoided (it reads the wall clock internally and would defeat the clock seam), as is ReserveN+Cancel (CancelAt refunds nothing once timeToAct has passed, silently double-charging). The wait is built from TokensAt plus the injected clockwork clock, which the budget now meters against. Burst is no longer a coincidence. verificationBudgetBurst was exactly C_max, so a maximum-cost message was admissible only on a completely idle node. It is now 2*C_max, and B > C_max is a compile-time assertion: MaxVoteExtensions invites being raised, and at 64 a burst left behind would make that message permanently inadmissible. Validate a minimum verification-rate-limit. 0.5 was legal (only NaN/Inf/negative were checked) and would mean minute-scale stalls; the limit must now be 0 (disabled) or at least the cost of the most expensive single message, so the bucket refills it within a second. Red -> green (peek-and-drop counterfactual: waitFor replaced by "TokensAt >= cost, else drop"): * TestVerificationBudgetWaitAdmitsExpensiveMessageUnderCheapFlood — ✖ "expensive message starved in round 0: cheap traffic must delay it, not exclude it" → ✔ * TestVerificationBudgetWaitAdmitsMessageAfterRefill — ✖ "a message that is not affordable yet must wait for the refill, not be dropped" → ✔ * TestVerificationBudgetWaitCompletesStagedPrecommitDraws — ✖ "expected []int{1,4,1,4}, actual []int(nil)" → ✔ Red -> green (piece-1 baseline: middleware wait disabled): * TestVerificationBudgetWaitCompletesStagedPrecommitDraws — ✖ "expected []int{1,4,1,4}, actual []int{1,4}", with the node logging "rejected peer message: verification budget exhausted" mid-verification → ✔ * Whole new API absent → ✖ "undefined: withVerificationBudgetClock", "inner.maxWait undefined", "undefined: config.MinVerificationRateLimit" Also covered: ctx cancellation returns promptly and does not hang shutdown of receiveRoutine; a deadline drop writes nothing to the WAL, queues no peer error and verifies nothing, while the same message admitted does write one WAL record; every budget charge is made on the receiveRoutine goroutine; a commit charges [1, n] and its admitted cost covers it; B > C_max; minimum-rate validation. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): decouple the per-peer vote burst from the configured rate Review follow-ups on the piece-2 cost model (5056628, 2064219), per docs/CONSENSUS_DOS_PIECE2_SPEC.md §5a and §7. Burst is no longer a multiple of the rate. voteRateBurstFor returned max(2*limit, C_max), so the new default of 600 work/s gave every peer a 1200-unit bucket: ~1200 cost-1 messages or 18 maximum-cost precommits front-loaded in a single instant, and 64 connection slots exposed 76800 units — nearly four times the 20000-message consensus queue they share. Since a peer starts with a full bucket, that is what one reconnect buys. The burst is now an independent work allowance sized from honest demand (voteRateBurstCatchUp = 200: ten vote-channel messages a second at the ten work units a four-extension Dash precommit costs, i.e. about two seconds of an honest peer's heaviest gossip), with C_max kept as a floor so the most expensive protocol-legal message can never become permanently inadmissible. All 64 slots now front-load 12800 units, below the queue. peer-vote-rate-limit keeps its default of 600. Message pricing is exhaustive. peerMessageCost priced any unrecognised message at the floor of 1, so a message type added later would be admitted at an invented price with nothing to notice it. Every type in the consensus wire union is now priced explicitly and an unknown type is refused a price — dropped locally, never a PeerError, since a version skew says nothing about the sender. The doc comment now states the contract narrowly: the cost covers the direct staged signature verifications only, not threshold recovery/interpolation over a vote set (types/vote_set.go) and not the ABCI VerifyVoteExtension round-trip. The clock seam covers the waiting path. WithRateLimitClock only reached AllowN, access timestamps and GC; with drop=false the limiter still called WaitN(ctx, 1), which reads the wall clock internally (so an injected clock could not release it) and discarded the caller's nTokens entirely, silently dropping cost weighting on that path. It is replaced by a ReserveN-based wait metered against the injected clock, charging the full weight and refunding the reservation when the caller's context is cancelled. The prevote row of the cost table is now documented as the conditional it is: charging 1 regardless of declared extensions is safe only because types.Vote.ValidateBasic rejects extensions on anything but a precommit for a real block, and MsgFromProto runs it before dispatch. A test pins that dependency so deleting the validation cannot silently turn a prevote into a 33x undercharge. Also drops release-status narration from the peer-vote-rate-limit default comment; the provisional status of 600 lives in the spec. Red → green: * TestVoteRateBurstDoesNotScaleWithLimit — ✖ "expected 1200, actual 12000" at a tenfold rate, and 120 at a tenth → ✔ * TestVoteRateBurstBoundsFreshPeerAggregate — ✖ "76800 is not less than 20000" → ✔ * TestPeerMessageCost_RefusesUnrecognisedMessage — ✖ "An error is expected but got nil" (priced at the floor) → ✔ * TestRateLimitWaitPathChargesNTokens (was TestRateLimitWaitPathIgnoresNTokens, which pinned the defect) — ✖ "9999.015583 is not less than 5100" for a 5000-token message → ✔ * TestRateLimit_WaitPathRefillsOnInjectedClock — ✖ hung until the 2-minute test timeout: the wait never registered on the injected clock → ✔ * TestPrevoteWithExtensionsRejectedBeforeVerification — passes as a guard; verified non-tautological by deleting the "unexpected vote extensions" check in types/vote.go, which turns it ✖ "An error is expected but got nil" Verified: go build ./... clean, go vet clean, config, internal/p2p/client and internal/consensus green with -race. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): record the chosen per-peer vote burst The spec asked for a burst sized independently of the rate but never named a value, leaving it out of sync with the implementation. Record 200 work units and the reasoning: it covers roughly two seconds of an honest peer's heaviest gossip while keeping the aggregate a fresh peer set can front-load below the shared queue's capacity. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(consensus): fold piece 2 review findings back into the plan The fairness review surfaced two things the plan did not account for. The evidence channel is undefended and was owned by no piece: two signature verifications per message, no rate limit at all, and de-duplication by hash so that flipping one signature byte forces the work to be redone. Added as a Phase 1 item. Validator connection hardening also has to raise how many honest peers we connect to, not only stop the ones we have from being evicted. We dial twelve of sixty-eight slots and the rest can be taken from a single host with free identities, so the honest share is capped no matter how fairly the work is scheduled. Records the fairness form decision and its arithmetic, and adds an open item on whether removing the double verification has to move out of Phase 2, since honest demand alone already exceeds the budget in normal operation. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(p2p): reserve connection slots for current-quorum validators Validator connection protection was attached to the dial action rather than to the validator's identity, which left it absent exactly where it matters. `routerDashDialer.ConnectAsync` sets `MutableScore = PeerScorePersistent` but never the `Persistent` flag, so `Score()` caps at `MaxInt16-1`, the value is ephemeral, and every peer error decrements it. Worse, `ConnectAsync` is only reached for validators we dial: `filterAddresses` skips any validator that is already connected, and DIP-6 is a directed overlay, so the neighbours at `(i-2^k) mod n` only ever connect inwards — as does every neighbour after a restart, since the remote retries at 250ms and wins the race against our startup. Those validators sit at score 0, and `findUpgradeCandidate` needs only a strictly lower score, so one `PeerError` (score -1) let any fresh score-0 Sybil evict them. `updateConnections()` runs only on validator-set updates, so the evicted validator was not redialed until the next quorum rotation. Introduce a reserved connection slot, keyed on the node ID the handshake authenticates. `PeerManager.SetProtectedPeers` replaces the reserved set; `configurePeer` derives `peerInfo.Protected` from it, so an inbound connection from a never-before-seen quorum member is covered on arrival. A reserved slot ranks as persistent, so it cannot be eroded by error scoring or dial failures, cannot be selected for eviction to make room for another peer, and wins an upgrade when the node is full. `ValidatorConnExecutor` publishes the set for the quorum members it must stay connected to, whichever side dials. Two findings from spec review are folded in: - `router.routeChannel` disconnected *any* erroring peer whenever `len(connected) >= MaxConnected`, ignoring rank — and a flood is precisely what puts a node at its ceiling, so this alone would have kept the one-error eviction alive. `ShouldDisconnectOnError` now spares peers holding a reserved slot from pressure-driven shedding; fatal errors still disconnect them. - Reservations are granted only to node IDs bound to the address the chain published (inline in the validator address, or from the TCP resolver's secret-connection handshake). `resolveNodeID` also answers from the address book, which peer exchange lets any peer write, so an attacker could otherwise PEX-inject `attackerNodeID@validatorIP:port` and be handed the validator's slot. Address-book answers remain good enough to dial. Design, verification of each claim against the code, and the rejected alternatives (per-/24 conn-tracker keys, raising MaxOutgoingConnections, a numeric inbound reservation) are in docs/CONSENSUS_DOS_PIECE3B_SPEC.md. Tests would have caught this in CI: TestProtectedValidatorSurvivesFloodErrorsAndRestart score -100 -> persistent TestProtectedValidatorDisplacesFloodOnInbound refused -> admitted TestProtectedPeersReplacedOnQuorumChange 0 -> persistent TestReservedSlotIsNotShedUnderConnectionPressure shed -> kept Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(dash): reserve slots for the inbound half of the DIP-6 overlay Reserving slots only for the validators this node dials protects half of its quorum neighbourhood. DIP-6 is a directed overlay: the member at sorted index i dials (i+2^k)%n, so the members that dial it are the ones at (i-2^k)%n — a different set, which `selectValidators` never returns and which is therefore only ever known through the connection it opens. Those are exactly the slots a connection flood takes, and the honest share stays pinned to the outbound half. Add `SelectInboundValidators` as the inverse of `SelectValidators`: same sorted list, same offsets, walked backwards. The two share one implementation parameterised by direction, so they cannot drift apart, and the index arithmetic moves from float to integer because Go's % keeps the sign of the dividend and a negative offset needs the result brought back into range. `ValidatorConnExecutor` now reserves the union of both halves. A failure to compute the inbound half keeps the outbound reservations rather than dropping everything. The union is small and bounded: at most 2*floor(log2(n-1)) identities, 12 for a 100-member LLMQ and fewer where the halves overlap (at n=64, -32 is +32 mod 64, giving 11), and at most n-1 <= 3 below the DIP-6 minimum, which is what keeps 4-node testnets safe. Guaranteed honest connection slots under a flood go from 0 — every neighbour was removable with one peer error before the previous commit — to the whole 12-member DIP-6 neighbourhood, plus the 6 outbound slots an attacker can only reach by poisoning the address book: >= 18 of 68. Test would have caught this in CI: the inverse property test (j in forward(i) <=> i in inverse(j)) fails on every quorum size at or above the DIP-6 minimum when the inbound selection is anything but the true inverse. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): harden slot reservations after review Independent security and liveness review of the previous two commits found three ways the mechanism could be turned against the node it protects. Reservations no longer run node ID resolution at all; they use only the node ID the chain published with the validator address. Resolution consults the address book first, and peer exchange lets any connected peer put an arbitrary node ID at an arbitrary address there, so an attacker could advertise `attackerID@validatorIP:port` and have the resolver name its own identity for a real validator — either claiming the slot or, since the answer was then treated as unauthenticated, stripping the reservation from that validator on demand. A per-target kill switch on the mitigation, for one PEX message. Resolution is also far too expensive to run here: `WithValidatorSetUpdate` publishes the full validator set on every committed block, so `updateConnections` runs per block, not per rotation. Resolving the inbound half would have added a blocking 1s dial plus 1s handshake per unresolved member, per block, on the event-bus subscriber goroutine — for peers this node never dials. A subscriber that falls behind is evicted by the pubsub server and never resubscribes, which would have frozen the reserved set on a rotated-out quorum. A rejected reservation set is now dropped instead of leaving the previous one in force, which was stale protection of exactly the kind keeping reservations out of the peer store is meant to prevent. A malformed node ID no longer costs the rest of the set its reservations, and the size ceiling now counts the configured persistent peers that hold a slot for the same reason. Score changes are no longer recorded for a peer holding a reservation. They were invisible while it lasted but still accumulated, so an attacker that could not shed a reserved validator could bank errors against it and have it drop to the bottom of the ranking the moment its quorum rotated out. Also: remove `HasMaxPeerCapacity`, dead since the previous commit replaced its only caller. Review found one test that could not fail — the hard-ceiling test passed with protection removed, because the flood peers it left at score -1 could be out-ranked by anyone. It now restores them to a clean rank first, so only a reservation can win the admission. New tests cover the rejected-set, malformed and self ID paths, and the seed-node incoming-connection timer. One review suggestion was rejected: keeping a connection to a member that moved to the half of the overlay that dials us. Holding an outbound connection to a peer DIP-6 says should dial us contradicts the overlay's semantics, and the existing executor tests encode that. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): serve peer messages in per-peer lanes by deficit round robin Every peer shared one arrival-ordered queue of 20 000 slots, drained by a single reader, so service was proportional to how much a peer sent. A peer flooding cheap messages could hold up the vote the node needed to make progress, however honest its sender. Give each peer a lane of its own and serve the lanes by deficit round robin. Plain round robin is not enough here: message cost varies by two orders of magnitude, so a rotation blind to cost lets a lane of maximum-cost precommits take 66 times an honest lane's work per turn. A per-lane deficit counter with a one-unit quantum makes the rotation fair in verification work instead of in message count, and bounds what other lanes can complete ahead of a head of cost W at lanes x max(quantum, W). Also restores the invariant that internal progress is independent of the peer path. The affordability wait introduced in 206421997 ran on the state goroutine because there was no scheduler to put it on; that goroutine also serves this node's own messages and the timeout ticker, so a saturated budget delayed timeouts by up to C_max/R against a one-second vote timeout. The wait now runs on the scheduler, and the state-goroutine check remains only for messages that did not come through the scheduler. Handing over one peer message at a time is what makes reading the budget on another goroutine sound, since a message's charges are made while it is verified. And fixes the non-punitive invariant. chanQueue.send reported a full queue as an error, which reactor.go turned into a p2p.PeerError and peerManager.Errored turned into eviction. With 20 000 shared slots that path was near-dead; with bounded lanes it becomes routine, and the peer that reaches capacity at full load is the honest one. Shedding and a cancelled context now both return nil. Lane capacity is 512 messages: a whole 21 MB proposal block arrives as 337 parts, and a peer's instantaneous vote allowance is 200 work units of the cheapest messages. The lanes are bounded in aggregate at the size of the queue they replace, so per-peer scheduling does not raise the memory a flood can pin; once several dozen lanes are busy that aggregate binds first, and a single peer can no longer hold a whole block's parts. Lanes are retired when a peer disconnects and reclaimed after 60 seconds idle, so an attacker cycling through free node identities cannot grow the rotation without bound. Overflow drops the oldest message, never the arriving one: consensus messages are only valid for the height and round they were made in, so dropping the newest would spend a peer's turns on guaranteed-stale messages and mute it for rounds with no attacker involved. Implements docs/CONSENSUS_DOS_PIECE2_SPEC.md §5c, restores I6 and fixes I4. Test evidence, per invariant: - I4: TestSheddingAPeerMessageNeverReportsThePeer/lane_overflow fails against a send that returns "msg queue is full" ("the peer was reported for a message this node chose to shed"), passes here. - DRR: TestPeerLanesBoundWorkAheadOfAHead/"cheap head, expensive flood" fails against cost-blind round robin ("528" is not less than or equal to "8"), passes here. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(consensus): prove peer scheduling holds end to end The lane unit tests exercise the rotation directly. These drive real messages through the reactor, the scheduler, the write-ahead log and the consensus state machine, so they assert what the invariants are actually about rather than what the scheduler reports. - An honest peer's vote completes VERIFICATION — enters the vote set, not merely gets dispatched — while 67 attacker lanes hold the verification budget at zero with forged commits, within the round timeout it belongs to. Both a cheap head and the heaviest precommit Dash validators produce, since only the expensive one distinguishes a scheduler that waits for budget from one that passes over what it cannot afford right now. - Shedding a peer message, whether at the lane or at the peer's own rate limiter, reaches neither the reactor's error path nor the write-ahead log nor the vote set, while a genuinely malformed message from another peer is still reported — so the test cannot pass by never reaching the scheduler. - This node's own messages and its round timeouts are served while the peer path is blocked on the verification budget. - A peer message the dispatcher finds no handler for still lets the scheduler serve the peer's next message. - The node stops while the scheduler is parked on the verification budget. - A peer going down retires its lane, and reconnecting starts it over. Timing is asserted against a fake clock advanced at exactly the rate the verification budget refills, so what the tests measure is the delay the budget imposes and nothing else. Work that rides inside a dispatch without being charged — threshold recovery and the vote-extension round-trip — is invisible to that measurement; bounding it is what the piece's load test is for. Red-before-green evidence: - The honest-vote test fails against a budget check that peeks instead of waiting ("the honest peer's vote was never verified while other peers flooded"), which is the design docs/CONSENSUS_DOS_PIECE2_SPEC.md §5b rejects, and passes here. - The dispatcher-drop test fails when the finished-message report is made from the middleware instead of the dispatch loop, because a message that reaches no middleware then never reports and the scheduler stops serving peers for good. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): fold peer-scheduling review findings back in Findings from independent liveness, concurrency and spec-conformance reviews of the per-peer scheduler. Correctness and robustness: - A budget that loses the ability to defer a message is now a compile error. Both callers ask for it through a type assertion and quietly stop deferring when it fails, which would give up whole-message atomicity with every test still green. - The reactor retires a lane outside its own lock, so the lane lock stays a leaf and cannot take part in a cycle if a future handler ever queues a message while holding the reactor's. - The consensus goroutine now stops the message queue when it leaves on a dispatch error, instead of stranding the queue's reader goroutines. Tests that asserted less than they claimed: - The aggregate bound over all charges is asserted against the real bucket over the flood, which matters more now that the budget is read on the scheduler goroutine and charged on another: the bound rests on the handoff between them rather than on one goroutine doing both. - The flood's premise is asserted rather than assumed: a commit an attacker cannot make good on is charged exactly one verification, and it is that price that decides how many turns it takes to hold the budget down. - Two assertions in the shed test could not fail, since nothing consumes the queue there. Replaced with what that setup can actually show, and the write-ahead log claim moved to the budget test, where a message really is dropped between the queue and the log. - The honest-vote test waited four minutes for a failure, twice, which is longer than the repo's own test timeout — a regression would have shown up as a timeout rather than as the assertion message. Now thirty seconds. Comments that were wrong or claimed too much: - The wait for budget takes no tokens, so it is not the reservation the old comment described; what makes the charges that follow safe is that only one peer message is ever in flight. - A lane's capacity is not a reservation: the aggregate bound is the smaller of the two once several dozen lanes are busy, so under a wide flood a single peer can no longer hold a whole block's parts and the round times out. - The deficit bound scales with the head's own cost. The heaviest precommit Dash validators produce is served inside the propose timeout but not inside the vote timeout; the test now says so instead of quietly grading it against the looser one. - Drop-oldest is argued from time-validity, which holds for votes and commits but not for block parts; the block-part case is now argued on its own terms. - The rotation is bounded at every instant, but the lane table only across a reclamation interval. The identity-rotation test claimed both. - An expensive head against a cheap flood bounds the wait but does not tell deficit round robin apart from plain round robin, which serves such a head sooner. Only the cheap-head-against-expensive-flood case does. - Which functions require the lane lock, that the scheduler's clock does not reach the budget's, and that routing every message with a peer to the peer side is what the finished-message report depends on. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(consensus): correct the fairness bound to account for message cost The stated bound assumed every competing message was the cheapest possible, and was then used as the acceptance criterion. The real bound scales with the head message's own verification cost, so a realistic precommit lands around two seconds rather than the fifth of a second quoted, which is longer than the vote timeout. No work-conserving fair scheduler can do better than the fair share, so the criterion as written could never have been met. The measured value is now recorded, the test grades against the propose timeout, and the three inputs that can actually close the gap are named: a higher verification rate, fewer lanes an attacker can hold, or removing the second verification pass. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(consensus): charge proposal verification to the verification budget Proposal signature verification is one BLS pairing on the consensus goroutine, and it was the one peer-reachable pairing the node-wide verification budget did not price: budgetedMessageCost returned 0 for a proposal, so the peer scheduler never gated one and nothing drew a permit before the check. Nothing de-duplicates a proposal that fails verification either -- rs.Proposal is set only by a proposal that passes -- so every forged copy is verified again. The per-peer data limit admits ~100 proposals/s/peer (PeerDataRateLimit 500 / proposalTokenCost 5) with a 200-message burst, so a handful of peers saturate a ~370 pairings/s verifier while the honest proposer's message waits behind rotating lanes, keeping rs.Proposal nil and the flood self-sustaining. Price a proposal at one work unit and draw the permit where the pairing is, so the gate the scheduler applies and the work actually drawn agree. The permit is taken after proposer selection (the non-validator path runs no pairing and is not charged) and before the sign-digest derivation, so that hashing is inside the bound too. Refusal returns the existing budget-exhausted sentinel, which the logging middleware already treats as a non-punitive local drop: no peer error, no WAL record. Red -> green: TestProposalFloodCannotExceedTheVerificationBudget dispatches 50 forged proposals against a drained budget. before: 50 WAL writes, 50 signature checks after: 0 WAL writes, 0 signature checks; one admitted after refill Refs docs/CONSENSUS_DOS_PLAN.md §1, §2.3; docs/CONSENSUS_DOS_PIECE2_SPEC.md §5a. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(consensus): stop peer-triggerable rejections from writing Error logs Two log-amplification leaks on the proposal and block-part paths. A proposal that fails signature verification wrote an Error line that embedded the whole proposal — an attacker-controlled, unbounded payload — and nothing de-duplicates a failing proposal, so one line was written per copy. The line is now Debug and carries only the round and the key the check was made against; nothing that came off the wire. Block-part proof failures, and the remaining proposal rejections (POL round, core-chain height, blockID-vs-commit mismatch, unverifiable proposal), all reached the logging middleware unclassified and were written at Error. Every one of them is free for a peer to produce, so they join the floodable set and are logged at Debug. Classification only selects a log level; it does not change whether a peer error is raised, and neither of these paths raises one. Red -> green: TestProposalRejectionsAreFloodable, TestBlockPartRejectionsAreFloodable and TestRejectedProposalIsNotEchoedIntoTheLog all fail before the change (8 unclassified errors; an Error line carrying the forged signature). Refs docs/CONSENSUS_DOS_PLAN.md §2.7. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(p2p): fail a rate-limit wait fast when the caller cannot wait it out Three review follow-ups. The rewritten wait path lost rate.Limiter.WaitN's fast-fail. WaitN reserves against the caller's remaining context budget and refuses up front when the delay exceeds it; the rewrite reserved without a limit and then blocked on the timer or ctx, so a caller with a short deadline was parked for the whole deadline — holding the reserved tokens, and on a shared channel goroutine every message behind it — only to be refused anyway. It also lost the distinction between "the bucket cannot serve you in time" and "you were cancelled". Restore both: compare the delay against the deadline, cancel the reservation (which refunds in full, since it has not come due) and return a distinct error. The fresh-peer burst aggregate test used 64 connections. The peer manager may hold MaxConnected plus MaxConnectedUpgrade at once, and node/setup.go passes 4 for the latter, so the ceiling is 68; the burst comment in the consensus reactor claimed 64 for the same reason. Narrow two comments that claimed more scope than the code delivers: the data-channel limiter and proposalTokenCost bound what ONE peer can spend, not the aggregate across peers, which is the node-wide verification budget's job. Red -> green: TestRateLimit_WaitFailsFastPastTheCallerDeadline before: returns after 301ms wrapping context.DeadlineExceeded after: returns up front with the limiter's own refusal Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound the hashing a peer can force with bad block-part proofs The part-set caps bound how many parts a node ACCEPTS. They say nothing about the ones it rejects: a proof that does not check out leaves the slot empty, so the next copy aimed at the same in-range index is hashed from scratch, and verifying a proof hashes the whole ~64 kB leaf before it can find the mismatch. Nothing charged for that work. Add a per-peer allowance denominated in the bytes of leaf hashing spent on proofs that fail. A part is refused before verification once its sender has spent its allowance; only an actual failure is charged, so a peer whose parts verify never draws on it. Per peer rather than node-wide, deliberately. A node-wide bucket would let one peer's garbage stop this node assembling a block at all, trading a bounded CPU cost for an unbounded liveness one. The node-wide bound follows from the connection ceiling instead: 68 slots x 256 KiB/s is a low single-digit percentage of one core, asserted by TestBlockPartProofBudgetNodeWideBound. An accepted part clears what its sender has spent. Honest proof failures come in runs -- a round this node has moved past -- mixed with parts that do verify, and it is the mixture that must not cost a peer the parts we need from it. The burst additionally absorbs 32 full-size failures before anything is refused. Refusal is a silent local drop: no error, no peer error, no WAL record, counted on the new consensus_block_part_proof_drops metric. Red -> green: TestRepeatedInvalidBlockPartProofsAreBounded, with the gate disabled, re-hashes the same invalid part 1000 times (65 MB of hashing from one peer, and it does not stop there); with it, the run ends inside the burst. Refs docs/CONSENSUS_DOS_PLAN.md §2.5. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(consensus): bound the State and VoteSetBits channels Neither channel verifies a signature, so the node-wide verification budget does not bound them at all; nothing else did either. Three problems, all reachable by any connected peer. Add a per-peer ceiling across both channels AND a node-wide one. Neither substitutes for the other: the per-peer allowance keeps one sender from occupying the channel goroutine, and the aggregate keeps that guarantee from being bought around with fresh node identities, which are free. Both sit well above honest gossip -- a peer broadcasts a HasVote per vote it adds, plus round-step messages and up to four VoteSetMaj23 per gossip tick -- and both drop silently: the peer at its allowance under load is as likely to be honest and gossiping hard as hostile. Price VoteSetMaj23 above the rest. It is the one message here that asks this node for work: it makes us build a bit array over every validator, up to MaxVotesCount bits, and send it back -- more than it cost to ask. Suppress repeats. A peer's gossip loop resends the same claim on every tick, and the answer comes from our own vote set alone, so until that vote set gains a vote the peer has not been told about, answering again conveys nothing. Tracked per peer by claim plus the number of votes the last answer carried; votes are only ever added, so an unchanged count means an unchanged answer, and the peer still learns of every vote we gain. Bound the response send. It went out with the caller's context, so a router that could not take it parked the goroutine serving every peer's state messages. It now has a short deadline of its own and gives up quietly; the peer asks again on its next tick. Red -> green, with each mechanism disabled in turn: per-peer ceiling: 400000 messages admitted from one peer against a 4000 ceiling aggregate: the fresh-identity loop never terminates suppression: an unchanged claim is answered every time bounded send: the test hangs until the 2m timeout Refs docs/CONSENSUS_DOS_PLAN.md §2.4. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(evidence): spec bounding the evidence channel Plan item §2.10. Records what was verified against the code rather than assumed, including three findings the plan did not have: the reactor evicts a peer on the first evidence that fails verification, evidence gossip is retry-based (so a receive-side drop is a delay, not a loss), and signature verification is skipped entirely when the validator set at the evidence height carries no public keys. That last one dictates the whole shape of the de-duplication: acceptance alone cannot be enough to remember an equivocation, or an attacker could claim a real equivocation's identity with garbage signatures and lock the genuine proof out for good. Reviewed by independent security and correctness lenses before any code; their findings are folded in and the pre-existing issues they surfaced are recorded in §6 for other owners. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(evidence): de-duplicate evidence by what it alleges, not how it is encoded De-duplication keyed on the evidence hash, which covers the signature bytes, so flipping one byte of a signature produced a piece of evidence the node had never seen and bought the sender a full re-verification — two BLS pairings plus a block-meta and a validator-set lookup — for the cost of one byte. Nothing rate-limited the evidence channel, so the flood was free to repeat. Remember instead what a piece of evidence alleges: the height, round and step, the accused validator, and the two conflicting block IDs. A re-encoded copy of an equivocation we have already proven is then recognised as the same accusation and costs a map lookup. The memory only ever records evidence whose signatures were actually checked. VerifyDuplicateVote skips them when the validator set at the evidence height carries no public keys, and such evidence is stored anyway — so remembering on acceptance alone would have handed an attacker an evidence-suppression tool: equivocations are public, and a forged copy could claim the identity before the genuine proof arrived. Evidence is a safety mechanism; suppressing it is worse than the flood. The set is bounded at 1024 entries and forgets the lowest heights first, which are the ones closest to ageing out of the window anyway. Forgetting only forfeits a free refusal, so it can never cost correctness. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(evidence): bound the work an inbound evidence message can cost The evidence channel had no ceiling of any kind. Every message that got past the hash de-duplication paid for two BLS pairings and two disk lookups on the evidence reactor's goroutine, and nothing limited how many a peer could send. Admit inbound evidence through a gate ordered cheapest-refusal-first: votes that cannot describe one equivocation, vote extensions beyond what a real vote may carry, heights the block store cannot serve, and equivocations we already hold proof of are all refused before anything is spent — including before the message is hashed for the pool's duplicate check, which is itself a full marshal and digest of a message that may approach the channel's 1 MB limit. Only what survives is charged, in pairings, against a per-peer bucket and a node-wide one. Genuine evidence still lands. Each peer has its own bucket, so an attacker cannot spend an honest peer's allowance however many identities it holds; the node-wide rate is set above what every peer together may spend, so against a fixed peer set it refills faster than it drains and stops being the binding constraint; and it is inspected before the per-peer bucket is charged, so a congested node never bills a peer for capacity it then denies. Where that is not enou…
shumkov
added a commit
that referenced
this pull request
Aug 17, 2026
…#17 could not Merging v1.6-dev brings in TestReactor_Backfill_UnknownVoteExtensionTypeAbortsUnattributed from #17. It fails, and it should: it asserted the mis-attribution this branch removed. #17 recorded the limitation deliberately rather than as an oversight. Its doc comment spelled out that a commit refused while decoding was dropped, that the fetch could only read the resulting silence as a slow peer, and that the run therefore ended on the retry budget every peer shares with the offending peer unnamed - "enough such answers end the backfill while honest peers are still available". Its assertion said the same in one line: ErrorContains "max retries", explained as "the abort is charged to the shared retry budget rather than to the peer that caused it". An unknown vote-extension type is the third member of the decode class this branch fixed, alongside the out-of-range quorum type and the block-protocol mismatch, so the limitation is gone: the response is now delivered to the fetcher as a refusal, the peer is withdrawn from the run and reported, and the run ends naming the cause. The assertions are inverted, not relaxed. Both original safety assertions are kept - the run errors rather than panics, and nothing reaches the block store - and the "max retries" assertion becomes three stronger ones: the failure names the extension type, it explicitly does not blame the budget, and the peer that sent it is reported by name. Renamed accordingly, since AbortsUnattributed asserts the opposite of what now happens. The report is asserted non-fatal, which this cause makes the clearest case for: an extension type undefined in this build is defined by whatever release introduces it, so a peer failing the check is as likely to be an honest node one release ahead as a malicious one. UPGRADING.md already records that adding a type has exactly this effect. Mutation-checked rather than observed passing: restoring the dropped-decode-error behaviour makes it fail with "max retries to fetch valid blocks exceeded (20); target height: 10, height reached: 15" - the string #17 asserted, produced by the code path #17 described. No production code changed. internal/statesync and internal/blocksync green under -race -tags deadlock; no golangci-lint delta across either package. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bumps github.com/cosmos/iavl from 0.15.0-rc5 to 0.15.0.
Release notes
Sourced from github.com/cosmos/iavl's releases.
Changelog
Sourced from github.com/cosmos/iavl's changelog.
... (truncated)
Commits
f5c104dchangelog: release 0.15.0 (#335)775339btest: run slow tests without race detector in CI (#338)4342f3fgo.mod: upgrade tendermint and other deps (#334)ec1e290docker: ci (#332)Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting
@dependabot rebase.Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR:
@dependabot rebasewill rebase this PR@dependabot recreatewill recreate this PR, overwriting any edits that have been made to it@dependabot mergewill merge this PR after your CI passes on it@dependabot squash and mergewill squash and merge this PR after your CI passes on it@dependabot cancel mergewill cancel a previously requested merge and block automerging@dependabot reopenwill reopen this PR if it is closed@dependabot closewill close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually@dependabot ignore this major versionwill close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)@dependabot ignore this minor versionwill close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)@dependabot ignore this dependencywill close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)