Skip to content

refactor(dash-spv): drop unreachable WouldBlock/TimedOut - #753

Merged
xdustinface merged 1 commit into
v0.42-devfrom
refactor/drop-unreachable-async-read-arms
May 14, 2026
Merged

xdustinface merged 1 commit into
v0.42-devfrom
refactor/drop-unreachable-async-read-arms

Conversation

@xdustinface

@xdustinface xdustinface commented May 10, 2026 •

Copy link
Copy Markdown
Collaborator

Tokio's AsyncReadExt::read consumes WouldBlock inside the runtime, so the future never resolves with that error kind. Read timeouts are imposed via tokio::time::timeout(..) and surface as Elapsed, not io::Error::TimedOut. The four match blocks in Peer::receive_message's framing loop kept arms for both kinds, all of which were dead code.

Drop the eight unreachable arms. The remaining Ok(0), Ok(_), ConnectionAborted/ConnectionReset, and catch-all Err(e) arms continue to surface real errors, with the catch-all converting any unanticipated io::Error into NetworkError::ConnectionFailed rather than silently masking it.

Summary by CodeRabbit

  • Bug Fixes
    • Improved network error handling to properly distinguish temporary communication timeouts from actual connection failures, enhancing system reliability, error reporting accuracy, and diagnostic capabilities for peer-to-peer network operations.

Review Change Stack

Tokio's `AsyncReadExt::read` consumes `WouldBlock` inside the runtime, so the future never resolves with that error kind. Read timeouts are imposed via `tokio::time::timeout(..)` and surface as `Elapsed`, not `io::Error::TimedOut`. The four `match` blocks in `Peer::receive_message`'s framing loop kept arms for both kinds, all of which were dead code.

Drop the eight unreachable arms. The remaining `Ok(0)`, `Ok(_)`, `ConnectionAborted`/`ConnectionReset`, and catch-all `Err(e)` arms continue to surface real errors, with the catch-all converting any unanticipated `io::Error` into `NetworkError::ConnectionFailed` rather than silently masking it.
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cf47fa5e-1052-4ff9-8062-4acccdd6b94f

📥 Commits

Reviewing files that changed from the base of the PR and between dca03ce and bb02633.

📒 Files selected for processing (1)
  • dash-spv/src/network/peer.rs
💤 Files with no reviewable changes (1)
  • dash-spv/src/network/peer.rs

📝 Walkthrough

Walkthrough

The PR removes special-case error handling in the Peer::receive_message method. Four read operations no longer treat timeout-like I/O errors (WouldBlock, TimedOut) as benign "no data available" conditions; instead, those errors now propagate through existing error branches, resulting in ConnectionFailed rather than Ok(None).

Changes

Peer Message Read Error Handling

Layer / File(s) Summary
Remove WouldBlock/TimedOut Exception Handling
dash-spv/src/network/peer.rs
Four dedicated error match arms handling ErrorKind::WouldBlock and ErrorKind::TimedOut in separate read contexts (framing header loop, resync search, header buffer fill, frame buffer fill) are removed, allowing those transient timeout conditions to propagate as ConnectionFailed instead of returning Ok(None).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A rabbit hops through error streams so bright,
Timeouts no longer hide in gentle night—
Let WouldBlock fall through, let TimedOut show,
Connection truth will reap what we now sow! 🌙

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically summarizes the main change: removing unreachable error handling code for WouldBlock and TimedOut conditions from the async message reading logic.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/drop-unreachable-async-read-arms

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 72.23%. Comparing base (dca03ce) to head (bb02633).

Additional details and impacted files
@@            Coverage Diff             @@
##           v0.42-dev     #753   +/-   ##
==========================================
  Coverage      72.22%   72.23%           
==========================================
  Files            320      320           
  Lines          69631    69615   -16     
==========================================
- Hits           50294    50287    -7     
+ Misses         19337    19328    -9     
Flag Coverage Δ
core 76.30% <ø> (ø)
ffi 45.28% <ø> (ø)
rpc 20.00% <ø> (ø)
spv 89.86% <ø> (+0.04%) ⬆️
wallet 71.22% <ø> (ø)
Files with missing lines Coverage Δ
dash-spv/src/network/peer.rs 61.63% <ø> (+1.55%) ⬆️

... and 5 files with indirect coverage changes

