Skip to content

fix(dash-spv): stop banning peers on decode failures - #1593

Draft
xdustinface wants to merge 11 commits into
devfrom
fix/no-ban-on-decode-failure
Draft

xdustinface wants to merge 11 commits into
devfrom
fix/no-ban-on-decode-failure

Conversation

@xdustinface

@xdustinface xdustinface commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Any message that failed to decode banned its sender for 24 hours and dropped the connection, and so did a headers2 message that failed to decompress. Dash Core only logs a message it cannot parse, so a bug in our decoder or a format change in a known message banned every honest peer that sent it. headers2 is chosen once per connection, so there was no way back to plain headers either.

RawNetworkMessageCodec now consumes a frame that is buffered whole but fails to decode, and the v2 decoder does the same for a decrypted packet whose message fails to parse. The peer reader skips such a message and keeps the connection. Only the first skip of a connection is logged as a warning, and a peer that sends 100 undecodable frames on one connection is disconnected and kicked for 10 minutes. A stream that cannot be resynced, a declared length over MAX_MSG_SIZE or a v2 packet that fails to decrypt, still ends the connection but no longer bans.

A skipped reply would leave its request owed until the request timeout kicked the peer. The skipped frame now carries its command and size, the ledger settles the oldest owed reply of that command, and the broker re-queues the matching request within the existing attempt limit. A bad cfilter counts as an answer without closing its batch, and the filters pipeline requests an incomplete batch again.

A headers2 decompression failure disconnects without a ban and records the address, so its next connection negotiates plain headers. The list keeps the latest 256 addresses.

The handshake ban wipe the issue also describes was fixed separately in #1483.

Closes #1239

`RawNetworkMessageCodec` returned the error of a frame that failed to decode, such as one with a bad checksum or a payload that does not parse, without consuming it. The frame boundary is known at that point, yet a caller could not go on with the next frame.

The codec now consumes such a frame before it returns the error, so a caller can skip it and keep reading. A declared payload length over `MAX_MSG_SIZE` still leaves the buffer untouched, since no frame boundary follows it. Callers that stop at the first error, as `FramedRead` does, see no difference.
The peer reader banned the sender for 24 hours and disconnected on any decode error that was not I/O, such as a bad checksum or a `headers` payload with a non-zero transaction count. Dash Core only logs a message it cannot parse, so a bug in our decoder or a format change in a known message banned every honest peer that sent it.

A frame that is buffered whole and fails to decode is now skipped with a warning, and the reader goes on with the next one. Over V1 the codec consumes such a frame, over V2 a decrypted payload that fails to parse is skipped. A stream that cannot be resynced, such as a declared length over the limit or a V2 packet that fails authentication, still ends the connection, but without a ban.

Fixes #1239
A `headers2` message that failed to decompress banned the peer for 24 hours. headers2 is chosen once per connection at the handshake, and Dash Core cannot be told to stop sending it on a live connection, so there was no way back to plain headers for that peer. A bug in our decompression would ban every peer that serves headers2.

The connection is now dropped without a ban and the address is remembered in the network state. Its next connection announces `sendheaders` instead of `sendheaders2` and sends plain `getheaders`, so the peer answers with plain headers.

Fixes #1239
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

This pull request is a draft, so Manki does not review it automatically. Marking it ready for review starts automatic reviews. Until then, someone with write access to this repository can tick a box below: Review this draft reviews the current commit once, Deeper review does so with more effort, and Review every push reviews it now and again after each push.

@coderabbitai

coderabbitai Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 11m 45s

Planner (6s)
    feat · 343 lines · 2 agents
    judge effort: high

