Repository navigation
refactor(dash-spv): drop unreachable WouldBlock/TimedOut - #753
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
💤 Files with no reviewable changes (1)
📝 WalkthroughWalkthroughThe PR removes special-case error handling in the ChangesPeer Message Read Error Handling
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. 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
|
`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.
`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.
`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.
* 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>
Tokio's
AsyncReadExt::readconsumesWouldBlockinside the runtime, so the future never resolves with that error kind. Read timeouts are imposed viatokio::time::timeout(..)and surface asElapsed, notio::Error::TimedOut. The fourmatchblocks inPeer::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-allErr(e)arms continue to surface real errors, with the catch-all converting any unanticipatedio::ErrorintoNetworkError::ConnectionFailedrather than silently masking it.Summary by CodeRabbit