@github-actions github-actions Bot added the ready-for-review CodeRabbit has approved this PR label May 10, 2026
@xdustinface
xdustinface requested a review from ZocoLini May 12, 2026 05:08
@xdustinface
xdustinface merged commit 3281616 into v0.42-dev May 14, 2026
40 checks passed
@xdustinface
xdustinface deleted the refactor/drop-unreachable-async-read-arms branch May 14, 2026 22:01
PastaPastaPasta added a commit that referenced this pull request Sep 20, 2026
`V2Transport::encode_message` built the extended-format command field from
`NetworkMessage::cmd()`, which returns the static string "unknown" for
`NetworkMessage::Unknown`. Any message without a dedicated variant was
therefore sent to the peer as command "unknown" instead of its real name,
while V1 framing (via `RawNetworkMessage::command()`) preserved it.

Switch to `command()`, make `encode_message`/`decode_message` associated
functions so the unit tests exercise the real encoder and decoder rather
than a hand-copied re-implementation, and add round-trip coverage for
Unknown messages plus truncated / reserved-ID inputs.

Also drop the `WouldBlock` / `TimedOut` arms from the receive loop, matching
the V1 path after #753: tokio's `AsyncReadExt::read` never surfaces those
kinds, so the arms were dead code.
PastaPastaPasta added a commit that referenced this pull request Oct 19, 2026
`V2Transport::encode_message` built the extended-format command field from
`NetworkMessage::cmd()`, which returns the static string "unknown" for
`NetworkMessage::Unknown`. Any message without a dedicated variant was
therefore sent to the peer as command "unknown" instead of its real name,
while V1 framing (via `RawNetworkMessage::command()`) preserved it.

Switch to `command()`, make `encode_message`/`decode_message` associated
functions so the unit tests exercise the real encoder and decoder rather
than a hand-copied re-implementation, and add round-trip coverage for
Unknown messages plus truncated / reserved-ID inputs.

Also drop the `WouldBlock` / `TimedOut` arms from the receive loop, matching
the V1 path after #753: tokio's `AsyncReadExt::read` never surfaces those
kinds, so the arms were dead code.
PastaPastaPasta added a commit that referenced this pull request Oct 29, 2026
`V2Transport::encode_message` built the extended-format command field from
`NetworkMessage::cmd()`, which returns the static string "unknown" for
`NetworkMessage::Unknown`. Any message without a dedicated variant was
therefore sent to the peer as command "unknown" instead of its real name,
while V1 framing (via `RawNetworkMessage::command()`) preserved it.

Switch to `command()`, make `encode_message`/`decode_message` associated
functions so the unit tests exercise the real encoder and decoder rather
than a hand-copied re-implementation, and add round-trip coverage for
Unknown messages plus truncated / reserved-ID inputs.

Also drop the `WouldBlock` / `TimedOut` arms from the receive loop, matching
the V1 path after #753: tokio's `AsyncReadExt::read` never surfaces those
kinds, so the arms were dead code.
xdustinface pushed a commit that referenced this pull request Nov 2, 2026
* feat(dash-spv): Add BIP324 v2 encrypted P2P transport

Implement BIP324 encrypted transport for dash-spv peer connections:

- Add Transport trait abstracting v1/v2 protocol differences
- Implement V1Transport (extracted from existing peer.rs code)
- Implement V2Transport with ChaCha20-Poly1305 encryption
- Add V2 handshake with ElligatorSwift key exchange
- Add Dash-specific short message IDs (128-167)
- Add TransportPreference config (V2Preferred, V2Only, V1Only)
- Default to V2Preferred with automatic fallback to v1

Key implementation details:
- Cache decrypted packet length to prevent cipher state desync
- Support all Dash short IDs matching Dash Core's V2_DASH_IDS
- Proper handling of bip324 crate's packet type header byte

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(dashcore): Extract payload serialization for V2 transport reuse

Add consensus_encode_payload() and consensus_decode_payload() methods to
NetworkMessage, enabling V2 (BIP324) transport to use dashcore's canonical
message serialization instead of duplicating ~400 lines of encoding logic.

Changes:
- Add NetworkMessage::consensus_encode_payload() for payload-only serialization
- Add NetworkMessage::consensus_decode_payload(cmd, payload) for decoding
- Refactor RawNetworkMessage encode/decode to use new methods
- Remove duplicated serialize_payload, deserialize_headers, decode_by_command
  from V2Transport (~380 lines removed)