Review (behavior · full): 15 findings
    ✅ Claude Opus 5.5 · high: 3 findings (3m 33s)
    ✅ GPT 6.2 Sol · high: 11 findings (3m 53s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 16 of 16 done, 1 finding (1m 12s)
    ✅ Second reads: 1 of 1 done (1m 15s)

Judge (5m 27s)
    graded 15 findings: 10 kept · 4 dropped · 1 merged
    dropped, as the finders filed them: 3 blockers · 1 warning
    refuter: 3 checked · 3 confirmed
    origin checks: 3 checked
    sweeps: 1 of 1 done (11s)

Posted: 5 findings
    1 blocker · 1 warning · 3 suggestions
    not posted: 4 over the review.notes limit · 1 rare trigger

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 60% (resets 2026-12-04 20:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Kept: "A reply that fails to decode still gets its peer kicked and banned once the request times out" (warning): "warning. The new Frame::Skipped arm at dash-spv/src/network/peer.rs:783 only logs. ledger.settle at :795 runs only for Frame::Message, and Skipped carries no command or size (transport/mod.rs:18). The owed reply therefore stays in awaited until the broker expires the request. The timeout monitor then bans culprits with Ban::Kicked at manager.rs:1317 and requeues the request to the next peer, which fails the same way. Whether judge.judge picks this peer as a culprit is not shown, so that is listed as a doubt. Even if it does, the finding fails test 3. The reply cannot be used either way, and the extra harm is a 10-minute kick plus a timeout delay, not lost data or a wrong result. It still contradicts the stated aim of no longer punishing peers for our own decode failures.
    Refutation confirmed: The Frame::Skipped arm only logs. Neither ledger.settle nor broker.progress/arrived runs for it, so the request stays OnWire with stale last_progress. Broker::expire then names the peer as a culprit, StallJudge::judge kicks it once our link is shown to work, and the monitor bans it with Ban::Kicked. Rule checked: A request stays owed and its peer is blamed after a timeout unless the broker records progress or an answer, and the broker records that only for decoded messages that reach the inbound channel.
  • Premise "judge.judge in dash-spv/src/network/manager.rs returns a peer as a culprit when the broker expires its request and the only bytes the peer sent for it were a frame the reader skipped" confirmed. expire returns the peer with its last_progress as the start of its silence, since nothing refreshes it for a skipped frame. judge puts that peer in silent once uptime since then exceeds its timeout (or downtime exceeds LINK_STALL_TIMEOUTS) and returns it as a culprit when kick pacing allows. It is banned unless it was kicked without a witness.
    Pair refutation confirmed: The reader logs the skipped frame without settling the ledger or notifying the broker. The timeout judge can therefore kick and ban the peer if the link remains active; it does not ban an unwitnessed kick, and the code does not establish that the next peer sends the same reply. Rule checked: Receiving a complete frame does not satisfy a request unless the receive path records it as an answer.
  • Premise "judge.judge in dash-spv/src/network/manager.rs returns a peer as a culprit when the broker expires its request and the only bytes the peer sent for it were a frame the reader skipped" confirmed. For an early attempt, the broker can nominate the peer despite the skipped reply, and the judge returns it after enough witnessed link uptime if it is next in line to be kicked.", trigger 5 and harm 6 of 10: "It takes a reply format change, or a parse bug, in a solicited message such as headers, which is uncommon but is exactly the issue scenario."
  • Kept: "A peer can flood the log with one warning per bad frame and is never dropped" (blocker): "blocker cell, held at warning by a doubt. The PR removes the ban and disconnect that followed the first undecodable frame. The new arm at peer.rs:783-790 logs at warn and keeps reading, with no count or limit. The codec now consumes every whole bad frame (dash/src/network/message.rs:924-927), so each frame becomes one Skipped and one log line longer than the frame itself. A checksum failure also logs a second warning in RawNetworkMessage decoding. The LogFileConfig shown at logging.rs:53-55 only caps archived files. Whether the current run log is unbounded is not shown, so it is listed as a doubt. Dash Core logs these drops only under the BCLog::NET debug category (dashpay/dash:src/net.cpp:825).
    Refutation confirmed: The changed reader arm logs a warning for every skipped frame and keeps reading. Before this PR, the same decode error led to a ban and a disconnect. The codec now consumes each whole bad frame, so a peer can send header-only frames with a bad checksum forever. Each one adds two warn lines to run.log, and that file is only rotated at startup. Rule checked: A reader loop that logs at a level the default filter passes, once per frame a remote peer sends, with no count, limit or disconnect, writes log output in proportion to what the peer sends. The active log file's size then has no bound within a run.
  • Premise "The SPV client's file logging writes warn events of target dash_spv::network to a run log whose size nothing in dash-spv/src/logging.rs limits" confirmed. File logging uses the configured level, which is info by default and so passes warn. It writes to a run.log created once at startup. Rotation and cleanup only run at startup and only count archived files, so nothing in logging.rs limits the size of the active file.
    Pair refutation confirmed: The PR turns fully consumed decode errors into skips that emit a warning without disconnecting the peer; Dash Core also skips checksum failures, but logs them under BCLog::NET. The default SPV CLI sends these warnings to run.log, and the lossy writer can drop lines when its queue fills but does not cap the file's size. Rule checked: A receive loop that logs each rejected frame and continues without a rate limit does logging work proportional to the number of rejected frames.
  • Premise "The SPV client's file logging writes warn events of target dash_spv::network to a run log whose size nothing in dash-spv/src/logging.rs limits" confirmed. The default CLI enables file logging at INFO, which admits WARN events for dash_spv::network, and logging setup rotates the previous run.log and limits only the number of archives before opening the uncapped active file."
  • Not listed, over the review.notes limit: "The new assertion message says the header was consumed, but the assertion checks that it was not" (suggestion): "note. assert_eq!(over.len(), 24, ...) at dash/src/network/message.rs:1016 checks that the header stays in the buffer. The codec returns before src.advance at :909-915, and the doc at :881-882 says the buffer is left as it is. The message says the opposite, which misleads whoever reads a failure."
  • Dropped: "Malformed frames can keep a dead peer in the connected set" (ignore): "ignore. last_seen at peer.rs:774 is refreshed by any frame the reader gets, before the match. A peer that ignores our pings can already keep the keepalive satisfied by sending any valid message, such as its own pings, which the reader answers at :797-800. Skipped frames give it no ability it did not already have. A peer that does not answer requests is still caught by the request timeout monitor."
  • Kept: "The header fallback cache grows with every distinct failing peer" (suggestion): "note. plain_headers (manager.rs:221) gains one SocketAddr per distinct peer whose headers2 fails to decompress (peer.rs:826), and nothing removes entries. Each entry is a few dozen bytes. Each one also needs a separate handshaked connection that sends a bad headers2, so the set stays tiny in any realistic run. A bound would be tidier, but nobody would notice the cost."
  • Not listed, its trigger is rated below review.min_warning_trigger: "A headers2 payload that fails to parse never triggers plain-header fallback" (warning): "warning. The fallback is recorded only when a parsed headers2 fails to decompress (peer.rs:826). A headers2 whose payload fails to parse is skipped instead. NetworkMessage::consensus_decode_payload fails at dash/src/network/message.rs:862, the frame becomes Frame::Skipped carrying only the error (peer.rs:137, v2.rs:106), and the reader only logs it at peer.rs:783. The peer is never added to plain_headers, so every reconnect asks for headers2 again and header sync from that peer never completes. This is a gap in the fix for the issue's headers2 fallback. The trigger needs a parser bug or a format change for honest peers, so rareTrigger is set.
    Refutation unsettled: It is true that a headers2 frame that fails to parse is only logged and never marks the peer for plain headers. But the Rust headers2 decoder reads exactly Dash Core's CompressibleBlockHeader serialization and accepts any flag byte under Core's own 8000-header cap, so only a malformed or truncated payload with a valid checksum, from a buggy or malicious peer, reaches this path, and falling back to plain headers would not help with such a peer. Rule checked: A decoder that accepts every byte sequence the reference implementation serializes, under the same count cap, can fail only on payloads an honest peer never sends.
  • Premise "This trigger happens in realistic use: when a peer sends a headers2 reply the client cannot parse, for example after a change in the headers2 format" unsettled. Dash Core's headers2 wire format matches the Rust decoder field for field: the same flag bits, set bit meaning the full field is sent, the same field order, and any flag byte accepted. The 8000-header cap equals Core's MAX_HEADERS_COMPRESSED_RESULT, so no headers2 an honest peer sends fails to parse, and no format change exists in the code in reach.
    Pair refutation confirmed: Both transports turn a fully framed payload parse error into a skip that the reader only logs, leaving compression enabled for that peer on reconnect. The tests supply a malformed plain headers payload and a headers2 payload that parses but fails decompression; neither establishes that a peer actually sends an unparseable headers2 reply. Rule checked: A payload decoder that returns only an error prevents downstream code from branching on the command, and a parse error never reaches decompression.
  • Premise "This trigger happens in realistic use: when a peer sends a headers2 reply the client cannot parse, for example after a change in the headers2 format" confirmed. On the code side, a peer's advertised service enables getheaders2, and an incoming headers2 reply is passed to the current payload parser without a format-compatibility check.", trigger 3 and harm 5 of 10: "It needs a headers2 payload that fails to parse rather than fails to decompress, which is a rarer subset of an already rare event."
  • Dropped: "V1 treats a wrong-network header as a recoverable frame boundary" (ignore): "ignore. TCP delivers an honest peer's frames in order, so the declared length always lands on the next frame boundary. A well-framed message with another network's magic decodes normally and is dropped by the magic check, as before. A misaligned stream can only come from the peer sending garbage itself. That affects only its own connection: each fake frame still needs a 4-byte checksum match to decode, and a fake length over MAX_MSG_SIZE disconnects it. No wrong message is accepted, and no other peer is affected."
  • Dropped: "The latency probe discards fatal read errors and proceeds as if the peer connected" (ignore): "ignore. The loop at peer.rs:684 ends on an error, EOF or timeout exactly as the old while let Ok(Some(Ok((raw, _)))) did. The PR only adds continue for a skipped frame. A probe that ends this way leaves lag_ms at 0, which is_bad_lag treats as bad (manager.rs:853). The peer is then turned away at manager.rs:941 rather than admitted, and the reader it was given stops on the next None. The remaining effect, dialed clearing a backoff, is unchanged and nobody would notice it."
  • Kept: "The public codec's skip behavior does not work through Tokio FramedRead" (suggestion): "note. The new doc at dash/src/network/message.rs:880-882 says a caller can skip a failed frame and decode the next one. That holds for a caller of decode directly, as SizedCodec is. Through FramedRead, the error is followed by None (tokio-util framed_impl.rs:164), and the seeds fetcher still returns the error (masternode-seeds-fetcher/src/peer.rs:64), as it did before. Nothing breaks for existing users, but the doc could say that the skip applies to direct decode calls."
  • Not listed, over the review.notes limit: "The fallback regression test can hang when no header reaches the subscriber" (suggestion): "note. headers.recv().await at manager.rs:2174 has no timeout, unlike the eventually waits around it. A regression would make the test hang until CI kills it instead of failing with a clear message. The test still fails, so this concerns how it is built."
  • Not listed, over the review.notes limit: "The new oversized-frame checks also pass before the fix" (suggestion): "note. The oversized length error is an io::Error (dash/src/network/message.rs:909-914), which the old code already exempted from the ban. So the a length over the limit case at manager.rs:2111 passes without the change. On V1, every non-I/O error is now turned into Skipped, so the removed ban branch at peer.rs:779 only matters for fatal V2 errors, such as a packet that fails authentication. No test drives that path, so restoring the ban would fail no test. The other two V1 cases do cover the skip."
  • Kept: "The loopback harness and the new tests duplicate Regtest frame encoding" (suggestion): "note. regtest_frame at manager.rs:2076 has the same body as the framed closure in answer_handshake at :1838. AGENTS.md requires extending an existing helper rather than writing a near copy. Moving the closure into regtest_frame and using it in both places removes the copy."
  • Dropped: "V2 decryption may receive a packet shorter than its authentication overhead" (ignore): "ignore. The packet length check and the decrypt_to_vec call at v2.rs:73-92 are unchanged by this PR, which only changes how a decrypted message that fails to parse is returned. The lead is about code the PR neither touches nor affects."
  • Not listed, over the review.notes limit: "Frame derives no Debug, unlike the crate's other outcome enums" (suggestion): "note. Frame at transport/mod.rs:14 has no derives. Both of its fields implement Debug, and similar outcome enums such as DiffOutcome derive it. Adding it would let a failing test print the frame it got. The code works without it."

Timing:

  • Parse: 7.3s
  • Review agents: 370.6s
  • Judge: 326.8s
  • Total: 704.8s

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

CI does not run on this PR while it is a draft. Someone with write access can start it here:

  • Run CI once on the current commit
  • Run CI on every push, starting now

Marking the PR ready for review also starts CI.

CI started for e32e805: Continuous integration, Pre-commit Checks, Sanitizer.

manki-review[bot]
manki-review Bot previously requested changes Dec 4, 2026

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Changes requested: 1 blocker, plus 1 warning and 3 suggestions in threads.

What blocks: Before this change, the first undecodable frame banned the peer. Now each one is skipped, the connection stays open, and tracing::warn! writes a line for it.


4 suggestions are not listed.


Checked and left out: 1 finding

Rare trigger, so not listed · 1 warning

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed 6612427, round 1
  • 343 changed lines read in 11m 45s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 6.6M in (5.4M from cache) · 106k out · about $7.30 at API prices
  • Runner: self-hosted · started after 11s · peak memory 5.0 GiB of 30.0 GiB
  • How Manki reviews

Comment thread dash-spv/src/network/peer.rs Outdated
break;
}
Some(Ok((raw, size))) => {
Some(Ok(Frame::Skipped(e))) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Warning · Correctness · Moderate

A reply that fails to decode still gets its peer kicked and banned once the request times out

What goes wrong: Frame::Skipped carries neither the command nor the size, so the reader never calls ledger.settle for it. The request it answered stays owed, and after REQUEST_TIMEOUT the timeout monitor kicks the peer and bans it with Ban::Kicked (10 minutes). The broker then sends the same request to the next peer, which sends the same reply and gets kicked too.

How to fix it, why, and 38 places read · confirmed with tools

How to fix it
Have Frame::Skipped carry the command and wire size of the dropped frame, read from the v1 header or the v2 short ID or command. Then let the reader release the awaited reply of that command in the Ledger and re-queue its request in the broker for another peer, so nothing is left owed.

Why it matters
This is the scenario from issue #1239, a format change in a known reply such as headers, so peers are still banned in turn, only later and for a shorter time. The new test sends only unsolicited bad frames, so it does not cover this.

Checked in the code
On the commented line: The Frame::Skipped(e) arm only logs, while ledger.settle(&raw.payload, size) at :795 runs only for Frame::Message

Skipped(encode::Error) holds no command or size

/// A whole frame that failed to decode. The next frame starts right after it.
Skipped(encode::Error),
}
/// Transport preference for peer connections.

silent_for measures from the oldest awaited entry, which only settle removes (:226-263)

/// owes none.
pub(super) async fn silent_for(&self) -> Duration {
let Some(oldest) = self.awaited.lock().await.first().map(|a| a.sent) else {
return Duration::ZERO;
};

A request with no progress for a timeout also condemns its peer, and the monitor runs bans.ban(peer.addr(), Ban::Kicked)

broker.receiving(&judge.observe(now, &peers)).await;
// A request with no progress for a timeout also condemns its peer: the
// per-peer byte check sees unrelated traffic and judges it healthy.
let timeout = |id: &PeerId| {
peers.iter().find(|p| p.id == *id).map_or(REQUEST_TIMEOUT, |p| p.timeout)

Double-checked
Manki tried to disprove this by reading the code and could not. The Frame::Skipped arm only logs. Neither ledger.settle nor broker.progress/arrived runs for it, so the request stays OnWire with stale last_progress…

Second check, on another model
Double-checked. The reader logs the skipped frame without settling the ledger or notifying the broker. The timeout judge can therefore kick and ban the peer if the link remain…

  • Create an issue for this

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Partly fixed. Still open: A garbled final cfilter leaves its batch charged and on the wire, so after the request timeout expire (broker.rs:341) and judge (manager.rs:1215) kick the peer and ban it with Ban::Kicked, and the next peer that gets the batch meets the same fate.

Comment thread dash-spv/src/network/peer.rs Resolved
Comment thread dash/src/network/message.rs Resolved
Comment thread dash-spv/src/network/peer.rs Resolved
Comment thread dash-spv/src/network/manager.rs Resolved
Skipping a message that fails to decode kept the connection open and logged a warning for every skipped frame, so a peer could flood the log at line rate and was never dropped.

The reader now counts the skipped frames of its connection. The first is logged at warn and the later ones at debug. After `MAX_SKIPPED_FRAMES` (100) the peer is disconnected and banned with `Ban::Kicked` for ten minutes, so one bad message from an honest peer still costs nothing.
A peer can send frames with a bad checksum at line rate, and the codec logged each one at warn. The codec consumes such a frame now, so a caller can skip it and decide itself how loudly to report it.
`FramedRead` yields `None` after a decoder error, so the consumed frame can only be skipped by a caller that calls `decode` itself or wraps the codec in its own decoder.
Every peer whose `headers2` failed to decompress stayed in the fallback set for the life of the client, so the set grew with each distinct failing address.

The list now keeps the latest `MAX_PLAIN_HEADERS` (256) addresses and forgets the oldest first. A forgotten address only costs one more failed `headers2` before it is added again.
The loopback responder kept its own `framed` closure next to the `regtest_frame` helper of the decode tests. It uses `regtest_frame` now.
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 10m 4s

Planner (4s)
    feat · 420 lines · 2 agents
    judge effort: high

Review (behavior · full): 10 findings
    ✅ Claude Opus 5.5 · high: 2 findings (2m 33s)
    ✅ GPT 6.2 Sol · high: 8 findings (3m 3s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 17 of 17 done (45s)

Judge (6m 17s)
    graded 10 findings: 7 kept · 2 dropped · 1 merged
    dropped, as the finders filed them: 1 blocker · 1 warning
    refuter: 4 checked · 3 confirmed · 1 unsettled
    origin checks: 4 checked · 1 older than this PR
    verdict reader: read the diff (1m 30s)

Posted: 2 findings
    1 warning · 1 suggestion
    not posted: 1 older than this PR · 1 on code an earlier round reviewed · 1 no realistic trigger · 1 rare trigger · 1 disproved by a check of the code

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 69% (resets 2026-12-04 20:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Not listed, on code this PR did not change: "The skip counter never resets, so a peer that keeps sending one message we cannot parse is still banned" (warning): "warning. skipped is set once per connection at dash-spv/src/network/peer.rs:761 and only increases at :788. Nothing in the Frame::Message arm resets it. At :804 the 100th failure kicks the peer with Ban::Kicked at :811, a 10 minute ban by dash-spv/src/network/bans.rs:9. One message type that is relayed on every block or lock and that our decoder rejects therefore kicks every honest peer within hours, and peers connected around the same time are kicked together. That is the outcome the PR sets out to avoid. The doc on MAX_SKIPPED_FRAMES says an honest peer sends few bad frames, but one repeated type is not few. The trigger needs a decoder fault or a protocol change, which nothing in normal use produces today, so rareTrigger holds it at a warning.
    Refutation confirmed: skipped is set to 0 once in spawn_reader and only goes up at line 788. Nothing resets it, including the Frame::Message arm. So the 100th undecodable frame of a connection's whole life kicks the peer with a 10-minute Ban::Kicked, even when every one of those frames is the same repeated message type. Rule checked: A counter set once per connection and only ever increased adds up every failure for the whole life of the connection, so a fault that repeats at a steady rate always reaches a fixed limit in the end.
  • Premise "This trigger happens in realistic use: When a frequently relayed message such as isdlock or clsig fails to decode, for example after a format change in a Dash Core release" confirmed. Only the code part can be checked here. clsig and isdlock are decoded with strict decoding that can fail, unlike unknown commands, which fall back to Unknown. Each failure becomes a skipped frame that counts toward the lifetime limit. Whether a Dash Core release will actually change these formats cannot be read from any code in reach.
    Pair refutation unsettled: The 100th skipped frame disconnects the peer and bans its address for ten minutes unless the address is explicitly configured. The test supplies repeated malformed frames and checks that a valid ping between them does not reset the count, but it does not establish that honest peers repeatedly send lock messages this decoder rejects. Rule checked: A counter initialized outside a receive loop accumulates failures across successful reads unless the loop resets or decays it.
  • Premise "This trigger happens in realistic use: When a frequently relayed message such as isdlock or clsig fails to decode, for example after a format change in a Dash Core release" unsettled. The client requests announced ChainLocks and propagates payload decode errors for both lock commands, but the code checked does not establish an incompatible release format or a recurring decode failure on valid lock traffic."
  • Kept: "A skipped reply leaves its request open, so the stall monitor still kicks and bans the honest peer" (warning): "warning. This repeats P1, and the code at that spot did not change. The Frame::Skipped arm at dash-spv/src/network/peer.rs:787-814 only logs and counts. Only the Frame::Message arm calls ledger.settle, at :819. The request stays OnWire, so expire blames its peer at dash-spv/src/network/broker.rs:305 while attempts < KICKING_ATTEMPTS. The monitor then bans that peer with Ban::Kicked at dash-spv/src/network/manager.rs:1338 and requeues the work at :1348, so the next peer gets the same reply and is kicked as well. The prior round confirmed the judge path. The cell stays at a warning, since the trigger needs a decoder fault.
    Refutation confirmed: The Frame::Skipped arm never calls ledger.settle, which only the Frame::Message arm does. A requested reply that fails to decode therefore leaves its request OnWire, and expire blames the peer. The monitor kicks it and requeues the work to the next peer, until KICKING_ATTEMPTS. Rule checked: A request the broker tracks stays OnWire until ledger.settle runs on its reply, and expire blames the peer of a request that has had no answer for longer than the timeout.
  • Premise "This trigger happens in realistic use: When a requested reply such as headers, mnlistdiff or cfilter fails to decode" confirmed. Answered on its code part: a block is a requested reply, and the decoder rejects one holding a special transaction type it does not know, even though unknown commands decode as Unknown. Whether Dash Core ever sends such a block depends on a future network upgrade, which no code shows.
    Pair refutation confirmed: A skipped frame neither settles the byte ledger nor reaches the broker's reply handler, so a witnessed timeout can still ban the peer and requeue the request. The tests inject malformed headers and exercise timeout bans separately, but do not show an honest peer's requested reply failing to decode or the same failure recurring after a retry. Rule checked: Consuming an undecodable frame does not complete an outstanding request unless the receive path also updates the request tracker.
  • Premise "This trigger happens in realistic use: When a requested reply such as headers, mnlistdiff or cfilter fails to decode" confirmed. On the code side, the client requests plain headers and the receive path can reject and skip a complete inbound frame of that reply type, as illustrated by the malformed-headers fixture; the fixture does not establish what an honest peer sends."
  • Not listed, it names no trigger that happens in realistic use: "A decode failure can leave a closed connection in the live peer set" (warning): "warning, with no realistic trigger. spawn_reader starts at dash-spv/src/network/peer.rs:716 before admit. A reader that exits on Some(Err(e)) at :783, or after a headers2 failure at :850, no longer records a ban. admit at dash-spv/src/network/peer_set.rs:95 then finds nothing to refuse, and remove at :118 already ran with nothing in the set. So a dead connection can be admitted. The window runs only from spawn_reader to admit, which is a few awaits. The same race already existed for EOF, which never banned, so an attacker gains nothing new. An occupied slot until the request timeout is the likely cost, but the code shown does not prove that nothing else cleans it up."
  • Dropped: "The decode-flood limit does not protect either handshake read loop" (ignore): "ignore. Both handshake loops are bounded by HANDSHAKE_TIMEOUT deadlines, at dash-spv/src/network/peer.rs:622 and :686. Within those windows, any well-formed message with an unhandled command is already read, checksummed, decoded and dropped by _ => {}, at :648 and :702, at the same cost as a bad frame. A peer gains no CPU or bandwidth it could not already spend with valid messages. A completed handshake leaves only 100 frames before the reader's limit applies."
  • Dropped: "A headers2 payload parse failure never triggers plain-header fallback" (ignore): "warning. The fallback runs only when a parsed Headers2 fails to decompress, at dash-spv/src/network/peer.rs:826 and :850. A headers2 frame whose payload fails consensus_decode_payload at dash/src/network/message.rs:862 becomes a plain Frame::Skipped, at dash-spv/src/network/peer.rs:140 and dash-spv/src/network/transport/v2.rs:106. That frame carries no command, so the reader cannot tell it from any other bad frame. The address is never recorded, and every reconnect asks for headers2 again. Each getheaders2 reply then stays owed and its peer is kicked, as in Finding 2. The PR's own fix for headers2 failures covers only one of the two ways our decoder can reject the message. The trigger needs a decoder fault, so it stays a warning.
    Refutation disproved: The headers2 decoder reads Dash Core's CompressibleBlockHeader serialization field for field (same flag bits, same order) and accepts any flags byte. Its only explicit limit is 8000 headers, which is Core's own MAX_HEADERS_COMPRESSED_RESULT, so a headers2 frame from an honest peer that passes framing always parses. Only a truncated or oversized payload, which Core never sends, reaches the Skipped arm, where the missing fallback would not help anyway. Rule checked: A parse failure can only steer the fallback if the peer sends a payload the decoder rejects; Rust's consensus decode returns an error only on short input or an explicit check.
  • Premise "This trigger happens in realistic use: When a peer's headers2 payload fails to parse in our decoder rather than failing to decompress" unsettled. Every payload Dash Core encodes decodes under our CompressedHeader and Headers2Message decoders, which match Core's bit layout and field order and cap the count at Core's own 8000, so in realistic use a headers2 payload fails to decompress rather than fails to parse.
    Pair refutation confirmed: The skipped-frame branch neither settles the header request nor records the peer for plain headers, so a later connection can still select compression. The fallback test exercises decompression failure, and the protocol documents when peers send headers2, but neither establishes that a normal peer sends a reply this parser rejects. Rule checked: A payload that fails parsing never reaches a fallback that runs only after successful parsing and failed decompression.
  • Premise "This trigger happens in realistic use: When a peer's headers2 payload fails to parse in our decoder rather than failing to decompress" confirmed. On the code side, the decoder can reject a headers2 payload while reading the count or compressed fields, before decompression is attempted."
  • Dropped: "A fatal decode error during the latency probe is returned as a successful connection" (ignore): "ignore. A probe that ends without a pong leaves lag_ms at 0. The supervisor treats 0 as missing latency and turns the peer away, at dash-spv/src/network/manager.rs:957-965, as it does on dev for a candidate that drops during the ping. The version handshake had completed by then, so clearing the dial backoff at :949 and reading start_height at :951 act on a handshake that really succeeded. The changed while let at dash-spv/src/network/peer.rs:687 ends on an error exactly as the old pattern did. No wrong result follows."
  • Not listed, on code an earlier round reviewed: "The oversized-frame assertion does not test a change in this PR" (suggestion): "note. The assertion at dash/src/network/message.rs:1016 checks that the 24 header bytes stay buffered. Its message says the header was consumed, which is the opposite. The oversized path returns at :909, before src.advance at :925, and this PR does not change it. So the assertion documents an invariant rather than covering a change. Rewording the message is enough."
  • Kept: "The eviction test bypasses reconnect negotiation" (suggestion): "note. The eviction part of the test calls the pub(crate) methods use_plain_headers and wants_plain_headers directly, at dash-spv/src/network/manager.rs:2204-2207. It does not go through a failing peer and a reconnect, and AGENTS.md asks for tests through the public API. Removing pop_front still fails the assertion, so the eviction is covered, and the point is only how the test is built."
  • Not listed, its trigger is rated below review.min_warning_trigger: "Fatal frame failures may bypass reconnect backoff" (warning): "warning, if the redial premise holds. The reader now exits on a stream it cannot resync without any ban, at dash-spv/src/network/peer.rs:783-786. The supervisor clears dial backoff after every successful handshake, at dash-spv/src/network/manager.rs:949. If nothing else delays a retry, a peer that always sends such a frame is redialed in a loop, with an error line each time. The code shown does not show how soon a disconnect leads to a redial, so that is listed as a doubt.
    Refutation confirmed: The no-delay redial path is real. But for the trigger named (a declared length over MAX_MSG_SIZE), the codec returns an encode::Error::Io, and the base reader also skipped the ban for Io errors, so this loop is not new. Each cycle costs a fixed handshake plus one log line, which does not grow with input normal use supplies. Rule checked: A peer that ends its connection without being banned, and whose dial backoff a successful handshake cleared, can be picked again in the very next supervisor round.
  • Premise "After a reader exits on Some(Err(e)), the supervisor can redial that address in its next round with no delay, since neither Bans nor discovery records the failure" confirmed. The reader exits without a ban, dialed() deletes the address's entry, the Disconnected event wakes the supervisor right away, and next_candidates skips only live and banned addresses, so discovery offers the address as untried again.
  • Premise "This trigger happens in realistic use: When a peer sends a frame whose declared length exceeds MAX_MSG_SIZE on every connection" confirmed. On the code side, a declared length over MAX_MSG_SIZE makes the codec return an error without consuming the buffer, SizedCodec passes it on as fatal, and it reaches the no-ban exit at peer.rs:783. Whether a peer actually sends such a frame cannot be read from code, and Dash Core caps messages at the same 3 MiB.
    Pair refutation confirmed: The active reader logs the fatal error and reports a disconnect without recording a failure. The pump removes the connection and wakes the supervisor, which can immediately select the same address if it is the only eligible configured peer. Rule checked: A disconnect that wakes the retry loop does not incur backoff unless the failure is recorded in state that candidate selection checks.
  • Premise "After a reader exits on Some(Err(e)), the supervisor can redial that address in its next round with no delay, since neither Bans nor discovery records the failure" confirmed. The disconnect branch removes the connection and wakes the supervisor without updating bans or discovery, so a sole configured address is eligible in the next round.
  • Premise "This trigger happens in realistic use: When a peer sends a frame whose declared length exceeds MAX_MSG_SIZE on every connection" confirmed. The loopback test supplies the oversized declaration after admission, and every fresh V1 connection accepts the same wire input and rejects it at the same length check.", trigger 3 and harm 4 of 10: "It needs a peer that keeps sending frames the decoder cannot resync, such as declared lengths over MAX_MSG_SIZE, which is a malicious or badly broken peer and not ordinary traffic."

Timing:

  • Parse: 7.1s
  • Review agents: 219.3s
  • Judge: 377.5s
  • Total: 603.9s

`NetworkMessage::split_v2` returns the command and payload of BIP324 V2 packet contents, the lookup `consensus_decode_v2` did inline. A caller can then name the command of a message whose payload fails to decode.

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ 1 warning to address. Fix it, reply in its thread with a reason Manki accepts, or tick Create an issue for this to track it for later. The PR is also a draft, so mark it ready for review too. If no approval follows, comment /manki check.

Still open from earlier reviews:

  • dash-spv/src/network/peer.rs:787: A reply that fails to decode still gets its peer kicked and banned once the request times out (view thread)

Checked and left out: 2 findings (1 disproved, 1 rare)

Disproved by a check of the code · 1 finding

  • A headers2 payload parse failure never triggers plain-header fallback · dash-spv/src/network/peer.rs:850
    The headers2 decoder reads Dash Core's CompressibleBlockHeader serialization field for field (same flag bits, same order) and accepts any flags byte.

Rare trigger, so not listed · 1 warning

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed 8971b56, round 2
  • 420 changed lines read in 10m 4s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 6.3M in (4.9M from cache) · 107k out · about $8.03 at API prices
  • Runner: self-hosted · started after 7s · peak memory 6.2 GiB of 30.0 GiB
  • How Manki reviews

(0..MAX_PLAIN_HEADERS as u16).map(|port| SocketAddr::from(([10, 0, 0, 1], port)));
for (n, other) in others.enumerate() {
assert!(net.state.wants_plain_headers(node.addr).await, "forgotten after {n}");
net.state.use_plain_headers(other).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Testing · Moderate

The eviction test bypasses reconnect negotiation

Why: The live reconnect portion tests the initial fallback, but the eviction portion populates the private cache through internal methods and then checks membership directly. Removing plain.pop_front() would fail that check, but the test does not show whether eviction changes what a reconnect sends on the wire.

How to fix it and 3 places read · breaks a repository rule

How to fix it
Keep the cache-capacity check separate from the network regression, and observe eviction through a subsequent connection's header negotiation rather than a cache lookup.

Repository rule
This PR breaks a required rule of AGENTS.md: Test through the public API. Don't set internal fields or states by hand: a test that builds a state production never reaches proves nothing.

Checked in the code
On the commented line: Seeds net.state.use_plain_headers(other).await without receiving a frame from those peers

Checks wants_plain_headers rather than reconnecting

}
assert!(!net.state.wants_plain_headers(node.addr).await);
}
/// The supervisor's candidates leave out the live peers and the banned ones before

Is the eviction line whose removal fails this assertion

if plain.len() == MAX_PLAIN_HEADERS {
plain.pop_front();
}
plain.push_back(addr);
}

  • Create an issue for this
  • Dismiss this finding

@manki-review
manki-review Bot dismissed their stale review December 4, 2026 11:53

Superseded by new review

A skipped message carried only its error, so the ledger kept owing the reply it answered. Its charge stayed in flight, and once the request timeout passed the stall judge kicked and banned the peer for a message our decoder failed on.

A skipped frame now carries its command and wire size, read from the V1 header before the codec consumes the frame, or from the V2 contents. The ledger settles the oldest owed reply of that command with that size, since the hash that names the exact reply is in the payload that failed. Peers answer in order, so the oldest is the one answered.

A `cfilter` is one of many replies to its batch, so a bad one only counts as an answer and adds its bytes. The batch stays owed until its stop filter arrives, and a batch that ends with filters missing is already requested again by the filters pipeline.
The broker kept a request whose reply failed to decode on the wire with its peer. Once the request timeout passed it blamed that peer, which got kicked and banned, and only then was the request sent elsewhere.

The reader now reports the command of a skipped message to the pump, and the broker re-queues the oldest request of that peer the command answers, through the same requeue path as a disconnect or a `notfound`. The broker cannot exclude a peer from routing, so the copy can go to the same peer again.

A request that already reached `KICKING_ATTEMPTS` is not re-queued. It stays on the wire, and `expire` retries it a timeout later without blaming its peer. A reply every peer garbles is then resent once per request timeout instead of at network speed, and nobody is kicked for it. It still never completes, as before this change.

A `cfilter` re-queues nothing. It is one of many replies to its batch, so it only counts as progress. A garbled filter in the middle of a batch is requested again by the filters pipeline once the batch ends incomplete. A garbled stop filter leaves the batch on the wire, and its peer is blamed once the request timeout passes, as before.
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 12m 58s

Planner (5s)
    feat · 674 lines · 2 agents
    judge effort: high

Review (behavior · full): 14 findings
    ✅ Claude Opus 5.5 · high: 2 findings (3m 43s)
    ✅ GPT 6.2 Sol · high: 9 findings (3m 8s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 18 of 18 done, 3 findings (1m 29s)

Judge (7m 41s)
    graded 14 findings: 10 kept · 1 dropped · 3 merged
    dropped, as the finders filed them: 1 blocker
    refuter: 3 checked · 1 confirmed · 2 unsettled
    origin checks: 4 checked
    verdict reader: read the diff (1m 20s)

Posted: 6 findings
    3 warnings · 3 suggestions
    not posted: 2 over the review.notes limit · 1 no realistic trigger · 1 disproved by a check of the code

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 75% (resets 2026-12-04 20:00 UTC)
  • ChatGPT subscription: weekly 3% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Kept: "The skip counter never resets, so a format change in a common message still gets every honest peer banned" (warning): "warning. skipped is set to 0 once per reader at peer.rs:776 and incremented on every Frame::Skipped at peer.rs:807. Nothing ever lowers it. At peer.rs:826-833 the 100th skip bans the peer with Ban::Kicked, which lasts 10 minutes (bans.rs:9). The comment at peer.rs:93-94 assumes an honest peer sends few such messages. One unparseable type that is relayed per block or per InstantSend lock reaches 100 within hours, so every honest peer is kicked and banned on a cycle. That is the case this PR says it fixes. The cap itself, which stops a log flood, is reasonable. The cost is that it counts over the whole connection instead of a window.", trigger 5 and harm 8 of 10: "It takes a protocol format change in a commonly sent message, which is uncommon but is exactly what the PR targets; a long-lived connection then reaches 100 skips over time."
  • Kept: "The broker and the ledger can pick different requests for the same garbled reply" (suggestion): "note. The two sides use different rules. Broker::undecodable only looks at requests where o.peer == peer (broker.rs:282). The peer's Ledger also holds the hedge copies charged to it (costs.rs:287). So a garbled block that answers a hedge can requeue a different block. The peer then sends that block anyway, and it is downloaded twice. The cost is one repeated download in a rare combination: a garbled reply on a peer that holds a hedge. The two rules should match."
  • Dropped: "Rejected V1 frames can change which requests the client treats as answered" (ignore): "ignore. A peer can send a frame with the right magic and the same command whose payload fails to parse. That frame reaches the same settle_undecodable and PeerEvent::Undecodable path at peer.rs:836-838. So a wrong magic or a bad checksum gives the sender nothing it does not already have. A bad checksum also means the peer did answer, and Dash Core itself only drops such a message, it does not punish the peer (net.cpp:824-830)."
  • Kept: "A malformed command reaches the network log without escaping" (suggestion): "note. CommandString::consensus_decode keeps every nonzero byte (message.rs:138-144). The new warning at peer.rs:812 formats that command with {}. A peer can therefore put a newline and up to 11 more characters into a log line. That is at most a short fake line, with no capability beyond confusing a reader. Printing the command with {:?} or a sanitised form, as Dash Core does with SanitizeString, would prevent it."
  • Kept: "An undecodable final compact filter can still get its sender banned" (warning): "warning. The earlier problem remains for filters. settle_undecodable never completes a Reply::CFilters (costs.rs:292), and answered_by returns false for RequestKey::CFilters (broker.rs:52). A garbled final filter therefore leaves the batch charged in the ledger and OnWire in the broker. Once the peer has nothing more to send, expire blames it while attempts < KICKING_ATTEMPTS (broker.rs:341), judge also counts its non-zero in-flight bytes (manager.rs:1215), and the monitor bans it with Ban::Kicked (manager.rs:1338). The next peer gets the same batch and the same fate.
    Refutation disproved: The code path matches the finding: settle_undecodable leaves a CFilters batch charged, and answered_by never re-queues it. But it only starts when a cfilter frame fails to decode. That frame is a plain u8, a 32-byte hash and a byte vector, with a checksum checked inside a length-bounded frame, so only a peer that sends malformed bytes produces it. Whether a ban for that counts as a wrong result cannot be settled from the code. Rule checked: A peer is blamed for a stale OnWire request only when a reply that should settle it never arrives. So the finding needs a cfilter frame that fails to decode, and an honest peer never sends one.
  • Premise "This trigger happens in realistic use: When the last cfilter of a batch fails to decode" disproved. A cfilter decodes as fixed fields (u8 filter type, block hash, length-prefixed byte vector) with no local state, unlike headers2 decompression, and its checksum is checked inside a frame limited to MAX_MSG_SIZE. A well-formed cfilter from an honest node always decodes, so the failure only comes from a peer that sends malformed bytes, not from normal use.
    Pair refutation confirmed: The reader records the failed reply, but the ledger leaves the batch charged and the broker does not requeue it on decode failure. If the sender then goes quiet while another peer keeps the link active, the outstanding charge can still make the sender a timeout culprit. Rule checked: A compact-filter batch is settled by a decoded reply matching its stop hash; recording an undecodable frame as progress only resets the timeout.
  • Premise "This trigger happens in realistic use: When the last cfilter of a batch fails to decode" confirmed. The ledger test exercises the decode-failure case for a one-block batch, and the wire decoder can report a complete cfilter as skipped without closing the connection; this establishes the input path, not how often deployed peers send such a frame."
  • Kept: "Unrelated traffic can postpone retry of a failed request indefinitely" (warning): "warning. At KICKING_ATTEMPTS the request is left OnWire (broker.rs:288). The doc says expire then retries it a timeout later. In fact expire only acts once last_answer or last_progress ages out (broker.rs:332-340), and refresh resets both on every answer from that peer (broker.rs:309). While the peer streams other replies, the request is never retried. When only some peers send the form we cannot parse, the request could have been served by another peer, but it is not.
    Refutation confirmed: After two sends (attempts reaches KICKING_ATTEMPTS = 2), undecodable leaves the request on its peer and counts on expire. But expire skips any request whose peer answered recently, and every cfilter/cfheaders/block/headers reply from that peer resets both timers. No sync manager releases the key on a timer of its own, and only block and cfilter requests get hedged to another peer. So a garbled headers, cfheaders or mnlistdiff request sits there until the peer stops answering. Rule checked: A stalled request is retried only after its peer has sent no answer for a timeout, and any answer from the peer resets that timer for all of its requests. So a request a busy peer will never fulfil is never retried while the peer keeps answering other work.
  • Premise "While a request that reached KICKING_ATTEMPTS stays OnWire, its peer can keep sending replies that call broker.progress (manager.rs:1435), so expire at broker.rs:332-340 never requeues that request" confirmed. refresh resets last_progress and last_answer on every request of the peer for each cfilter/cfheaders/block/headers reply (and for the undecodable frame itself). expire only requeues once one of those timers is older than the timeout.
  • Premise "This trigger happens in realistic use: When a request's reply fails to decode on three peers in a row and the last peer keeps serving other requests" confirmed. On the code side, two undecodable replies are enough (the first send sets attempts to 1 and the requeue keeps it, the resend sets 2 = KICKING_ATTEMPTS), and a peer is kicked only after 100 skipped frames. Whether peers actually garble replies is up to the peers and cannot be read from the code.
    Pair refutation unsettled: At the attempt limit, a decode failure leaves the request on the wire. Replies for other work—and named decode failures even when no request matches—refresh both timers that govern expiration. Rule checked: A timeout based only on peer-wide activity cannot bound an individual request’s lifetime while that peer continues to make progress on other work.
  • Premise "While a request that reached KICKING_ATTEMPTS stays OnWire, its peer can keep sending replies that call broker.progress (manager.rs:1435), so expire at broker.rs:332-340 never requeues that request" confirmed. The pump refreshes both timestamps on every on-wire request owned by the replying peer, so qualifying replies before the deadline keep expiration from requeueing the missing request.
  • Premise "This trigger happens in realistic use: When a request's reply fails to decode on three peers in a row and the last peer keeps serving other requests" unsettled. The exact three-peer sequence is not established: the limit is two sends, the second decode failure does not dispatch a third, and the test supplies a decodable replacement before advancing past the deadline.", trigger 4 and harm 5 of 10: "It needs a request that already reached the attempt limit, plus a peer that keeps answering other work without ever supplying the missing reply, which is an uncommon combination."
  • Not listed, it names no trigger that happens in realistic use: "A fast decode failure can arrive before the broker registers the send" (warning): "warning. route sends at broker.rs:400 and only registers the sends after the loop at broker.rs:413. undecodable handles only OnWire (broker.rs:282), unlike arrived, which also handles Queued. A garbled reply that is processed inside that window settles the ledger charge but is dropped by the broker. The request then sits OnWire with no reply coming, and expire blames the peer. The window is the length of one routing pass, which is much shorter than a network round trip, so the trigger is not realistic."
  • Dropped: "A headers2 payload decode failure never enables the plain-header fallback" (ignore): "warning. This PR adds the plain-header fallback but calls use_plain_headers only when decompression fails (peer.rs:878). A headers2 frame that fails to parse goes through the generic skip at peer.rs:836, which never records the address. So the next connection still negotiates headers2 (peer.rs:687-688). If such a failure is systematic, header sync can never fall back, which is the sibling of the path this PR fixes in the same file. The state it needs is a headers2 payload from Dash Core that our own decoder rejects. Only a defect in our own parsing code produces that, so the column is rare.
    Refutation disproved: The client's headers2 decoder reads the same flag byte, fields and bit masks as Dash Core's CompressibleBlockHeader serializer, and caps a batch at 8000 headers, as Core does. So a conforming Dash Core peer never produces a headers2 frame that reaches the generic skip at peer.rs:836. Only a non-conforming or hostile peer does, and that peer is kicked after MAX_SKIPPED_FRAMES; asking it for plain headers would fix nothing. Rule checked: A wire decoder that reads the same fields in the same order, under the same flag bits and count limit as the sender's serializer, accepts everything that sender produces. So the skip path for undecodable frames only runs for frames that do not follow the format.
  • Premise "Normal use or outside input can produce the state this failure needs" unsettled. The decoder reads the same flag byte, conditional version, prev-hash, merkle root, time, bits and nonce fields as Core's serializer, with the same bit masks and the same 8000-header limit. So no conforming Dash Core headers2 payload fails to parse, and only a defect in the client's own parser or a non-conforming peer could produce the state.
    Pair refutation confirmed: The skip path leaves compressed-header negotiation unchanged; only a decompression error records the peer for plain headers on reconnect. Dash Core's reply path is present, but I did not establish that its serializer produces a reply this decoder rejects, or that a peer in normal use repeatedly supplies one. Rule checked: A payload decode error takes the skipped-frame branch and cannot reach fallback logic that runs only after successful decoding.
  • Premise "Normal use or outside input can produce the state this failure needs" confirmed. The peer supplies the payload bytes, and the decoder rejects invalid counts or incomplete header fields before decompression; an internal decoder defect is not required to reach the skip path."
  • Not listed, over the review.notes limit: "The retry test bypasses the production request-registration path" (suggestion): "note. The test sends straight to a peer handle (manager.rs:2962) and then sets the broker state by hand with mark_on_wire (manager.rs:2963), which the AGENTS.md rule asks tests not to do. The state it builds is one production reaches, and the test still fails if the requeue in undecodable is reverted. It cannot catch a reply that lands while route is still registering the send."
  • Kept: "undecodable marks progress for any command, while decoded messages count only for five reply types" (suggestion): "note. undecodable calls progress before any answered_by check (broker.rs:275). The pump calls progress only for five reply types (manager.rs:1427-1435). So a garbled inv or ping refreshes stall timers, while the same message decoded would not. A peer can already refresh them without limit by sending an empty decoded headers, and skips are capped at 100. So this gives no new way to stall, but the two rules for what counts as an answer disagree."
  • Not listed, over the review.notes limit: "The new command-string method is named command(), while the existing ones use cmd()" (suggestion): "note. The private Reply::command returns &'static str (costs.rs:65), like NetworkMessage::cmd (message.rs:292) and MessageType::cmd (manager.rs:165). NetworkMessage::command returns an owned CommandString. Only the name differs."

Timing:

  • Parse: 10.0s
  • Review agents: 307.0s
  • Judge: 460.7s
  • Total: 777.7s

Last reviewed e32e805 · head e32e805 · up to date

  • Pause automatic reviews
  • Review again
  • Deeper review
  • Review this draft
  • Review every push

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ 3 warnings to address. Fix each one, reply in its thread with a reason Manki accepts, or tick Create an issue for this to track it for later. The PR is also a draft, so mark it ready for review too. If no approval follows, comment /manki check.

Still open from earlier reviews:

  • dash-spv/src/network/peer.rs:783: A reply that fails to decode still gets its peer kicked and banned once the request times out (view thread)

2 suggestions are not listed.


Checked and left out: 1 finding

Disproved by a check of the code · 1 finding

  • A headers2 payload decode failure never enables the plain-header fallback · dash-spv/src/network/peer.rs:836
    The client's headers2 decoder reads the same flag byte, fields and bit masks as Dash Core's CompressibleBlockHeader serializer, and caps a batch at 8000 headers, as Core does. So a conforming Dash Core peer never produces a headers2 frame that reaches the generic skip at peer.rs:836.

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed e32e805, round 3
  • 674 changed lines read in 12m 58s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 8.0M in (6.5M from cache) · 134k out · about $9.58 at API prices
  • Runner: self-hosted · started after 12s · peak memory 4.6 GiB of 30.0 GiB
  • How Manki reviews

error
);
}
if skipped == MAX_SKIPPED_FRAMES {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Warning · Reliability · Quick fix

The skip counter never resets, so a format change in a common message still gets every honest peer banned

What goes wrong: skipped starts at 0 when the reader starts and only ever goes up. Any long-lived connection that keeps sending a message our decoder cannot parse is banned once the total reaches MAX_SKIPPED_FRAMES, with Ban::Kicked for 10 minutes. Honest peers send headers/headers2 announcements every block and clsig/isdlock replies all the time, so a format change in one of them, which is the case this PR sets out to handle, gets every peer banned again after 100 such messages, then again after each reconnect.

How to fix it, 7 places read, and 1 other check · proven from the cited lines

How to fix it
Kick only on a burst, not on a lifetime total. For example, keep the count in a window that resets every PING_INTERVAL, or let decoded frames reduce it, so a peer that sends one unparseable message type at normal relay rates is never kicked. Update the only_a_flood_of_undecodable_frames_bans_a_peer test so it still checks the flood case and also checks that slow repeats keep the connection.

Checked in the code
On the commented line: if skipped == MAX_SKIPPED_FRAMES { ... state.bans.ban(addr.addr(), Ban::Kicked).await; break; }

  • Declares let mut skipped = 0; once per reader task. Nothing resets it.
  • Initializes skipped once per reader and dash-spv/src/network/peer.rs:807 increments it for every skipped frame.

let mut last_seen = tokio::time::Instant::now();
let mut skipped = 0;
loop {
let next = tokio::select! {
_ = shutdown.cancelled() => break,

skipped += 1; runs on every Frame::Skipped, whatever its command or how much time has passed.

})) => {
skipped += 1;
let name = command.as_ref().map_or("unnamed", AsRef::as_ref);
if skipped == 1 {
tracing::warn!(

const KICK_BAN: Duration = Duration::from_secs(10 * 60);, and bans.rs:60 maps Ban::Kicked to it.

const MAX_DIAL_BACKOFF: Duration = Duration::from_secs(60);
const KICK_BAN: Duration = Duration::from_secs(10 * 60);
const MISBEHAVIOUR_BAN: Duration = Duration::from_secs(24 * 60 * 60);
pub enum Ban {

  • dash-spv/src/network/peer.rs:93-94: Says in its doc that an honest peer sends "one message type we cannot parse", but a type gets sent many times, once per block or per InstantSend transaction.
  • dash-spv/src/network/manager.rs:2142: Verifies a successful ping between failures, then dash-spv/src/network/manager.rs:2148 expects the first failure still to count toward the ban.
  • dashpay/dash:src/net_processing.cpp:6025 logs a payload-processing exception and dashpay/dash:src/net_processing.cpp:6031 returns without banning the peer on t…
  • Create an issue for this

_ => None,
})
.min_by_key(|(sent, ..)| *sent);
if let Some((_, _, key)) = oldest.filter(|(_, attempts, _)| *attempts < KICKING_ATTEMPTS) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Warning · Reliability · Moderate

Unrelated traffic can postpone retry of a failed request indefinitely

What goes wrong: At the attempt limit, the broker leaves the failed request on the wire and relies on silence to retry it. A peer that keeps answering other work can keep that request alive without ever supplying its missing reply. The new handler also refreshes all request timers for malformed commands that match no outstanding request.

How to fix it and 18 places read · confirmed with tools

How to fix it
Put a request known to have failed into a non-punitive retry state with its own deadline. Update answer timers only for responses that qualify as progress, and do not let unrelated replies extend a failed request's retry deadline.

Checked in the code
On the commented line: Leaves a matching request on the wire when attempts >= KICKING_ATTEMPTS.

Calls progress(peer) before checking whether any request matches.

pub async fn undecodable(&self, peer: PeerId, command: &str) {
self.progress(peer).await;
let oldest = self
.requests
.lock()

Refreshes both timestamps on all requests for the peer, and dash-spv/src/network/broker.rs:332 retries only once one of those timestamps ages out.

if let ReqState::OnWire(o) = state {
if peers.contains(&o.peer) {
o.last_progress = now;
if answered {
o.last_answer = now;

Refreshes the same timestamps for successful replies to other work.

// big answers on a slow link would be judged stalled.
if matches!(
*msg,
NetworkMessage::CFilter(_)
| NetworkMessage::CFHeaders(_)

Double-checked
Manki tried to disprove this by reading the code and could not. After two sends (attempts reaches KICKING_ATTEMPTS = 2), undecodable leaves the request on its peer and counts on expire. But expire skips any reques…

Second check, on another model
Not settled. At the attempt limit, a decode failure leaves the request on the wire. Replies for other work—and named decode failures even when no request matches—refresh bo… See dash-spv/src/network/manager.rs lines 1427, 1435, 2965, 2977, 2982, 2912, and 2934, dash-spv/src/network/broker.rs lines 288, 309, 332, 275, 305, 162, 354, 459, and 484, and dash-spv/src/sync/filter_headers/pipeline.rs lines 199, 215, 253, and 271.

  • Create an issue for this

/// decode, answers. One that reached [`KICKING_ATTEMPTS`] stays, so [`Self::expire`] retries
/// it a timeout later without blame, and a reply every peer garbles is not resent at once.
pub async fn undecodable(&self, peer: PeerId, command: &str) {
self.progress(peer).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Maintainability · Quick fix

undecodable marks progress for any command, while decoded messages count only for five reply types

Why: Neither not_found nor arrived calls progress itself. The manager loop calls broker.progress(peer) only for CFilter, CFHeaders, Block, Headers and Headers2. undecodable calls self.progress(peer) for every command, before it checks answered_by, so a garbled inv, tx or mnlistdiff resets the stall clocks of all that peer's requests, but the same message decoded does not.

How to fix it, why, and 5 places read

How to fix it
Call progress only when the command is a reply that the manager loop would also count (for example, gate it on answered_by matching any on-wire key), or move the decision to the PeerEvent::Undecodable arm in manager.rs next to the existing list.

Why it matters
The rule for what counts as an answer now lives in two places that disagree. A peer whose unrelated messages fail to decode is not blamed for its stalled requests until it reaches MAX_SKIPPED_FRAMES skipped frames, which bounds how much this can happen.

Checked in the code
On the commented line: self.progress(peer).await; runs before any answered_by(command) check

if matches!(*msg, NetworkMessage::CFilter(_) | NetworkMessage::CFHeaders(_) | NetworkMessage::Block(_) | NetworkMessage::Headers(_) | NetworkMessage::Headers…

// big answers on a slow link would be judged stalled.
if matches!(
*msg,
NetworkMessage::CFilter(_)
| NetworkMessage::CFHeaders(_)

not_found only requeues matching keys and never calls progress

pub async fn not_found(&self, peer: PeerId, inv: &[Inventory]) {
let keys: HashSet<RequestKey> = inv
.iter()
.filter_map(|i| match i {

arrived settles the key and wakes the router, with no progress call

/// nothing, and a manager that cannot use the reply must release the key.
pub async fn arrived(&self, peer: PeerId, key: RequestKey) {
let mut reqs = self.requests.lock().await;
match reqs.get(&key) {
Some(ReqState::OnWire(o)) if o.peer == peer || o.hedges.contains(&peer) => {}

  • Create an issue for this
  • Dismiss this finding

.await
.iter()
.filter_map(|(key, state)| match state {
ReqState::OnWire(o) if o.peer == peer && key.answered_by(command) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Correctness · Moderate

The broker and the ledger can pick different requests for the same garbled reply

Why: Broker::undecodable only looks at requests where o.peer == peer, and it counts a headers reply as answering a getheaders2. Ledger::settle_undecodable also includes hedge copies the peer carries, and it matches Reply::Headers2 only on headers2. Example: a peer carries a hedge copy of block A and is the primary carrier of block B.

How to fix it, why, 9 places read, and 1 other check

How to fix it
Use one rule in both places. Either let the broker also consider requests the peer holds as a hedge, or skip the requeue when the peer holds an older hedge copy of the same kind. Make answered_by for Headers follow the peer's headers2 choice, the way Reply::command does.

Why it matters
A garbled reply to A settles A in the ledger but requeues B in the broker. The peer still sends B, so B is downloaded twice. This needs a garbled block or headers reply, so it is rare.

Checked in the code
On the commented line: Filters with ReqState::OnWire(o) if o.peer == peer && key.answered_by(command), so hedges are ignored. Selects only o.peer == peer, while dash-spv/src/network/broker.rs:259 accepts a decoded answer from o.hedges too.

RequestKey::Headers(_) => matches!(command, "headers" | "headers2")

match self {
RequestKey::Headers(_) => matches!(command, "headers" | "headers2"),
RequestKey::CfHeaders(_) => command == "cfheaders",
RequestKey::CFilters(_) => false,
RequestKey::MnListDiff(_) => command == "mnlistdiff",

awaited.iter().position(|a| a.reply.command() == command) also includes hedge copies charged to this peer, and costs.rs:68 maps Reply::Headers2 to "heade…

let mut awaited = self.awaited.lock().await;
let Some(i) = awaited.iter().position(|a| a.reply.command() == command) else {
return;
};
*self.last_answer.lock().await = Instant::now();

arrived ignores a reply from a peer that is neither the carrier nor a hedge, so the requeued copy is sent and downloaded again.

match reqs.get(&key) {
Some(ReqState::OnWire(o)) if o.peer == peer || o.hedges.contains(&peer) => {}
Some(ReqState::Queued(_)) => {
reqs.remove(&key);
self.drop_queued(&key, &reqs).await;

  • Create an issue for this
  • Dismiss this finding

if skipped == 1 {
tracing::warn!(
target: "dash_spv::network",
"skipped a {} message from {} that failed to decode: {}",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Correctness · Quick fix

A malformed command reaches the network log without escaping

Why: A V1 peer can put control characters in the command of a rejected frame, and the reader puts that command directly in the warning or debug message. The command decoder removes NULs but preserves other control characters, so this can inject lines into a plain-text log.

How to fix it, 6 places read, and 1 other check

How to fix it
Validate the V1 command field before turning it into a command name. Log rejected command bytes and other peer-supplied command names using an escaped or hex representation, including in the checksum diagnostic.

Checked in the code
Converts every nonzero byte with Some(u as char) instead of validating printable characters and NUL padding.

let rawbytes: [u8; 12] = Decodable::consensus_decode(r)?;
let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| {
if u > 0 {
Some(u as char)
} else {

Decodes the command using CommandString::consensus_decode after a frame fails.

Err(error) if src.len() < before => Ok(Some(Frame::Skipped {
command: command
.and_then(|c| CommandString::consensus_decode(&mut &c[..]).ok()),
size: (before - src.len()) as u64,
error,

Uses the raw command as name, which is formatted with {} at dash-spv/src/network/peer.rs:812 and dash-spv/src/network/peer.rs:820.

skipped += 1;
let name = command.as_ref().map_or("unnamed", AsRef::as_ref);
if skipped == 1 {
tracing::warn!(
target: "dash_spv::network",

  • dash/src/network/message.rs:853: Also formats the V1 command directly in the checksum diagnostic.
  • dash-spv/src/network/peer.rs:820: "skipped a {} message from {} that failed to decode: {}",
  • dashpay/dash:src/net.cpp:825 logs SanitizeString(msg.m_type) on a checksum failure and dashpay/dash:src/net.cpp:831 rejects an invalid command field.
  • Create an issue for this
  • Dismiss this finding

@codecov

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.60154% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.18%. Comparing base (9329b3e) to head (e32e805).
⚠️ Report is 1 commits behind head on dev.

Files with missing lines Patch % Lines
dash-spv/src/network/costs.rs 84.44% 7 Missing ⚠️
dash-spv/src/network/broker.rs 80.00% 5 Missing ⚠️
dash-spv/src/network/peer.rs 89.47% 4 Missing ⚠️
dash-spv/src/network/transport/v2.rs 92.30% 3 Missing ⚠️
dash-spv/src/network/manager.rs 99.04% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1593      +/-   ##
==========================================
+ Coverage   88.16%   88.18%   +0.02%     
==========================================
  Files         270      270              
  Lines       72623    72960     +337     
==========================================
+ Hits        64031    64343     +312     
- Misses       8592     8617      +25     
Flag Coverage Δ
core 83.87% <100.00%> (+<0.01%) ⬆️
rpc 83.87% <100.00%> (+<0.01%) ⬆️
spv 95.42% <94.10%> (-0.04%) ⬇️
wallet 83.87% <100.00%> (+<0.01%) ⬆️
Files with missing lines Coverage Δ
dash/src/network/message.rs 94.22% <100.00%> (+0.45%) ⬆️
dash-spv/src/network/manager.rs 97.67% <99.04%> (+0.11%) ⬆️
dash-spv/src/network/transport/v2.rs 97.19% <92.30%> (-2.81%) ⬇️
dash-spv/src/network/peer.rs 94.54% <89.47%> (+0.25%) ⬆️
dash-spv/src/network/broker.rs 98.51% <80.00%> (-0.78%) ⬇️
dash-spv/src/network/costs.rs 95.39% <84.44%> (-1.91%) ⬇️

... and 3 files with indirect coverage changes

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dash-spv: our own parse failures ban peers for 24 hours

1 participant