Skip to main content

reth_eth_wire_types/snap/
mod.rs

1//! Implements Ethereum SNAP message types.
2//! Snap protocol runs on top of `RLPx`
3//! facilitating the exchange of Ethereum state snapshots between peers
4//! Reference: [Ethereum Snapshot Protocol](https://github.com/ethereum/devp2p/blob/master/caps/snap.md#protocol-messages)
5//!
6//! This module implements the snap/2 (EIP-8189) message definitions.
7
8use alloc::vec::Vec;
9use alloy_primitives::Bytes;
10use alloy_rlp::{Decodable, Encodable};
11
12mod account;
13pub use account::{AccountData, SlimAccountBody};
14
15mod messages;
16pub use messages::{
17    AccountRangeMessage, BlockAccessListsMessage, ByteCodesMessage, GetAccountRangeMessage,
18    GetBlockAccessListsMessage, GetByteCodesMessage, GetStorageRangesMessage, RangeBound,
19    StorageData, StorageRangesMessage,
20};
21
22/// Supported SNAP protocol versions.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[repr(u8)]
26pub enum SnapVersion {
27    /// BAL-based healing as proposed by EIP-8189.
28    #[default]
29    V2 = 2,
30}
31
32impl SnapVersion {
33    /// Returns the protocol message slot length for this version (not the count of valid ids; use
34    /// [`Self::supports_message_id`] to check validity).
35    pub const fn message_count(self) -> u8 {
36        match self {
37            Self::V2 => 10,
38        }
39    }
40
41    /// Returns `true` if `id` is a valid `snap/2` message id.
42    ///
43    /// snap/2 (EIP-8189) drops trie nodes (`0x06`/`0x07`) and adds BAL (`0x08`/`0x09`),
44    /// so validity is not a contiguous range.
45    pub const fn supports_message_id(self, id: u8) -> bool {
46        match self {
47            // snap/2: 0x00..=0x05 plus BAL (0x08/0x09). TrieNodes (0x06/0x07) removed.
48            Self::V2 => {
49                id <= SnapMessageId::ByteCodes as u8 ||
50                    id == SnapMessageId::GetBlockAccessLists as u8 ||
51                    id == SnapMessageId::BlockAccessLists as u8
52            }
53        }
54    }
55}
56
57/// Message IDs for the snap sync protocol
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SnapMessageId {
60    /// Requests of an unknown number of accounts from a given account trie.
61    GetAccountRange = 0x00,
62    /// Response with the number of consecutive accounts and the Merkle proofs for the entire
63    /// range.
64    AccountRange = 0x01,
65    /// Requests for the storage slots of multiple accounts' storage tries.
66    GetStorageRanges = 0x02,
67    /// Response for the number of consecutive storage slots for the requested account.
68    StorageRanges = 0x03,
69    /// Request of the number of contract byte-codes by hash.
70    GetByteCodes = 0x04,
71    /// Response for the number of requested contract codes.
72    ByteCodes = 0x05,
73    /// Request BALs for a list of block hashes.
74    GetBlockAccessLists = 0x08,
75    /// Response containing BALs for the requested block hashes.
76    BlockAccessLists = 0x09,
77}
78
79impl SnapMessageId {
80    /// Returns the message id of the response paired with this request, or `None` if this id is
81    /// itself a response.
82    pub const fn response(self) -> Option<Self> {
83        match self {
84            Self::GetAccountRange => Some(Self::AccountRange),
85            Self::GetStorageRanges => Some(Self::StorageRanges),
86            Self::GetByteCodes => Some(Self::ByteCodes),
87            Self::GetBlockAccessLists => Some(Self::BlockAccessLists),
88            Self::AccountRange | Self::StorageRanges | Self::ByteCodes | Self::BlockAccessLists => {
89                None
90            }
91        }
92    }
93}
94
95/// Represents all types of messages in the snap sync protocol.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum SnapProtocolMessage {
98    /// Request for an account range - see [`GetAccountRangeMessage`]
99    GetAccountRange(GetAccountRangeMessage),
100    /// Response with accounts and proofs - see [`AccountRangeMessage`]
101    AccountRange(AccountRangeMessage),
102    /// Request for storage slots - see [`GetStorageRangesMessage`]
103    GetStorageRanges(GetStorageRangesMessage),
104    /// Response with storage slots - see [`StorageRangesMessage`]
105    StorageRanges(StorageRangesMessage),
106    /// Request for contract bytecodes - see [`GetByteCodesMessage`]
107    GetByteCodes(GetByteCodesMessage),
108    /// Response with contract codes - see [`ByteCodesMessage`]
109    ByteCodes(ByteCodesMessage),
110    /// Request for block access lists - see [`GetBlockAccessListsMessage`]
111    GetBlockAccessLists(GetBlockAccessListsMessage),
112    /// Response with block access lists - see [`BlockAccessListsMessage`]
113    BlockAccessLists(BlockAccessListsMessage),
114}
115
116/// Error decoding an inbound `snap` protocol message from its framed bytes, or matching a response
117/// to its request.
118#[derive(thiserror::Error, Debug)]
119pub enum SnapProtocolError {
120    /// The payload was empty and carried no message id.
121    #[error("empty snap message")]
122    Empty,
123    /// The message id is not valid for the negotiated snap version (e.g. the removed trie-node
124    /// messages `0x06`/`0x07` under snap/2).
125    #[error("message id {0:#x} is invalid for snap/{1:?}")]
126    UnsupportedMessageId(u8, SnapVersion),
127    /// Decoding the RLP message body failed.
128    #[error("RLP error: {0}")]
129    Rlp(#[from] alloy_rlp::Error),
130    /// The response answers no request sent on this connection.
131    ///
132    /// The response is rejected before its body is decoded.
133    #[error("received unsolicited {message_id:?} response with request id {request_id}")]
134    UnsolicitedResponse {
135        /// The message id of the response.
136        message_id: SnapMessageId,
137        /// The request id the response carried.
138        request_id: u64,
139    },
140    /// A list in the response is longer than its request allows: more entries than requested, or
141    /// more range proof nodes than two boundary paths can hold.
142    ///
143    /// The response is rejected before its body is decoded.
144    #[error(
145        "{message_id:?} response with request id {request_id} holds a list longer than the {max_items} items its request allows"
146    )]
147    ResponseExceedsRequest {
148        /// The message id of the response.
149        message_id: SnapMessageId,
150        /// The request id the response carried.
151        request_id: u64,
152        /// The longest the list may be.
153        max_items: usize,
154    },
155}
156
157impl SnapProtocolMessage {
158    /// Returns the protocol message ID for this message type.
159    ///
160    /// The message ID is used in the `RLPx` protocol to identify different types of messages.
161    pub const fn message_id(&self) -> SnapMessageId {
162        match self {
163            Self::GetAccountRange(_) => SnapMessageId::GetAccountRange,
164            Self::AccountRange(_) => SnapMessageId::AccountRange,
165            Self::GetStorageRanges(_) => SnapMessageId::GetStorageRanges,
166            Self::StorageRanges(_) => SnapMessageId::StorageRanges,
167            Self::GetByteCodes(_) => SnapMessageId::GetByteCodes,
168            Self::ByteCodes(_) => SnapMessageId::ByteCodes,
169            Self::GetBlockAccessLists(_) => SnapMessageId::GetBlockAccessLists,
170            Self::BlockAccessLists(_) => SnapMessageId::BlockAccessLists,
171        }
172    }
173
174    /// Returns the `request_id` used to correlate this message with its request/response pair.
175    pub const fn request_id(&self) -> u64 {
176        match self {
177            Self::GetAccountRange(m) => m.request_id,
178            Self::AccountRange(m) => m.request_id,
179            Self::GetStorageRanges(m) => m.request_id,
180            Self::StorageRanges(m) => m.request_id,
181            Self::GetByteCodes(m) => m.request_id,
182            Self::ByteCodes(m) => m.request_id,
183            Self::GetBlockAccessLists(m) => m.request_id,
184            Self::BlockAccessLists(m) => m.request_id,
185        }
186    }
187
188    /// Returns `true` if this is a response message (as opposed to a request).
189    pub const fn is_response(&self) -> bool {
190        matches!(
191            self,
192            Self::AccountRange(_) |
193                Self::StorageRanges(_) |
194                Self::ByteCodes(_) |
195                Self::BlockAccessLists(_)
196        )
197    }
198
199    /// Overwrites the `request_id`, e.g. so a session can assign a connection-unique id before
200    /// sending a request.
201    pub const fn set_request_id(&mut self, request_id: u64) {
202        match self {
203            Self::GetAccountRange(m) => m.request_id = request_id,
204            Self::AccountRange(m) => m.request_id = request_id,
205            Self::GetStorageRanges(m) => m.request_id = request_id,
206            Self::StorageRanges(m) => m.request_id = request_id,
207            Self::GetByteCodes(m) => m.request_id = request_id,
208            Self::ByteCodes(m) => m.request_id = request_id,
209            Self::GetBlockAccessLists(m) => m.request_id = request_id,
210            Self::BlockAccessLists(m) => m.request_id = request_id,
211        }
212    }
213
214    /// Encode the message to bytes
215    pub fn encode(&self) -> Bytes {
216        let mut buf = Vec::new();
217        // Add message ID as first byte
218        buf.push(self.message_id() as u8);
219
220        // Encode the message body based on its type
221        match self {
222            Self::GetAccountRange(msg) => msg.encode(&mut buf),
223            Self::AccountRange(msg) => msg.encode(&mut buf),
224            Self::GetStorageRanges(msg) => msg.encode(&mut buf),
225            Self::StorageRanges(msg) => msg.encode(&mut buf),
226            Self::GetByteCodes(msg) => msg.encode(&mut buf),
227            Self::ByteCodes(msg) => msg.encode(&mut buf),
228            Self::GetBlockAccessLists(msg) => msg.encode(&mut buf),
229            Self::BlockAccessLists(msg) => msg.encode(&mut buf),
230        }
231
232        Bytes::from(buf)
233    }
234
235    /// Decodes a SNAP protocol message from its message ID and RLP-encoded body.
236    pub fn decode(message_id: u8, buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
237        // Decoding protocol message variants based on message ID
238        macro_rules! decode_snap_message_variant {
239            ($message_id:expr, $buf:expr, $id:expr, $variant:ident, $msg_type:ty) => {
240                if $message_id == $id as u8 {
241                    return Ok(Self::$variant(<$msg_type>::decode($buf)?));
242                }
243            };
244        }
245
246        // Try to decode each message type based on the message ID
247        decode_snap_message_variant!(
248            message_id,
249            buf,
250            SnapMessageId::GetAccountRange,
251            GetAccountRange,
252            GetAccountRangeMessage
253        );
254        decode_snap_message_variant!(
255            message_id,
256            buf,
257            SnapMessageId::AccountRange,
258            AccountRange,
259            AccountRangeMessage
260        );
261        decode_snap_message_variant!(
262            message_id,
263            buf,
264            SnapMessageId::GetStorageRanges,
265            GetStorageRanges,
266            GetStorageRangesMessage
267        );
268        decode_snap_message_variant!(
269            message_id,
270            buf,
271            SnapMessageId::StorageRanges,
272            StorageRanges,
273            StorageRangesMessage
274        );
275        decode_snap_message_variant!(
276            message_id,
277            buf,
278            SnapMessageId::GetByteCodes,
279            GetByteCodes,
280            GetByteCodesMessage
281        );
282        decode_snap_message_variant!(
283            message_id,
284            buf,
285            SnapMessageId::ByteCodes,
286            ByteCodes,
287            ByteCodesMessage
288        );
289        decode_snap_message_variant!(
290            message_id,
291            buf,
292            SnapMessageId::GetBlockAccessLists,
293            GetBlockAccessLists,
294            GetBlockAccessListsMessage
295        );
296        decode_snap_message_variant!(
297            message_id,
298            buf,
299            SnapMessageId::BlockAccessLists,
300            BlockAccessLists,
301            BlockAccessListsMessage
302        );
303
304        Err(alloy_rlp::Error::Custom("Unknown message ID"))
305    }
306
307    /// Decodes a framed snap message (`[id, body..]`), validating the id against `version`.
308    ///
309    /// Empty payload, invalid id, and malformed body are reported as distinct
310    /// [`SnapProtocolError`] variants.
311    pub fn decode_versioned(version: SnapVersion, bytes: &[u8]) -> Result<Self, SnapProtocolError> {
312        let (&id, mut body) = bytes.split_first().ok_or(SnapProtocolError::Empty)?;
313        if !version.supports_message_id(id) {
314            return Err(SnapProtocolError::UnsupportedMessageId(id, version));
315        }
316        let msg = Self::decode(id, &mut body)?;
317        if !body.is_empty() {
318            return Err(SnapProtocolError::Rlp(alloy_rlp::Error::UnexpectedLength));
319        }
320        Ok(msg)
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::BlockAccessLists;
328    use alloy_primitives::{B256, KECCAK256_EMPTY, U256};
329    use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH};
330    use test_case::test_case;
331
332    // Helper function to create a B256 from a u64 for testing
333    fn b256_from_u64(value: u64) -> B256 {
334        B256::left_padding_from(&value.to_be_bytes())
335    }
336
337    // Helper function to test roundtrip encoding/decoding
338    fn test_roundtrip(original: SnapProtocolMessage) {
339        let encoded = original.encode();
340
341        // Verify the first byte matches the expected message ID
342        assert_eq!(encoded[0], original.message_id() as u8);
343
344        let mut buf = &encoded[1..];
345        let decoded = SnapProtocolMessage::decode(encoded[0], &mut buf).unwrap();
346
347        // Verify the match
348        assert_eq!(decoded, original);
349    }
350
351    // geth's GetStorageRangesPacket types Origin/Limit as raw byte strings and sends them
352    // empty for the common unbounded multi-account request, rather than as 32-byte
353    // zero/max-value hashes. A conforming decoder must accept this raw packet shape.
354    #[derive(alloy_rlp::RlpEncodable)]
355    struct GethStorageRequest {
356        request_id: u64,
357        root_hash: B256,
358        account_hashes: Vec<B256>,
359        origin: Bytes,
360        limit: Bytes,
361        response_bytes: u64,
362    }
363
364    #[test]
365    fn test_all_message_roundtrips() {
366        assert_eq!(SnapVersion::V2.message_count(), 10);
367
368        test_roundtrip(SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
369            request_id: 42,
370            root_hash: b256_from_u64(123),
371            starting_hash: b256_from_u64(456),
372            limit_hash: b256_from_u64(789),
373            response_bytes: 1024,
374        }));
375
376        test_roundtrip(SnapProtocolMessage::AccountRange(AccountRangeMessage {
377            request_id: 42,
378            accounts: vec![AccountData::from_trie_account(
379                b256_from_u64(123),
380                &TrieAccount::new(7, U256::from(42), EMPTY_ROOT_HASH, KECCAK256_EMPTY),
381            )],
382            proof: vec![Bytes::from(vec![4, 5, 6])],
383        }));
384
385        test_roundtrip(SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
386            request_id: 42,
387            root_hash: b256_from_u64(123),
388            account_hashes: vec![b256_from_u64(456)],
389            starting_hash: b256_from_u64(789).into(),
390            limit_hash: b256_from_u64(101112).into(),
391            response_bytes: 2048,
392        }));
393
394        // Geth's empty-byte-string encoding for an unbounded storage range.
395        test_roundtrip(SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
396            request_id: 43,
397            root_hash: b256_from_u64(123),
398            account_hashes: vec![b256_from_u64(456), b256_from_u64(789)],
399            starting_hash: RangeBound::default(),
400            limit_hash: RangeBound::default(),
401            response_bytes: 2048,
402        }));
403
404        test_roundtrip(SnapProtocolMessage::StorageRanges(StorageRangesMessage {
405            request_id: 42,
406            slots: vec![vec![StorageData {
407                hash: b256_from_u64(123),
408                data: Bytes::from(vec![1, 2, 3]),
409            }]],
410            proof: vec![Bytes::from(vec![4, 5, 6])],
411        }));
412
413        test_roundtrip(SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
414            request_id: 42,
415            hashes: vec![b256_from_u64(123)],
416            response_bytes: 1024,
417        }));
418
419        test_roundtrip(SnapProtocolMessage::ByteCodes(ByteCodesMessage {
420            request_id: 42,
421            codes: vec![Bytes::from(vec![1, 2, 3])],
422        }));
423
424        test_roundtrip(SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
425            request_id: 42,
426            block_hashes: vec![b256_from_u64(123), b256_from_u64(456)],
427            response_bytes: 4096,
428        }));
429
430        test_roundtrip(SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
431            request_id: 42,
432            block_access_lists: BlockAccessLists(vec![
433                Some(Bytes::from_static(&[alloy_rlp::EMPTY_LIST_CODE])),
434                Some(Bytes::from_static(&[0xc1, alloy_rlp::EMPTY_LIST_CODE])),
435            ]),
436        }));
437    }
438
439    #[test]
440    fn test_unknown_message_id() {
441        // Create some random data
442        let data = Bytes::from(vec![1, 2, 3, 4]);
443        let mut buf = data.as_ref();
444
445        // Try to decode with an invalid message ID
446        let result = SnapProtocolMessage::decode(255, &mut buf);
447
448        assert!(result.is_err());
449        if let Err(e) = result {
450            assert_eq!(e.to_string(), "Unknown message ID");
451        }
452    }
453
454    #[test]
455    fn test_snap_v2_message_validity() {
456        let v2 = SnapVersion::V2;
457        // 0x00..=0x05 valid.
458        for id in 0x00..=0x05 {
459            assert!(v2.supports_message_id(id), "snap/2 should accept {id:#x}");
460        }
461        // Trie nodes (0x06/0x07) are removed in snap/2.
462        assert!(!v2.supports_message_id(0x06));
463        assert!(!v2.supports_message_id(0x07));
464        // BAL added in snap/2.
465        assert!(v2.supports_message_id(SnapMessageId::GetBlockAccessLists as u8));
466        assert!(v2.supports_message_id(SnapMessageId::BlockAccessLists as u8));
467        assert!(!v2.supports_message_id(0x0a));
468        assert!(!v2.supports_message_id(0xff));
469    }
470
471    #[test_case(
472        SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
473            request_id: 1, root_hash: B256::ZERO, starting_hash: B256::ZERO,
474            limit_hash: B256::ZERO, response_bytes: 0,
475        }), 1, false ; "get_account_range is a request"
476    )]
477    #[test_case(
478        SnapProtocolMessage::AccountRange(AccountRangeMessage {
479            request_id: 2, accounts: vec![], proof: vec![],
480        }), 2, true ; "account_range is a response"
481    )]
482    #[test_case(
483        SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
484            request_id: 3, root_hash: B256::ZERO, account_hashes: vec![],
485            starting_hash: B256::ZERO.into(), limit_hash: B256::ZERO.into(), response_bytes: 0,
486        }), 3, false ; "get_storage_ranges is a request"
487    )]
488    #[test_case(
489        SnapProtocolMessage::StorageRanges(StorageRangesMessage {
490            request_id: 4, slots: vec![], proof: vec![],
491        }), 4, true ; "storage_ranges is a response"
492    )]
493    #[test_case(
494        SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
495            request_id: 5, hashes: vec![], response_bytes: 0,
496        }), 5, false ; "get_byte_codes is a request"
497    )]
498    #[test_case(
499        SnapProtocolMessage::ByteCodes(ByteCodesMessage { request_id: 6, codes: vec![] }),
500        6, true ; "byte_codes is a response"
501    )]
502    #[test_case(
503        SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
504            request_id: 7, block_hashes: vec![], response_bytes: 0,
505        }), 7, false ; "get_block_access_lists is a request"
506    )]
507    #[test_case(
508        SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
509            request_id: 8, block_access_lists: BlockAccessLists(vec![]),
510        }), 8, true ; "block_access_lists is a response"
511    )]
512    fn request_id_and_is_response(msg: SnapProtocolMessage, expected_id: u64, is_response: bool) {
513        assert_eq!(msg.request_id(), expected_id);
514        assert_eq!(msg.is_response(), is_response);
515    }
516
517    #[test_case(
518        SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
519            request_id: 1, root_hash: B256::ZERO, starting_hash: B256::ZERO,
520            limit_hash: B256::ZERO, response_bytes: 0,
521        }) ; "get_account_range"
522    )]
523    #[test_case(
524        SnapProtocolMessage::AccountRange(AccountRangeMessage {
525            request_id: 1, accounts: vec![], proof: vec![],
526        }) ; "account_range"
527    )]
528    #[test_case(
529        SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
530            request_id: 1, root_hash: B256::ZERO, account_hashes: vec![],
531            starting_hash: B256::ZERO.into(), limit_hash: B256::ZERO.into(), response_bytes: 0,
532        }) ; "get_storage_ranges"
533    )]
534    #[test_case(
535        SnapProtocolMessage::StorageRanges(StorageRangesMessage {
536            request_id: 1, slots: vec![], proof: vec![],
537        }) ; "storage_ranges"
538    )]
539    #[test_case(
540        SnapProtocolMessage::GetByteCodes(GetByteCodesMessage {
541            request_id: 1, hashes: vec![], response_bytes: 0,
542        }) ; "get_byte_codes"
543    )]
544    #[test_case(
545        SnapProtocolMessage::ByteCodes(ByteCodesMessage { request_id: 1, codes: vec![] }) ;
546        "byte_codes"
547    )]
548    #[test_case(
549        SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
550            request_id: 1, block_hashes: vec![], response_bytes: 0,
551        }) ; "get_block_access_lists"
552    )]
553    #[test_case(
554        SnapProtocolMessage::BlockAccessLists(BlockAccessListsMessage {
555            request_id: 1, block_access_lists: BlockAccessLists(vec![]),
556        }) ; "block_access_lists"
557    )]
558    fn per_variant_request_id_and_round_trip(mut msg: SnapProtocolMessage) {
559        // set_request_id overwrites the id for every variant.
560        msg.set_request_id(42);
561        assert_eq!(msg.request_id(), 42);
562
563        // decode_versioned round-trips every valid snap/2 id.
564        let decoded =
565            SnapProtocolMessage::decode_versioned(SnapVersion::V2, &msg.encode()).unwrap();
566        assert_eq!(decoded, msg);
567    }
568
569    #[test]
570    fn decode_versioned_rejects_empty() {
571        // An empty payload carries no message id and is distinct from an invalid id.
572        assert!(matches!(
573            SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[]),
574            Err(SnapProtocolError::Empty)
575        ));
576    }
577
578    #[test]
579    fn decode_versioned_rejects_trie_node_ids_in_v2() {
580        // snap/2 (EIP-8189) removes trie nodes (`0x06`/`0x07`); decoding must reject them as an
581        // unsupported id rather than a malformed body.
582        for id in [0x06u8, 0x07] {
583            assert!(matches!(
584                SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[id]),
585                Err(SnapProtocolError::UnsupportedMessageId(got, SnapVersion::V2)) if got == id
586            ));
587        }
588    }
589
590    #[test]
591    fn decode_versioned_reports_malformed_body() {
592        // A valid id (GetBlockAccessLists, 0x08) with a non-decodable body is an RLP error, not an
593        // unsupported id.
594        assert!(matches!(
595            SnapProtocolMessage::decode_versioned(SnapVersion::V2, &[0x08, 0xff]),
596            Err(SnapProtocolError::Rlp(_))
597        ));
598    }
599
600    #[test]
601    fn decode_versioned_rejects_trailing_bytes() {
602        // A valid framed message with junk appended after the RLP body must be rejected rather
603        // than silently decoded.
604        let original = SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
605            request_id: 7,
606            block_hashes: vec![b256_from_u64(1)],
607            response_bytes: 1024,
608        });
609        let mut framed = original.encode().to_vec();
610        framed.push(0xff);
611        assert!(matches!(
612            SnapProtocolMessage::decode_versioned(SnapVersion::V2, &framed),
613            Err(SnapProtocolError::Rlp(alloy_rlp::Error::UnexpectedLength))
614        ));
615    }
616
617    #[test]
618    fn get_storage_ranges_decodes_geths_empty_origin_and_limit() {
619        let body = alloy_rlp::encode(GethStorageRequest {
620            request_id: 21,
621            root_hash: B256::ZERO,
622            account_hashes: vec![B256::repeat_byte(1), B256::repeat_byte(2)],
623            origin: Bytes::new(),
624            limit: Bytes::new(),
625            response_bytes: 1024,
626        });
627        let mut framed = vec![SnapMessageId::GetStorageRanges as u8];
628        framed.extend_from_slice(&body);
629
630        let decoded = SnapProtocolMessage::decode_versioned(SnapVersion::V2, &framed).unwrap();
631        let SnapProtocolMessage::GetStorageRanges(msg) = decoded else {
632            panic!("expected a GetStorageRanges message");
633        };
634        assert_eq!(msg.starting_hash.unwrap_or(B256::ZERO), B256::ZERO);
635        assert_eq!(msg.limit_hash.unwrap_or(B256::repeat_byte(0xff)), B256::repeat_byte(0xff));
636    }
637}