Repository navigation
fix(dash-spv): stop banning peers on decode failures - #1593
xdustinface wants to merge 11 commits into
Conversation
`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
|
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. |
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
|
✅ Review complete in 11m 45s Planner (6s) Review (behavior · full): 15 findings Judge (5m 27s) Posted: 5 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
|
|
CI does not run on this PR while it is a draft. Someone with write access can start it here:
Marking the PR ready for review also starts CI. CI started for e32e805: Continuous integration, Pre-commit Checks, Sanitizer. |
There was a problem hiding this comment.
🔴 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
- A headers2 payload that fails to parse never triggers plain-header fallback ·
dash-spv/src/network/peer.rs:819
Trigger 3 of 10, below the cut-off of 4.
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-5andgpt-6.2-sol, judged byclaude-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
| break; | ||
| } | ||
| Some(Ok((raw, size))) => { | ||
| Some(Ok(Frame::Skipped(e))) => { |
There was a problem hiding this comment.
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
rust-dashcore/dash-spv/src/network/transport/mod.rs
Lines 17 to 21 in 6612427
silent_for measures from the oldest awaited entry, which only settle removes (:226-263)
rust-dashcore/dash-spv/src/network/costs.rs
Lines 198 to 202 in 6612427
A request with no progress for a timeout also condemns its peer, and the monitor runs bans.ban(peer.addr(), Ban::Kicked)
rust-dashcore/dash-spv/src/network/manager.rs
Lines 1293 to 1297 in 6612427
dash-spv/src/network/bans.rs:9:KICK_BAN: Duration = Duration::from_secs(10 * 60)dash-spv/src/network/manager.rs:2117:let _peer = joined(&net, &node).await;dash-spv/src/network/manager.rs:2119: The test sends an unsolicited bad frame, so nothing is in flight to time outdash-spv/src/network/peer.rs:795:ledger.settle(&raw.payload, size).await;dash-spv/src/network/broker.rs:296:let silent_since = if now.duration_since(o.last_answer) > timeout * ANSWER_TIMEOUTS {dash-spv/src/network/broker.rs:300:} else if now.duration_since(o.last_progress) > timeout {dash-spv/src/network/manager.rs:1226:let up = self.uptime_since(since);dash-spv/src/network/manager.rs:1228:let witnessed = up > p.timeout;dash-spv/src/network/manager.rs:1229:if witnessed || down > p.timeout * LINK_STALL_TIMEOUTS {dash-spv/src/network/manager.rs:1251:let kick = silent.first().filter(|_| due);dash-spv/src/network/manager.rs:1252:kicked.extend(kick.map(|(_, p, _)| p.id));dash-spv/src/network/broker.rs:305:if o.attempts < KICKING_ATTEMPTS {dash-spv/src/network/broker.rs:306:let since = culprits.entry(o.peer).or_insert(silent_since);dash-spv/src/network/manager.rs:1406:if matches!(dash-spv/src/network/manager.rs:1414:broker.progress(peer).await;dash/src/network/message.rs:923:let mut cursor = io::Cursor::new(&src[..frame_len]);dash/src/network/message.rs:925:src.advance(frame_len);dash/src/network/message.rs:927:msg.map(Some)dash-spv/src/network/peer.rs:138:Err(e) => Err(e),dash-spv/src/network/manager.rs:1327:let retried = broker.requeue_from(&culprits).await;dash-spv/src/network/broker.rs:14:const KICKING_ATTEMPTS: u32 = 2;dash-spv/src/network/manager.rs:1238:silent.sort_by_key(|&(since, p, _)| (since, p.id.addr()));dash-spv/src/network/manager.rs:2869:for second in 0..secs as usize {dash-spv/src/network/manager.rs:2870:tokio::time::advance(TIMEOUT_CHECK).await;dash-spv/src/network/broker.rs:45:pub fn request_keys(msg: &NetworkMessage) -> Vec<RequestKey> {dash-spv/src/network/broker.rs:364:if peer.send(&msg).await.is_ok() {dash-spv/src/network/broker.rs:388:*slot = ReqState::OnWire(Box::new(OnWire {dash-spv/src/network/manager.rs:2083:fn headers_with_a_transaction() -> Vec<u8> {dash/src/network/message.rs:819:if u8::consensus_decode(r)? != 0u8 {dash-spv/src/network/manager.rs:1321:let (kicked, remaining) = connected.remove(&culprits).await;dash-spv/src/network/bans.rs:44:if self.configured.contains(&addr) && !matches!(ban, Ban::DialFailed) {dash-spv/src/network/bans.rs:60:Ban::Kicked => (&mut entry.banned_until, KICK_BAN),dash-spv/src/network/bans.rs:67:*until = (*until).max(now + duration);dash-spv/src/network/manager.rs:986:if self.state.bans.is_banned(peer.addr()).await {
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
There was a problem hiding this comment.
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.
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.
|
✅ Review complete in 10m 4s Planner (4s) Review (behavior · full): 10 findings Judge (6m 17s) Posted: 2 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
|
`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.
There was a problem hiding this comment.
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
- Fatal frame failures may bypass reconnect backoff ·
dash-spv/src/network/peer.rs:784
Trigger 3 of 10, below the cut-off of 4.
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-5andgpt-6.2-sol, judged byclaude-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; |
There was a problem hiding this comment.
✨ 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
rust-dashcore/dash-spv/src/network/manager.rs
Lines 2206 to 2210 in 8971b56
Is the eviction line whose removal fails this assertion
rust-dashcore/dash-spv/src/network/manager.rs
Lines 247 to 251 in 8971b56
- Create an issue for this
- Dismiss this finding
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.
|
✅ Review complete in 12m 58s Planner (5s) Review (behavior · full): 14 findings Judge (7m 41s) Posted: 6 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
Last reviewed
|
There was a problem hiding this comment.
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 atpeer.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-5andgpt-6.2-sol, judged byclaude-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 { |
There was a problem hiding this comment.
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
skippedonce per reader and dash-spv/src/network/peer.rs:807 increments it for every skipped frame.
rust-dashcore/dash-spv/src/network/peer.rs
Lines 775 to 779 in e32e805
skipped += 1; runs on every Frame::Skipped, whatever its command or how much time has passed.
rust-dashcore/dash-spv/src/network/peer.rs
Lines 806 to 810 in e32e805
const KICK_BAN: Duration = Duration::from_secs(10 * 60);, and bans.rs:60 maps Ban::Kicked to it.
rust-dashcore/dash-spv/src/network/bans.rs
Lines 8 to 12 in e32e805
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) { |
There was a problem hiding this comment.
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.
rust-dashcore/dash-spv/src/network/broker.rs
Lines 274 to 278 in e32e805
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.
rust-dashcore/dash-spv/src/network/broker.rs
Lines 308 to 312 in e32e805
Refreshes the same timestamps for successful replies to other work.
rust-dashcore/dash-spv/src/network/manager.rs
Lines 1426 to 1430 in e32e805
dash-spv/src/network/manager.rs:2985: Sends a valid replacement reply before advancing the clock, so the new test never exercises a retry at the deadline.dash-spv/src/network/broker.rs:332:let silent_since = if now.duration_since(o.last_answer) > timeout * ANSWER_TIMEOUTS {dash-spv/src/network/broker.rs:14:const KICKING_ATTEMPTS: u32 = 2;dash-spv/src/network/broker.rs:215:reqs.insert(key, ReqState::Queued(o.attempts));dash-spv/src/network/broker.rs:433:attempts: attempts + 1,dash-spv/src/network/peer.rs:95:pub(super) const MAX_SKIPPED_FRAMES: u32 = 100;dash-spv/src/network/peer.rs:826-841:if skipped == MAX_SKIPPED_FRAMES {dash-spv/src/network/broker.rs:459:let o = lowest_on_wire(&mut reqs, |key| matches!(key, RequestKey::Block(_)))?;dash-spv/src/network/broker.rs:484:ReqState::OnWire(o) if matches!(key, RequestKey::CFilters(_)) => {dash-spv/src/network/manager.rs:1534-1535:PeerEvent::Undecodable(peer, command) => {dash-spv/src/network/manager.rs:1435:broker.progress(peer).await;dash-spv/src/network/broker.rs:336-340:} else if now.duration_since(o.last_progress) > timeout {dash-spv/src/sync/masternodes/pipeline.rs:126-127:let wanted = self.wanted.remove(&target)?;dash-spv/src/network/broker.rs:162-163:if keys.iter().any(|k| reqs.contains_key(k)) {
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; |
There was a problem hiding this comment.
✨ 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…
rust-dashcore/dash-spv/src/network/manager.rs
Lines 1426 to 1430 in e32e805
not_found only requeues matching keys and never calls progress
rust-dashcore/dash-spv/src/network/broker.rs
Lines 237 to 241 in e32e805
arrived settles the key and wakes the router, with no progress call
rust-dashcore/dash-spv/src/network/broker.rs
Lines 255 to 259 in e32e805
dash-spv/src/network/peer.rs:836:PeerEvent::Undecodableis sent for any named command that fails to decode
- 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) => { |
There was a problem hiding this comment.
✨ 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")
rust-dashcore/dash-spv/src/network/broker.rs
Lines 49 to 53 in e32e805
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…
rust-dashcore/dash-spv/src/network/costs.rs
Lines 286 to 290 in e32e805
arrived ignores a reply from a peer that is neither the carrier nor a hedge, so the requeued copy is sent and downloaded again.
rust-dashcore/dash-spv/src/network/broker.rs
Lines 258 to 262 in e32e805
dash-spv/src/network/costs.rs:97: MarksCfHeaders,CFiltersandBlockas in order, and dash-spv/src/network/costs.rs:303 removes earlier entries of any of those kinds when a garbled block…dash-spv/src/network/costs.rs:315: Feedsa.bytesinto the shared response-cost estimator even on the failure path.dash-spv/src/network/costs.rs:293:self.complete(&mut awaited, i);dash-spv/src/network/costs.rs:303:awaited.drain(..i).partition(|earlier| earlier.reply.in_order());- dashpay/dips:dip-0025.md:147 permits
headers2both as a reply and as an unsolicited announcement.
- 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: {}", |
There was a problem hiding this comment.
✨ 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.
rust-dashcore/dash/src/network/message.rs
Lines 137 to 141 in e32e805
Decodes the command using CommandString::consensus_decode after a frame fails.
rust-dashcore/dash-spv/src/network/peer.rs
Lines 146 to 150 in e32e805
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.
rust-dashcore/dash-spv/src/network/peer.rs
Lines 807 to 811 in e32e805
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 Report❌ Patch coverage is 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
|
Any message that failed to decode banned its sender for 24 hours and dropped the connection, and so did a
headers2message 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.RawNetworkMessageCodecnow 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 overMAX_MSG_SIZEor 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
cfiltercounts as an answer without closing its batch, and the filters pipeline requests an incomplete batch again.A
headers2decompression 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