This ensures Headers messages are properly serialized with trailing zero byte
(transaction count) and validates during deserialization that it equals 0.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore(dash-spv): Remove unused TransportEstablishResult enum

Dead code that was never integrated - V2HandshakeResult already serves
this purpose in the actual transport establishment flow.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(dash-spv): Improve V2 handshake session_id and decoy handling

- Use cipher.id() for actual BIP324 session ID instead of zeros
- Handle decoy packets by looping until genuine version packet received
- Add documentation explaining why we use bip324's low-level API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(dash-spv): Remove redundant garbage buffer size check

bip324 crate already enforces the max garbage limit internally and
returns NoGarbageTerminator error if exceeded. No need to duplicate
the check in dash-spv.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(dash-spv): Resolve clippy warnings in network module

- Remove unused consecutive_resyncs field from Peer (V1Transport has its own)
- Simplify match_single_binding to direct let binding
- Box V2Session in V2HandshakeResult to fix large_enum_variant warning

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: Add BIP324 V2 transport tests

Add comprehensive tests for the BIP324 V2 encrypted transport:

- message.rs: 4 tests for consensus_encode_payload/consensus_decode_payload
  round-trips covering standard Bitcoin, Dash-specific, empty payload,
  and Headers special encoding

- message_ids.rs: 1 test for bidirectional short ID mapping consistency

- v2.rs: 2 tests for V2 message framing (short format and extended format)

- handshake_test.rs: 1 integration test for V2Preferred fallback behavior

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: Add regression test for Unknown message payload encoding

Add test that exposes a bug in consensus_encode_payload for Unknown
message variants - serialize(data) adds a VarInt length prefix but
consensus_decode_payload expects raw bytes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: Return raw bytes for Unknown message payload encoding

Fix consensus_encode_payload for Unknown message variants to return
the raw payload bytes directly instead of using serialize() which
adds a VarInt length prefix. This matches consensus_decode_payload
which expects raw bytes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(dash-spv): preserve Unknown command names on the V2 wire

`V2Transport::encode_message` built the extended-format command field from
`NetworkMessage::cmd()`, which returns the static string "unknown" for
`NetworkMessage::Unknown`. Any message without a dedicated variant was
therefore sent to the peer as command "unknown" instead of its real name,
while V1 framing (via `RawNetworkMessage::command()`) preserved it.

Switch to `command()`, make `encode_message`/`decode_message` associated
functions so the unit tests exercise the real encoder and decoder rather
than a hand-copied re-implementation, and add round-trip coverage for
Unknown messages plus truncated / reserved-ID inputs.

Also drop the `WouldBlock` / `TimedOut` arms from the receive loop, matching
the V1 path after #753: tokio's `AsyncReadExt::read` never surfaces those
kinds, so the arms were dead code.

* fix(dash-spv): don't drop ciphertext read past the V2 version packet

The handshake reads the version packet in 64-byte chunks, so when the
peer's first application packet arrives in the same TCP segment the
trailing bytes ended up in `leftover_data` and were thrown away when the
handshake returned. The transport then started reading mid-packet, the
length decryption desynchronised the cipher, and the connection stalled
until the caller timed out.

Carry the surplus bytes in `V2Session::pending` and seed
`V2Transport`'s receive buffer with them. `V2Transport::new` now takes the
whole session, so the transport can't be constructed without them.

Add `tests/v2_transport.rs`, a loopback suite that runs the real handshake
and cipher on both ends of a local socket (no dashd required):
- V2Only round-trips a BIP324 short ID, a Dash short ID (128+) and an
  Unknown command, and observes EOF as a disconnect;
- V2Preferred falls back to V1 both when the peer answers with V1 magic and
  when it hangs up on the V2 key (Dash Core's behaviour);
- V2Only refuses a V1-only peer with `V2NotSupported`;
- V1Only never puts a V2 key on the wire.
The first of these reproduced the lost-bytes bug before the fix.

Also correct the module docs: the peek-based V1 detection avoids a
decryption failure, but the caller still reconnects for V1 because the
peer has already consumed our key bytes.

* fix(dash-spv): drop V2 session on unrecoverable cipher errors

Once decrypt_packet_len has consumed the length bytes, or a packet fails
authentication, the inbound cipher state can't be resynchronised, so mark
the transport disconnected instead of leaving a dead session looking
alive.

Run the V2 loopback suite on mainnet, testnet and regtest, since the
handshake and V1-magic detection depend on the network magic, and add a
tampered-packet case covering the disconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(dash-spv): port the V2 transport onto the rewritten network module

dev's network rewrite (#902) replaced the old `Peer` with a split socket:
a `FramedRead` over the read half and a locked write half. The `Transport`
trait no longer fits, so V2 now plugs into that design:

- `V2Decoder` is a tokio-util codec. It caches the decrypted length across
  partial reads, skips decoys, and drops what Dash Core drops: unassigned
  short IDs and malformed extended commands. Cipher errors disconnect and
  ban, like V1 decode errors.
- `PeerWriter` frames each message for its transport. The outbound cipher
  sits behind the same lock as the socket, so packets are encrypted in
  write order.
- `open_link` runs the BIP324 handshake and reconnects over V1 only for
  `V2Preferred`, and only when the handshake itself fails or the peer
  answered with V1 magic. Timeouts and connect errors are propagated.
- Ciphertext the handshake read past its version packet is chained ahead
  of the socket, so it's decoded before the next read rather than waiting
  for the peer to send more.
- `ClientConfig::transport_preference` reaches peers via `NetworkState`.

`V1Transport` is gone, since dashcore's `RawNetworkMessageCodec` now does
V1 framing. The loopback tests drive `PeerNetworkManager` against mock V1
and V2 peers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(dash-spv): don't link V2Decoder's docs to the private decode_message

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build(deps): depend on bip324 0.11 from crates.io

Replace the git rev pin with the released 0.11, declared in the root
workspace dependencies next to the other rust-bitcoin crates. dash-spv
enables its `tokio` feature for `bip324::futures::handshake`.

bip324 0.11 brings in secp256k1 0.29 alongside the workspace's 0.33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(dash): encode and decode BIP324 V2 contents with Dash Core's short IDs

Add NetworkMessage::consensus_encode_v2 / consensus_decode_v2 next to
cmd() and consensus_encode_payload. The short ID tables mirror
V2_BITCOIN_IDS and V2_DASH_IDS in Dash Core's net.cpp, empty slots
included: ID 5 stays empty, so feefilter uses the extended format, and
platformban is 168. Messages are looked up by command(). The extended
command is written with CommandString's Encodable impl.

Also hoist the test-body imports in message.rs to the test module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(dash-spv): use bip324's async handshake and dashcore's V2 encoding

Drop the hand-rolled V2HandshakeManager, V2HandshakeResult, V2Session,
the stream.peek() V1-magic probe and NetworkError::V2NotSupported. The
peer now splits the stream and runs bip324::futures::handshake on the
halves inside one 10 s timeout. PeerReader reads through
Either<ProtocolSessionReader<OwnedReadHalf>, OwnedReadHalf>, so the
crate replays the bytes the handshake read past the version packet.
V2Preferred reconnects over V1 when the crate flags a V1 retry
(reset/abort/EOF) or sees V1 magic in the key slot. Timeouts are not
retried.

message_ids.rs is gone in favour of dashcore's table. V2Decoder reads
the length without expect(). network::transport is private apart from
TransportPreference. The loopback test's mock peer runs
bip324::futures::handshake as the responder and checks the raw short
IDs on the wire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(dash-spv): set TCP_NODELAY on every peer socket and send BIP324 garbage

Move set_nodelay(true) into open(), so V1-only connections and the V1
fallback redial get it as well as V2 ones. lag_ms is measured from a
ping written right after other small writes, so with Nagle on only V1
peers, V1 and V2 peers were measured differently under V2Preferred.

Send 0..=4095 random garbage bytes after our key, as Dash Core's
GenerateRandomGarbage does, so a V2 connection's first flight isn't a
fixed 64 bytes.

Also make the V2 codec items pub(crate), drop a comment that repeated
the field doc, and run each loopback test on one network: they only
varied the magic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(dash): keep the payload codec private and fold its tests into the round trip

consensus_encode_payload / consensus_decode_payload are only used
inside message.rs, so make them private instead of new public API.

full_round_ser_der_raw_network_message_test already runs both through
RawNetworkMessage. Add the missing variants to it (GetMnListD, CLSig,
ISLock, GetHeaders2, SendHeaders2, empty and multi-header Headers,
Unknown) plus a V2 round trip per message. Then drop the duplicate
payload round-trip tests and trim the rest to the byte-level checks a
round trip can't catch.

consensus_encode_v2 now writes the extended command with
serialize(&command), matching the payload next to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-review CodeRabbit has approved this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants